Commit Graph

1055 Commits

Author SHA1 Message Date
Víctor Falcón e6cb0459f6
fix(binance): value past days from Binance's own snapshot total (#763)
Last of the crypto-pricing family, after #759 and #761. The issues queue
has produced nothing new for four cycles, so this came out of reading
the code the logs pointed at.

## What was wrong

`syncHistoricalBalances` rebuilds past daily rows in `account_balances`
— the data behind the net-worth chart. It priced each holding by handing
its raw ticker to `CurrencyConversionService`:

```php
$converted = $this->currencyConverter->convert($asset, $targetCurrency, $quantity, $date);

if ($converted == 0.0) {
    $skippedAssets[$asset] = true;   // and the holding leaves the day's total
    continue;
}
```

That provider carries fiat currencies and a couple of majors. Everything
it did not recognise was dropped from the day's total, so an altcoin
portfolio produced a chart history far below what the user actually held
— while **today's** balance was correct, because the live path prices
through Binance's own tickers. The new test demonstrates it: a day
holding 10 SOL comes out as **0** on the old code.

I first went looking for the USD hop that fixed the Coinbase equivalent,
and there isn't one to add here — a past day needs a *dated* price, and
both the asset leg and any USD leg would come from the same provider
that does not know the asset.

## What it does instead

The snapshot already carried the answer and the service was throwing it
away. Binance sends `totalAssetOfBtc` — what it valued the whole spot
account at, on that day — in the same `data` object as the balances. One
BTC→fiat conversion, on the one ticker the rate provider always covers,
replaces the per-asset loop and covers every holding including the ones
nothing else can price.

Both are spot-only (`accountSnapshot?type=SPOT` and `api/v3/account`),
so historical and current days stay on the same basis — no discontinuity
at the join.

Second commit is a review follow-up: the day's balance now rests
entirely on that one field, so a response that stops carrying it gets
its own counter in the summary log rather than looking like a day with
no snapshot.

## ⚠️ Correction to the ops advice I gave in #759 and #761

I twice suggested `php artisan banking:sync --full` to repair the
understated Coinbase rows. **Do not run that unscoped.** With no filter
it forces `isFirstSync = true` for *every* active connection, which
would also rewrite up to 180 days of history for all 11 Binance accounts
in one shot as a side effect. `--connection=<id>` already exists — use
it:

```
php artisan banking:sync --full --connection=<coinbase-connection-id>
```

For Binance the same command is the repair, but it should be a
deliberate decision per connection, not collateral damage. **Nothing
repairs the existing 11 accounts automatically**: incremental sync only
fills the gap after `MAX(balance_date)` and never revisits older rows,
so their charts stay understated until someone asks for it.

## Deliberate behaviour changes, called out

- **An empty day now charts as zero.** Previously a snapshot with no
balances was skipped, leaving a gap that the frontend forward-fills — so
a day the account was actually empty showed the *previous* non-zero
value. It now writes 0. More correct, but it is a change beyond the
stated fix.
- **A day whose BTC value is positive but unconvertible is left alone**
rather than written as zero, so it disappears into the frontend's
forward-fill instead of reading as a portfolio that briefly vanished.

## Tests

`historical sync values a holding the rate provider cannot price` — a
day holding SOL with deliberately no `sol` rate available. **Verified to
fail on the old implementation: 0 instead of 100000.**

The three touched historical fixtures gained `totalAssetOfBtc` and keep
their original expected cents, recomputed on the new basis (2.0 BTC ÷
0.000019 = 10526316; 1.0 ÷ 0.000018 = 5555556; 0.02 ÷ 0.00002 = 100000).

`tests/Feature/OpenBanking` green at 341/341 locally.

## Not covered

Coinbase's historical path already prices via dated per-asset candles
with a USD route, so it is not exposed to this at the same scale, and
Coinbase exposes no portfolio-level BTC equivalent to substitute.
Bitpanda has no historical sync at all.
2026-08-11 11:04:06 +00:00
Víctor Falcón 9e493dc75b
feat(mcp): record MCP tool usage and report it with stats:mcp-usage (#760)
## What

We had no idea whether anyone actually uses the MCP server. This records
one row per tool call and adds a report to read it back: which tools get
used, by which users, and how much.

**Storage** — `mcp_tool_calls`: `user_id`, `tool`, `created_at`. Raw
rows rather than pre-aggregated counters, because the volume is a
handful of calls per Pro user per day and a `GROUP BY` then answers
whatever we want to ask later. No arguments and no financial content are
stored.

**Recording** — one `rescue()`d insert in `McpTool::handle()`, the base
class all 24 tools inherit with no overrides, so coverage is complete by
construction. It sits *after* `respond()` and skips error responses, so
the number means "calls that did something": a plan-gate rejection, a
read-only token rejected on a write, or a `ValidationException` for an
unreachable id is an attempt, not usage. `rescue()` keeps a failed
insert from ever breaking a working tool call while still reporting to
Sentry.

**Reading** — `php artisan stats:mcp-usage [--days=30] [--top=20]`:

```
MCP usage — last 30 days (since 2026-07-13)
  Calls: 15   Users: 2

By tool
+---------------------+-------+-------+-------+
| Tool                | Calls | %     | Users |
+---------------------+-------+-------+-------+
| search_transactions | 10    | 66.7% | 2     |
| get_cashflow        | 2     | 13.3% | 1     |
| get_net_worth       | 2     | 13.3% | 1     |
| create_transaction  | 1     | 6.7%  | 1     |
+---------------------+-------+-------+-------+

By user (top 20)
+--------------------------------------------+-------+-------+---------------------+
| User                                       | Calls | Tools | Last call           |
+--------------------------------------------+-------+-------+---------------------+
| ana@example.com                            | 12    | 4     | 2026-08-11 08:06:59 |
| 20260811080659_bruno@example.com (deleted)  | 3     | 1     | 2026-08-11 08:06:59 |
+--------------------------------------------+-------+-------+---------------------+

By day
+------------+-------+-------+
| Day        | Calls | Users |
+------------+-------+-------+
| 2026-08-08 | 2     | 1     |
| 2026-08-11 | 13    | 2     |
+------------+-------+-------+
```

The per-user table joins `users` instead of eager-loading the relation:
`user:delete` soft-deletes, so the FK cascade never fires and the
relation's `deleted_at is null` scope would silently blank out exactly
the users we most want to see — the ones who churned. They render with a
`(deleted)` marker.

## QA

Driven through the real `/mcp` HTTP endpoint with real Sanctum bearer
tokens, against MySQL:

- 5 successful calls by a read+write user → 5 rows, right user, right
tool names.
- `get_net_worth` with missing arguments and `search_transactions` on an
unreachable space → both rejected, neither recorded.
- A read-only token: `list_accounts` recorded; `create_label` rejected
with "This token is read-only" and not recorded.
- Report checked at `--days` 1 / 30 / 200, with `--top 1` truncation,
with a churned (`markAsDeleted()`) user, and with no data at all.

48 MCP tests green, `pint` and `phpstan` clean.

## Deliberately left out

- **No Discord post or schedule.** The other `stats:*` commands post
weekly; whether MCP usage is worth that noise is a product call, and
it's one `Schedule::command()` line whenever we want it.
- **No client column.** `Auth::getDefaultDriver()` would tell us OAuth
(Claude Desktop / ChatGPT) vs personal token (Claude Code) at the
insert. It's not recoverable after the fact, so it's worth knowing we
skipped it — but it wasn't asked for.
- **No pruning.** Noted in the migration; add it if the table ever gets
big.
- **No collector service.** The sibling report commands extract one
because they feed both the console and Discord. This has one consumer.
2026-08-11 10:27:32 +02:00
Víctor Falcón 1a0e80a342
fix(coinbase): stop one unlisted stablecoin from unpricing the whole portfolio (#761)
Follow-up to #759, which turned out to be **inert in production**.
Confirmed from the logs after it deployed.

## What is actually happening

`fetchPriceMap` builds `{ASSET}-{QUOTE}` product ids for a batched
`best_bid_ask` call. **EURC** — Circle's euro stablecoin — is not an ISO
4217 code, so `isFiatCurrency()` rejects it, and the stablecoin list was
USD-only, so it went out as an ordinary crypto product id.

Coinbase does not list `EURC-EUR`, and it refuses the **entire** request
over one unknown id:

```
invalid product_id provided: "EURC-EUR"
```

Since #759 that happens twice per run — once for the fiat pass, once for
the new USD retry (`invalid product_id provided: "EURC-USD"`). So
`fetchPriceMap` has been returning an empty map on **every** sync,
#759's USD hop never contributed anything, and every holding fell
through to the per-asset `CurrencyConversionService`, which prices
almost no crypto. The post-#759 log signature is 2× `Coinbase API error`
(400) + 2× `Coinbase best_bid_ask failed` per run, and `Could not price
Coinbase asset` never dropped.

The balance is still written, so net worth and the chart have been
showing a badly understated number.

## Three commits

1. **EURC settles at its euro peg.** The USD-only list became a peg map
(`asset => peg currency`), which also collapses three duplicated
`in_array` branches into one lookup that carries the peg.
USDT/USDC/DAI/PYUSD/GUSD are byte-for-byte unchanged.
2. **A rejected batch retries one asset at a time.** Fixing EURC removes
today's bad id, but not the shape of the failure: one unlisted holding
takes the price of every other holding with it, and the next unlisted
token would do it again. The batch is now an optimisation rather than a
single point of failure.
3. **Fan out only when the batch itself was refused.** Both reviews
caught this independently, and it was a real bug I introduced in commit
2: retrying on *any* throwable multiplies `CoinbaseClient`'s own 429
backoff (10s/30s/60s ≈ 100s per call) by the number of holdings, against
`SyncBankingConnectionJob`'s 120s timeout — trading a fast wrong answer
for a sync that hangs and dies. The fan-out now requires a 4xx that is
not 429.

## Tests

Three new, each verified to fail without its fix:

| test | without the fix |
|---|---|
| `settles EURC at its euro peg instead of asking Coinbase to quote it`
| 5 000 000 instead of 5 010 000 — the EURC vanishes |
| `prices the rest of the portfolio when Coinbase rejects one product
id` | **0** — the entire portfolio unpriced, which is what production
does today |
| `gives up on a rate-limited price batch rather than retrying every
asset` | fans out and sends the per-asset requests |

The 429 test fakes `Sleep`; without it the real backoff makes the file
take 209s instead of 10s.

`tests/Feature/OpenBanking` is green at 341/341 locally.

## Deliberately not here

- **Already-written rows stay understated.** `needsHistoricalBackfill`
is already satisfied by the wrong rows, so the next sync only heals
today's. The chart will show a discontinuity on deploy day. No new code
needed to repair it — `SyncBankingConnectionJob` already has a
`fullSync` flag that forces the historical pass, reachable as `php
artisan banking:sync --full`. Replaying a year of pricing on real
accounts is your call, not something this loop should do unattended.
Blast radius: 2 Coinbase connections, both EUR.
- **A USD-currency user's EURC** used to be quoted against the real
`EURC-USD` pair and now goes peg + FX instead. Inert today (all crypto
connections in production are EUR) and consistent with how USDT/USDC are
already handled, but it is a silent pricing change for a future USD
holder.
- **Anything not in the peg map and not quotable is still silently
zero.** This fixes EURC by name; the general "report an incomplete
balance as if it were complete" behaviour needs a product decision.
- **`BinanceBalanceSyncService`'s historical path** still hands a raw
crypto ticker to the fiat converter with no USD hop (its live path is
fine). Same class, own PR — I started on it this cycle and dropped it
when the logs showed this was live and Binance's was not.
2026-08-11 08:24:14 +00:00
Víctor Falcón 5eb43067f8
fix(banking): stop crypto holdings quoted only in USD from vanishing from the balance (#759)
Found in the Sentry **logs**, not the issues queue — this class of bug
never throws, it just quietly reports the wrong number. `Could not price
Coinbase asset` has been firing steadily, 24 times in the last 7 days.

## What happens

`CoinbaseBalanceSyncService::fetchPriceMap` only ever asked Coinbase for
`{ASSET}-{USER_CURRENCY}` price books. Coinbase lists most assets
against USD alone, so for a EUR user those come back empty.
`convertCryptoAssets` then falls through to
`CurrencyConversionService::convert('SOL', 'EUR', …)` — a **fiat** FX
service that has no rate for a crypto ticker and returns `0.0`.

The holding contributes nothing. The balance is still written to
`account_balances`, so it feeds net worth and the balance chart as a
confidently wrong, lower number — indistinguishable from the user
genuinely holding less.

The historical backfill never had this problem:
`fetchHistoricalPricesForAsset` already retries against USD and
converts. So the same wallet is priced correctly for every past month
and collapses on today's balance — a cliff at the right-hand edge of the
chart rather than an obviously broken figure.

**All three Coinbase/Bitpanda/Binance users in production are on EUR**,
so the Coinbase half of this is live for both Coinbase connections.

## The commits

1. **Coinbase**: the live path takes the same USD hop the historical
path already takes, for whatever the fiat pricebook did not cover — one
extra batched request, and only when something is actually missing.
2. **Bitpanda**: same defect one service over. `getTickerPrice` read
`$ticker[$symbol][$targetCurrency]` and gave up on a miss, and the
caller logs and `continue`s, dropping the wallet entirely. Bitpanda's
ticker only quotes EUR, USD, CHF, GBP and TRY — so every other supported
currency reads **zero for every crypto wallet**, which now includes DKK
(added in #754). No user is on such a currency with a Bitpanda
connection today, so this one is a landmine rather than a live bug; I
fixed it because it is the same one-line shape and it silently
misreports money.
3. **Review follow-ups** (no behaviour change): stop quoting stablecoins
that `convertCryptoAssets` settles at 1 USD before it ever reads the
map; guard the empty batch inside `fetchBestBidAskPrices` rather than
relying on the caller; drop the now-untrue "falling back to per-asset
USD conversion" tail from the catch message.
4. **Mixed-batch test** — the single-asset test never exercises the
`array_diff` that decides what the USD pass asks for.

## Safety

- USD users short-circuit before any USD hop. Assets that already have a
fiat book are excluded from the retry and never touch the new path.
Stablecoins are intercepted before the map is consulted.
- If the second request throws, or the FX rate for the date is missing,
the `$targetPrice > 0` guard drops it and the asset falls through to
exactly today's behaviour. The change can only add a price, never
replace a good one.
- Money math verified against `CurrencyConversionService::convert`,
which **divides** by a rate keyed to the target currency as base: 100
USD ÷ 2.0 = 50 EUR per unit, then multiplied by quantity.

## Two things this does NOT do

**Already-written rows stay wrong.** The next sync overwrites only
today's `balance_date` row. `needsHistoricalBackfill` re-runs the
historical pass only once, so every daily row written since the account
was connected keeps its understated value — 102 rows on one Coinbase
account, 16 on the other. The existing `php artisan banking:sync --full`
re-runs the historical pass and would repair them; I did not run it,
since replaying a year of pricing for real accounts is an ops call, not
something an autonomous loop should do unattended.

**An asset Coinbase does not quote in USD either still vanishes
silently.** It logs and contributes zero, with nothing surfaced to the
user. Pricing an unquotable asset is not solvable here, but reporting a
balance we know is incomplete as if it were complete is a product
decision worth taking: flagging the account as partially priced would be
the honest behaviour.

## Follow-up found in review, deliberately not here

`BinanceBalanceSyncService`'s **historical** path (`:145`) also hands a
raw ticker to the fiat converter with no USD hop, dropping zeros into a
`skipped_assets` log. Its live path is correct, so today's balance is
right and only the one-time historical anchors are affected — a smaller,
different blast radius that deserves its own change.

## Tests

`prices an asset Coinbase only quotes in USD instead of dropping it from
the balance`, `mixes fiat-quoted and USD-only assets in one balance`
(asserts the second request carries `SOL-USD` and does not re-quote
`BTC`), and `prices a wallet Bitpanda does not quote in the user
currency via USD` (a DKK user).

**I could not run the PHP suite locally — the local Docker daemon is
wedged, so the MySQL testcontainer never starts. Relying on CI.** Pint
and `php -l` are clean.
2026-08-11 02:56:03 +00:00
Víctor Falcón a500c00b2b
fix(ui): show a recoverable screen instead of a blank page when render throws (#758)
Relates to
[PHP-LARAVEL-5A](https://whisper-money.sentry.io/issues/PHP-LARAVEL-5A).

## Why

The app has never had a React error boundary. Any throw during render or
in an effect unmounts the whole tree, so the user gets a blank white
page — no message, no way out, and nothing telling them to reload.

That is not hypothetical, it is how **every** frontend crash we have
fixed this year presented itself: #41 (`addEventListener` on old
Safari), #43 (missing `indexedDB`), #47 (recharts render loop), #57 /
#4Y (`localStorage` null in a restricted webview), #675
(`colorClasses.bg`). Each got a targeted fix, and the next unguarded
property access white-screened the app again. PHP-LARAVEL-5A is the
current one: `props.features` arrives undefined on `/dashboard` and
`props.features.cashflow` takes the page down.

**This does not fix 5A's root cause.** I could not confirm why
`props.features` goes missing — the server always shares it, and the
only mechanism I found is Inertia core's `mergeProps` bailing out when a
partial response's component differs from the current page, which I
could not reproduce. What this does is stop that class of bug from
costing the user their whole session.

## What it does

Wraps the tree in `@sentry/react`'s `ErrorBoundary` — already a
dependency, no new packages — with a fallback offering a reload and a
way to the dashboard.

Two things the boundary has to take over, because once React handles an
error it never reaches `window.onerror`:

- **Reporting.** `Sentry.ErrorBoundary` captures on its own via
`captureReactException`, and adds the React component stack. Note this
will fingerprint as a *new* issue rather than continuing 5A, since the
exception now carries a synthetic cause.
- **The stale-chunk reload.** `chunk-load-recovery`'s global listeners
only see what React did not catch, so `onError` re-runs
`reloadOnChunkLoadError`. Its actual reload-once behaviour stays covered
by `chunk-load-recovery.test.ts`.

## The two follow-up commits are the interesting ones

Both came out of review and both were real bugs in the first commit:

**`handled` was silently flipped.** The SDK derives `handled` from
whether a fallback was supplied (`errorboundary.js:51`), so simply
adding one would have reclassified every caught crash as handled — they
would stop counting against crash-free sessions and stop matching any
`error.handled:false` alert. Now passes `handled={false}` explicitly.

**Both escape hatches were dead ends.**
- "Back to home" pointed at `/`, which renders the marketing page — and
that page mounts `AuthenticatedRedirectDialog`, which `router.visit()`s
a signed-in user to the dashboard on a 3s timer. The escape hatch
trampolined the user straight back into whatever crashed. It now goes to
the dashboard directly, as a document load.
- The **back button** was worse. Inertia's popstate listener lives at
module scope and outlives React unmounting the page, so going back
changed the URL and painted nothing — the screen just looked frozen. The
fallback now reloads on `popstate`.

## Scope, honestly

- `initializeTheme()` and `initializeChartColorScheme()` run at module
scope, **before** the boundary mounts, so the boot-crash class (#57 /
#4Y) is still outside its reach. Those are already fixed by #743's
`safe-storage`; worth knowing the boundary is not a second net for them.
- One boundary at the root means a crash anywhere replaces the whole app
rather than just the page. Since React unmounts the entire tree on an
uncaught error anyway, the trade is white screen → error screen, not
working page → error screen. A second boundary around `<App>` only would
let the shell survive and make `resetError()` meaningful — worth doing
if this ever fires often enough to matter.
- `ssr.tsx` keeps its own unwrapped copy of the provider tree.
Pre-existing duplication, now one element wider; extracting a shared
`AppProviders` is the fix.
- No reload-loop guard. "Try again" is user-initiated, not automatic, so
a deterministic crash means the button does nothing rather than looping
— and the dashboard button is the real way out.

## Tests

`app-error-boundary.test.tsx`: children render normally; a throwing
child produces the recovery screen with both actions instead of nothing;
the error is handed to the chunk-load recovery; the popstate listener is
registered and cleaned up. 4/4 locally, plus
`chunk-load-recovery.test.ts` 5/5.

Copy uses existing `lang/es.json` keys except one new line, which is
added.
2026-08-10 15:02:39 +00:00
Víctor Falcón 81c32b887b
fix(banking): stop Wise outages from silently parking a bank connection (#757)
Fixes
[PHP-LARAVEL-58](https://whisper-money.sentry.io/issues/PHP-LARAVEL-58).

## What production looks like

There is exactly one Wise connection in production and it has **never
synced** — `last_synced_at` is null. Its entire history is three failed
attempts:

| when | error |
|---|---|
| 2026-07-29 | `ConnectionException` — cURL error 28, timed out after
30s |
| 2026-08-03 | `ConnectionException` — cURL error 28, timed out after
30s |
| 2026-08-10 | `RequestException` — HTTP 500 from
`/v1/profiles/{id}/activities`, mid-cursor |

All three are upstream. All three were charged to
`consecutive_sync_failures`, now at **2**. At `MAX_SCHEDULED_RETRIES =
3` both `SyncAllBankingConnectionsJob` and `sync:banking` stop
dispatching the connection — permanently, with no email and no reconnect
notice in the UI. The next Wise outage would have been the last sync
this user ever got.

## Three commits

**1. Classify Wise timeouts and 5xx as transient.** `WiseClient` rethrew
everything raw, so an outage looked like an application bug: reported to
Sentry at error level and logged as `Wise API error`. Timeouts and 5xx
now raise `TransientBankingProviderException`, matching
`EnableBankingProvider` (PR #678). The job already understands that type
— warning instead of error, `ShouldntReport`, and a "temporarily
unavailable" message for the user. **401/403 and 429 deliberately stay
raw**: `isAuthError` and `isRateLimitError` match on `RequestException`,
and `resolveRateLimitBackoffUntil` reads `Retry-After` off
`$e->response`. The three request methods now share one private `get()`,
which is where the classification lives.

**2. Keep an empty body from becoming a TypeError.** Introduced by
commit 1: routing everything through `get(): array` turned a 200 with an
empty body into a `TypeError` — neither transient nor suppressed, i.e.
exactly the noise this branch removes. It used to degrade to `[]` via
`$accounts[0] ?? []`. Caught by review.

**3. Stop provider outages from parking a connection for good.** Without
this the branch is only a log-level change: `handleTemporaryError`
incremented the counter for any non-auth throwable, so the
classification never reached the user. A transient failure now surfaces
on the connection (status and message unchanged) without spending a
scheduled retry. Unclassified failures still count, so a genuine defect
still parks the connection.

No data migration needed — the connection is at 2, still under the cap,
so it stays eligible and the counter resets on its first success.

## Trade-off, stated plainly

A provider that is down forever is now retried forever: one job per
cycle, surfacing as a repeating `Banking sync failed` warning. That is
cheap and visible, and strictly better than silently never syncing a
user's bank. Marked with a `ponytail:` comment naming the ceiling.

The flip side is that a **persistent** Wise breakage (an API contract
change, say) now produces no Sentry issue — only warn-level logs and
`banking_sync_logs` rows. Worth knowing before assuming silence means
health.

## Tests

- `WiseTransientErrorTest`: 500 mid-cursor and a cURL 28 timeout both
become `TransientBankingProviderException`; 401/403/429 (dataset) stay
`RequestException`; an empty body still degrades to `[]`.
- `SyncRetryAndLoggingTest`: a transient failure at
`consecutive_sync_failures = 2` leaves it at 2 and below the cap; a
**non**-transient one still takes it to 3.

Local: 490/490 across `tests/Feature/OpenBanking`, `tests/Feature/Jobs`,
`tests/Unit`.

## Follow-ups (found in review, deliberately not here)

- `WiseClient` sets no timeouts; `EnableBankingProvider` uses
`timeout(20)->connectTimeout(5)`, IB uses 5/15. Two of the three prod
failures were 30s timeouts, so bounding them is worth a look — but
shortening the window on a 12-month first sync needs its own thinking.
- `EnableBankingProvider` logs its 5xx at `error` while raising the same
transient exception. Wise is the consistent one here; EB should follow.
- The `ConnectionException` + 5xx catch skeleton now exists three times.
Rule of three is reached — a shared trait would also let
Binance/Coinbase/Bitpanda/IndexaCapital adopt it.
- Both credential-validation call sites catch `\Throwable`, so
connecting Wise during an outage still tells the user "Invalid API
token". Now cheaply fixable by catching the transient type first.
2026-08-10 16:40:09 +02:00
Víctor Falcón 5baa677c2a
fix(banking): stop requesting a year of Enable Banking history on every sync (#755)
## Why

Enable Banking connections re-requested **a year of transaction history
every 6 hours**. Trade Republic connections failed ~70% of their syncs
with HTTP 429 (220 of 307 attempts in the last 7 days, against 1–4% for
other ASPSPs), and the cause was ours:

1. `EnableBankingSyncer::sync()` persisted the transactions, then the
balance call threw a 429, the exception bubbled up to
`SyncBankingConnectionJob`, and the whole run was marked failed.
2. `last_synced_at` is only written after a clean `sync()`, so it never
got written. 15 of 16 Trade Republic connections have zero rows in
`account_balances` and `last_synced_at = NULL` weeks after connecting.
3. `$isFirstSync = ! $connection->last_synced_at || $this->fullSync` was
therefore permanently true, so every run used `now()->subYear()` with
`strategy = 'longest'` plus `calculateHistoricalBalances()`. Paginating
a year of history four times a day is what trips the rate limit.

This is **not Trade Republic specific**: CaixaBank and Eurocaja Rural
show the same 429 pattern at lower volume, and the fix applies to every
Enable Banking ASPSP.

## What changed

All in `app/Services/Banking/Sync/EnableBankingSyncer.php`.

**1. The fetch window comes from the transaction watermark, not from
`last_synced_at`.**

The `linked` branch already did this; the lookup is now shared by both
branches:

- **Watermark found** → `date_from` = that transaction's date minus a
3-day overlap (banks post transactions with retroactive value dates, so
the previous no-overlap watermark could silently miss them), no
`longest` strategy.
- **No watermark** → unchanged: one year back with `strategy =
'longest'`. That is the genuine first sync.

This is the fuse: even if everything else fails, a routine sync asks for
a few days instead of a year. The two branches' differing balance
handling (`saveDailyBalances: false` for linked accounts,
`calculateHistoricalBalances()` on first sync for unlinked) is
untouched.

**2. A failing balance call no longer fails the whole sync.** It is
logged, counted, and surfaced as `balance_failed` in the array `sync()`
returns, so it lands in `banking_sync_logs.metadata` instead of being
silently swallowed. The run finishes clean → `last_synced_at` gets
written → `$isFirstSync` stops being permanently true →
`calculateHistoricalBalances()` stops running every 6 hours.

**Two exceptions are deliberately still fatal** (both raised by review,
see below): an expired session, and a **429**.

## Deviation from the brief, worth a look

The brief asked for *every* balance failure to be non-fatal, including
the 429. Both review passes flagged the same problem with that: a 429
escapes `EnableBankingProvider` as a raw `RequestException`, and that is
exactly what `SyncBankingConnectionJob::isRateLimitError()` matches to
set `rate_limited_until`. Swallowing it would have removed the only
backoff — and Enable Banking quotas are **per-consent daily access
counts** (`Maximum daily access exceeded`, `Allowed number of accesses
exceeded for consent`), so a connection that lost its backoff would keep
burning the remaining quota on every 6-hourly cycle and never get its
balances.

So a balance 429 is re-thrown and the existing backoff (untouched, as
the brief required) applies. The transactions from that run are still
persisted, and the connection stays `active`. Every other balance
failure is non-fatal as specified.

Three more findings from review, fixed in the second commit:

- **`--full` still forces the year-wide window.** A first sync on a
connection that has already synced can only come from that flag, so it
beats the watermark. Without this, `banking:sync --full` had become a
no-op for the window — the operator's only remedy for a gap in history.
- **Windows reaching back more than 90 days keep `strategy =
'longest'`.** A dormant account with an old watermark would otherwise be
rejected (422) and walked down the `[90, 30, 7]` narrowing ladder, which
advances the watermark past the span it never fetched — a silent,
permanent gap.
- **The watermark counts trashed rows** (the dedup already uses
`withTrashed()`, so re-fetching them creates nothing), and the
future-date clamp no longer eats the 3-day overlap.

## Out of scope

No migration, no new watermark column, no change to the
`rate_limited_until` backoff, no manual reset of the broken production
connections — the first clean sync clears `error_message` on its own.

Two things worth a follow-up, not fixed here:
`calculateHistoricalBalances()` is still gated on the connection-level
`$isFirstSync` while the window is now per-account, so an account added
to an already-synced connection pulls a year of transactions without a
balance backfill; and 61 accounts have never received a bank transaction
at all, so they stay on the year-wide window until one lands.

## QA

Ran the whole chain with nothing mocked but the network (real
`EnableBankingProvider`, `Http::fake`), checking the request that
actually leaves for the bank:

| Case | Request that goes out |
|---|---|
| Account with a watermark at `2026-08-08`, today `2026-08-10` |
`…/transactions?date_from=2026-08-05&date_to=2026-08-10` — 5 days, no
`strategy` |
| Account with no bank transactions |
`…/transactions?date_from=2025-08-10&date_to=2026-08-10&strategy=longest`
— unchanged |
| Balances returns 429 `Maximum daily access exceeded` | transactions
persisted, `status = active`, `rate_limited_until = 2026-08-11 00:00:00`
(next UTC midnight) |

Against the production database (read-only), for the 475 syncable Enable
Banking accounts:

| After the fix | Accounts | Avg. days requested |
|---|---|---|
| Watermark → short window | 382 | 13.7 |
| No watermark → 1 year + `longest` | 61 | 365 |
| Watermark older than 90d → wide + `longest` | 32 | 173 |

All 12 Trade Republic accounts have a watermark, averaging **7.1 days**
— down from 365 on every run.

## Tests

`tests/Feature/OpenBanking/SyncBankingConnectionJobTest.php`:

- an account with existing Enable Banking transactions asks for
`watermark - 3 days`, not a year (the test that matters)
- an account without them still asks for the year with `longest`
- `--full` beats the watermark
- a non-429 balance failure → connection stays `active`,
`last_synced_at` written, the run's transactions persisted,
`balance_failed: 1` in the sync log metadata
- a 429 balance failure → transactions persisted and the backoff still
applied
- an expired session during the balance call is not swallowed

Full suite green (2080 passed), `pint` and `phpstan` clean.
2026-08-10 15:56:45 +02:00
Víctor Falcón 33fc058f3c
fix(demo): stop demo:reset from colliding on the fake Stripe subscription id (#756)
Fixes
[PHP-LARAVEL-5B](https://whisper-money.sentry.io/issues/PHP-LARAVEL-5B).

## What broke

`demo:reset` seeds a fabricated Stripe subscription so the demo account
gets Pro access without touching Stripe. The id was the hardcoded
literal `sub_demo_free_forever`, and `subscriptions.stripe_id` is
unique.

`--email` (#753, shipped this morning) made a second seeded account
possible. `createSubscription()` deletes only the *current* user's
subscriptions before inserting, so the first `demo:reset --email` run
after the public demo account existed died on:

```
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'sub_demo_free_forever' for key 'subscriptions.subscriptions_stripe_id_unique'
```

`createSubscription()` is the last step of `handle()`, so the reviewer
account was left fully seeded but with **no subscription at all** — an
app-store reviewer signing in lands on the paywall instead of the Pro
app.

## The fix

Derive the fake id from the user: `sub_demo_{$user->id}`. Matches what
`E2eBankingFixtureCommand` already does (`sub_e2e_.$user->id`). Nothing
reads the old literal — entitlement goes through Cashier's
`subscribed('default')`, which only looks at `stripe_status`. Production
is self-healing: the next run replaces the old row, and the demo account
keeps working until then.

## Second commit: seeded accounts and the Stripe billing paths

Fixing the collision means reviewer accounts now genuinely have
`hasProPlan() === true`, which switches on paths that were unreachable
while they were paywalled. `isDemoAccount()` is equality against
`config('app.demo.email')`, so an `--email` account is **not** a demo
account and skipped every existing guard:

- `SubscriptionController::billingPortal` would call
`createAsStripeCustomer()` — creating a real Stripe customer in
production — and drop the reviewer on an empty portal.
- Bucketed into `PAY_NOW`, `canSelfRefund()` returns true, so the refund
box renders; `RefundSelfServe::handle` then calls
`$subscription->latestPayment()` on `sub_demo_<uuid>` → Stripe 404,
thrown above the `try`, 500 plus a false `🔴 Self-service refund FAILED —
the user may have been charged without a refund` Discord alert.

`User::hasSeededSubscription()` keys off the fabricated id prefix rather
than one hardcoded email, so it also covers the e2e fixture account.
Real Stripe ids are `sub_` + alphanumerics with no further underscore,
so no paying user can match it.

## Tests

- `demo:reset subscribes a named account even when the public demo
account already exists` — seeds the public demo account, then a named
one. Verified it fails on the pre-fix code with the **identical**
SQLSTATE 1062 message from the Sentry event, and asserts the two ids
differ so a regression back to a shared literal is caught.
- `a seeded reviewer account cannot reach the billing portal`, `blocks a
self-refund on a seeded demo subscription`.

Local: `ResetDemoAccountCommandTest` 7/7, `SelfServeRefundTest` +
`DemoAccountRestrictionsTest` + `SubscriptionTest` 59/59.

## Not fixed here (found during review, out of scope)

- `ResetDemoAccountCommand` falls back to
`Bank::factory()->create(['user_id' => null])` when a named bank is
missing, permanently adding randomly-named **global** banks visible to
every user. `firstOrCreate(['name' => …, 'user_id' => null])` would fix
it.
- Seeded accounts count as paid in `SubscriptionFunnelCollector` /
`ExperimentFunnelCollector` unless their email is in
`AI_SUGGESTIONS_REPORT_EXCLUDED_EMAILS`.
- `handle()` runs without a transaction, so a failure mid-reseed still
leaves a half-seeded account.
2026-08-10 12:48:13 +00:00
Víctor Falcón 02b6892489
feat(currencies): add the Danish Krone (DKK) (#754)
## What

Adds the **Danish Krone (DKK)** as both a user primary currency and an
account currency.

Per `docs/adding-a-currency.md` this is a config change — validation
(`ProfileUpdateRequest`, `StoreAccountRequest`, `UpdateAccountRequest`),
the Inertia dropdown props and conversion all derive from
`config/currencies.php`.

Both pre-checks in the doc pass:

- `DKK` is the current ISO 4217 code (no deprecated-code trap like
`GHC`/`GHS`).
- The provider covers it: `EUR→DKK = 7.4754`, consistent with the ERM II
peg (~7.46).

## Closing the translation gap

Currency names are translated in PHP by `CurrencyOptions`, so they never
appear as literal `__()` keys in the TS/TSX source — `LocalizationTest`
never saw them, and a missing Spanish name silently shipped the English
one. The doc even warned about it.

`LocalizationTest` now feeds the configured currency names into its
translatable-key check, so Spanish is enforced and French warns, exactly
like every other key. That surfaced pre-existing gaps, now filled:

- Spanish: PKR, BRL, DOP, SAR
- French: those four plus NGN

## Also

Dropped the docs' "add a symbol" step. `getCurrencySymbol` has no
callers left — every consumer of `utils/currency` imports
`formatCurrency` only — so entries in its map change nothing on screen.
Removing the function itself is a separate cleanup.

## QA

Real browser QA against the running app, in Spanish:

- `DKK - Corona danesa` appears in the profile currency select; saving
persists `users.currency_code = 'DKK'` and survives a reload.
- `DKK - Corona danesa` appears in the create-account currency select;
created a `Danske Bank Private` account and confirmed
`accounts.currency_code = 'DKK'`.
- Conversion both ways: `100 EUR → 747.68 DKK`, `100 DKK → 13.38 EUR`.
- `LocalizationTest` + `CurrencyConversionServiceTest` green; `pint`,
`phpstan`, `prettier`, `eslint` clean.

## Demo

<!-- PLACEHOLDER: drag the video here -->
**⬆️ Attach `~/Downloads/dkk-currency-qa.mp4` here.**

## Follow-up (out of scope)

Prod already holds accounts and users on currencies that aren't in the
config (PLN, MAD, PHP).
`AccountUserCurrencyService::resolveImportedCurrency` accepts whatever a
bank reports and `forceFill`s it onto `users.currency_code`, bypassing
validation — so those users can't save **any** profile change, and their
currency select renders empty. Worth a separate issue: either
validate/fall back on import, or make the selects tolerate an
out-of-list current value.
2026-08-10 12:08:56 +02:00
Víctor Falcón fb692dabf6
feat(demo): seed named accounts with demo:reset --email (#753)
## Why

The ChatGPT app directory review needs a reviewer account: fully
featured, pre-loaded with sample data, reachable with an email and
password, no 2FA, and on the Pro plan our MCP tools require.
`demo:reset` already builds that dataset — 6 accounts, ~2k transactions,
12 months of balances, categories, labels, rules, budgets — and attaches
an active subscription, so it only needed to target an email other than
the public demo user.

## What

- `--email` / `--password` create or reset an arbitrary account instead
of the configured demo user. An explicit `--email` skips the
`app.demo.enabled` gate, since a named account is not the public demo.
- The account keeps `isDemoAccount() === false` (that check compares
against `app.demo.email`), so none of the demo UI restrictions apply to
it.
- `--imported` marks one account's transactions as bank-imported, so a
reviewer can verify that `update_transaction` and `delete_transaction`
refuse to touch synced data — one of the negative test cases in the
submission. That account gets no banking connection, so no sync ever
runs on it.
- The public `demo:reset` path is unchanged: same config, same gate,
same data.

Usage:

```
php artisan demo:reset --email=openai-review@whisper.money --password='...' --imported
```

## Testing

`tests/Feature/Console/ResetDemoAccountCommandTest.php` adds two cases
on top of the existing ones: a named account comes out on the Pro plan,
not flagged as the demo account, and holding both manual and imported
transactions; and `--email` without `--password` fails without creating
anything.
2026-08-10 09:03:14 +00:00
Víctor Falcón fe747c4472
feat(stats): post the Discord stats reports in Spanish, opened by an AI summary (#752)
## What

The admin Discord channel is Spanish, but the four scheduled `stats:*`
reports posted English. They now post Spanish, and the three
cohort/experiment reports open with a short AI-written summary so a
reader understands the situation without decoding the table.

### 1. Spanish reports

`stats:daily-report`, `stats:subscription-funnel`,
`stats:experiment-funnel` and `stats:ai-cohort-report` now post Spanish
embed titles, field names, ASCII table headers, legends and disclaimers,
with Spanish dates (`sáb., 13 jun. 2026`). Table headers and cells stay
ASCII (`Semana`, `Variante`, `UMad`, `pdte`, …) so `sprintf`'s byte
padding keeps the columns aligned inside the code block.

Hardcoded, not `__()`: this is an internal channel, not user-facing UI,
so it never needs a second language and doesn't belong in
`lang/es.json`. Everything else — code, comments, PHPDoc, command
descriptions, `$this->info()` — stays English.

### 2. AI summary (best-effort)

New `ReportSummarizer` + `ReportSummaryAgent` (laravel/ai, same
Gemini-Flash pattern and `AI_PROVIDER` switch as the other AI features,
config in `config/ai_reports.php`). It prepends a few sentences to the
embed description that compare the current period against the previous
one (week over week for the two weekly reports, month over month for the
monthly cohort one), say what got better or worse, and call out
explicitly when a figure isn't conclusive — small sample, immature
cohort, signup surge week, or no previous period.

- **Data**: only what each collector already computes. The two cohort
reports pass their weekly series with the per-metric maturity flags; the
experiment report passes the per-variant figures plus the
already-rendered significance verdict (one source of truth), with money
figures nulled exactly where the table renders `—`, so the summary can't
report a zero where the reader sees no data.
- **Previous period**: the experiment report has no time series, so each
run caches its figures (with a capture timestamp) as the next run's
baseline. A same-day manual re-run doesn't overwrite it, and the model
is told to flag a gap that isn't roughly one period.
- **Degrades safely**: no API key, a provider outage, a bad provider
name or a slow response (30s timeout) → the report is posted unchanged,
without the summary. Transient provider errors are logged; anything else
is reported, matching `CategorizeTransactions` /
`LaravelAiRuleSuggestionGenerator`.

### 3. Fix found while reviewing: Discord's embed limits

The translated "Cómo leerlo" field came out at 1152 characters, past
Discord's 1024-character cap on a field value — Discord rejects the
**whole** payload, so the experiment funnel would have silently stopped
appearing in the channel every Monday (`DiscordWebhook` only logs the
400). Both long fields are now tighter (745 and 898 chars),
`DiscordWebhook` trims anything still over the limit instead of losing
the report, and a test measures every scheduled report's embed so
growing copy fails in CI rather than in production.

## Testing

- `tests/Feature/Ai/ReportSummarizerTest.php`: baseline in/out, same-day
re-run, dry run, backtick stripping, truncation, empty answer,
transient-vs-reported failures.
- `tests/Feature/DiscordReportEmbedLimitsTest.php`: all four embeds
inside Discord's limits, plus the trimming fallback.
- The four command tests: Spanish assertions, summary is the first thing
in the description, and the report is still posted when the AI throws.
- 64 tests / 338 assertions pass locally, plus PHPStan and Pint.

## QA

Ran all four commands against the local DB with `--no-discord` (and
dumped the real webhook payloads with the Discord call faked). Real
Gemini output, e.g. the experiment funnel on the second run:

> No se ha producido ningún cambio en las métricas del experimento
respecto a la ejecución previa del 10 de agosto de 2026. La tasa de
conversión sobre usuarios maduros se mantiene en el 4,7 % para la
variante reducida, el 4,0 % para pay_now y el 3,7 % para el control. Las
cifras no son conclusivas ya que las diferencias entre variantes no son
estadísticamente significativas, con un p-valor de 0,593 frente al
umbral α de 0,017.

Also verified with an unreachable provider: the report renders in full,
without the summary.

## Not included

- `stats:stuck-cohort-report` is still English. It posts to the same
webhook but isn't scheduled in `routes/console.php`, so it was out of
the four active reports; worth its own decision.
- The `—` and `` cells are still a couple of bytes off inside the code
block (multibyte in `sprintf`). Pre-existing on `main`, unchanged here.
2026-08-10 10:13:40 +02:00
Víctor Falcón da9032a76e
fix(mcp): declare all three MCP hints on every tool (#751)
## Why

The ChatGPT app directory rejects the submission with:

> Every MCP tool must set readOnlyHint, openWorldHint, destructiveHint
to true or false.

We only ever declared one hint per tool — `#[IsReadOnly]` on the reads,
`#[IsDestructive]` on the writes — so the other two were absent from
`tools/list` and the portal's scan flagged all 23 tools.

## What

- `McpTool::annotations()` now defaults all three hints, so every tool
reports `readOnlyHint`, `destructiveHint` and `openWorldHint`
explicitly. The attributes still override: `#[IsReadOnly]` on the eight
read tools, `#[IsDestructive]` on the four deletes.
- `openWorldHint` is always `false`: every tool reads or writes the
user's own account, never the open web.
- `destructiveHint` drops to `false` on the eleven
create/update/categorize/label tools. Marking them destructive was wrong
— the directory reserves it for irreversible operations — and it made
ChatGPT ask for confirmation on every write, including recategorizing a
transaction.
- Tool descriptions trimmed to the portal's 200-character cap (nine were
longer, `create_automation_rule` ran to 524). The cuts are facts the
server instructions already state — amounts in minor units,
whole-account scope. The JsonLogic variable list and example move to the
`rules_json` schema field, which the model still reads and the form does
not cap.
- `chatgpt-app-submission.json` is the submission-import file the portal
accepts, carrying the listing metadata, the per-tool hints with their
required justifications, and the positive/negative test cases.

## Testing

`tests/Unit/Mcp/ToolAnnotationsTest.php` pins both contracts: every tool
declares all three hints with `readOnlyHint`/`destructiveHint` matching
the expected tool lists, and no description exceeds 200 characters.
`tests/Feature/Mcp` still passes.
2026-08-10 08:06:00 +00:00
Víctor Falcón 7260e86817
feat(mcp): serve the ChatGPT app directory domain challenge (#749)
## Why

Publishing the MCP server to the ChatGPT app directory requires proving
we own the host that serves it. The submission portal issues a token and
fetches `https://whisper.money/.well-known/openai-apps-challenge`,
expecting the bare token back. That path currently 404s.

## What

- `GET /.well-known/openai-apps-challenge` returns
`OPENAI_APPS_CHALLENGE` as `text/plain`, nothing else — no JSON
envelope, no extra tokens.
- Aborts with 404 when the token is unset, so a host without the
variable configured cannot answer with an empty body that the verifier
would read as a mismatched token.
- Token lives in config/env rather than the repo: it is per-plugin and
rotates independently of the code.

## Testing

`tests/Feature/OpenAiAppsChallengeTest.php` covers both branches: the
token is served verbatim when configured, and the route 404s when it is
not.

The production env var is already set, so the endpoint answers once this
deploys.
2026-08-10 07:46:49 +00:00
Víctor Falcón 698aaffbba
feat(feedback): move feedback and roadmap links from Canny to UserJot (#748)
## What

Replaces Canny (`whisper-money.canny.io`) with UserJot
(`whispermoney.userjot.com`) everywhere it is linked in the app.

| Surface | Before | After |
| --- | --- | --- |
| User dropdown → **Feedback** |
`whisper-money.canny.io/feature-requests` | `whispermoney.userjot.com/`
|
| User dropdown → **Roadmap** | `whisper-money.canny.io/` |
`whispermoney.userjot.com/roadmap` |
| Jan 2026 update email | both Canny URLs | `/roadmap` + root |

Canny's board root was the feedback list and `/feature-requests` the
submission board; UserJot inverts that. The root is the cross-board "All
Feedback" feed — it covers both the Features and Bugs boards and carries
the *Give Feedback* button, so it is a superset of the old
`/feature-requests` destination. `/roadmap` is a real dedicated page,
which Canny never had.

A repo-wide grep confirms no `canny` reference remains. Nothing else
linked it — not the README, the landing page, the privacy/terms pages,
or the drip emails.

The new vitest case pins both hrefs, so an accidental revert fails the
build.

## Testing

- `user-menu-content.test.tsx` — 3/3 green.
- Browser QA on the running app: logged in, opened the dropdown, clicked
**Feedback** and **Roadmap**, and confirmed each opens the right UserJot
page in a new tab (`rel="noopener noreferrer"` intact). Repeated at a
390×844 mobile viewport. See the demo below.

## Demo

<!-- PLACEHOLDER: drag the video here -->

## Follow-ups (outside this repo)

- **The UserJot workspace still has demo seed posts.** "Shared access
for family accounts" (Emily Roberts) is the only card under **In
Progress**, so every user clicking Roadmap sees a fake item presented as
actively being built — and it duplicates the real imported post
"Multi-tenant support for families or companies". "Custom tags for
transactions" (Sam Wilson) is in the feed too. Worth deleting before
this ships.
- **Canny is still live** and still serves its 17 posts. It has no URL
redirect feature, so already-sent emails, Discord pins and search
results will keep landing there. Close or rename the boards with a
pointer to UserJot, and reconcile the import (Canny 17 vs UserJot
Planned 5 / In Progress 1 / Done 11) before decommissioning.
- **The Bugs board has no entry point.** The Support dialog still routes
bug reports to Discord/email, so `/board/bugs` sits empty. Either point
Support at it or drop the board.
- **No SSO.** UserJot supports JWT identification; without it users need
a second account to vote. Same as Canny, but the migration is the
natural moment to add it.
2026-08-10 06:54:21 +00:00
Víctor Falcón 85c74604b2
feat(transactions): allow manual transactions on bank-connected accounts (#747)
## Why

You could not add a transaction by hand to a bank-connected account.
There was no good reason for it: bank sync **only inserts** rows it has
not seen before (dedup runs on `dedup_fingerprint` /
`external_transaction_id`, both `null` on manual rows) and **never
deletes or updates**, so a hand-entered transaction survives every later
sync untouched.

The one thing that genuinely does not make sense is letting a user set a
**balance** on a connected account, because the next sync overwrites it.
That restriction stays.

## What was actually blocking it

Less than it looked. The HTTP endpoint already allowed it,
`ManualBalanceAdjuster` already skipped connected accounts, and the
transaction dialog already handled them (it forces `updateBalance:
false`). Only two surfaces blocked it:

- **MCP** — `WriteTool::writableAccount()` rejected every connected
account for *all* writes. Split into `accountInSpace()` (no connection
check — used by `create_transaction` / `update_transaction`) and
`balanceWritableAccount()` (still rejects connected — used by
`create_balance`).
- **The account detail page** — hid its "Add transaction" button for
connected accounts, even though the same dialog on the transactions page
already offered them in its account picker.

## Also in here

Two problems the change surfaced, both fixed:

- **`EnableBankingSyncer` linked-account watermark** took the newest
transaction of *any* source. With manual rows now able to land on a
connected account, one dated later than the bank's last posting would
shrink the fetch window and skip the bank history in between —
permanently, since the watermark only moves forward. On the QA data this
would have skipped **36 days**. Now restricted to bank-sourced rows.
- **`calculateHistoricalBalances`** derives history by walking back from
a bank-provided reference balance, summing transactions unfiltered.
Counting a hand-entered row subtracts money the bank never had. Now
walks bank-sourced rows only. (Safe before only because manual rows
could not reach a connected account.)

Plus the honesty/copy work:

- `ManualBalanceAdjuster` returns whether it shifted anything, so
`create` / `update` / `delete_transaction` all report `balance_updated`
instead of silently no-opping and letting the agent claim a balance
moved.
- The **OAuth consent screen** and the AI Connector settings page said
"bank-connected accounts stay read-only". That was a trust statement,
and it is no longer true — both now say bank-*synced transactions*
cannot be edited or deleted and connected balances stay untouched.
- `create_balance`'s description no longer contradicts the server
instructions shipped alongside it.
- The transaction dialog now *explains* why the "Update account balance"
checkbox is absent on a connected account instead of just hiding it (it
defaults to on and is localStorage-persisted, so it used to vanish
mid-form with no reason given).

## What stays blocked

- Balances on connected accounts — MCP `create_balance` rejects them,
the adjuster no-ops, the UI shows the explanation instead of the
checkbox.
- Editing or deleting bank/imported transactions — still gated on
`source === manually_created`, unchanged.

## Testing

- `create_transaction` on a connected account leaves its balances alone;
moving a transaction onto a connected account unwinds only the manual
side it came from.
- A manual row survives a sync and does not block the bank's own rows —
the invariant the whole change rests on, previously untested.
- A manual transaction does not move the linked-account sync window.
- The account page offers "Add transaction" on connected accounts, and
hides it on non-transactional ones.
- Full suite: 2047 passing, phpstan clean.

QA'd in the browser end to end (create from a connected account, edit it
afterwards, contrast with a manual account, switch accounts mid-form)
and over real MCP calls against the running server (`create_transaction`
returned `balance_updated: false` on connected / `true` on manual;
`create_balance` refused the connected account).

## Demo


https://github.com/user-attachments/assets/7a7f1cbb-8f68-402d-ba35-3288dd7ea77f


<!-- PLACEHOLDER: drag the video here -->
2026-08-10 05:32:40 +02:00
Víctor Falcón eb60f2eb30
fix(open-banking): unblock account mapping when the bank reports accounts without a uid (#746)
## Problem

A paying user reported that "Save & Sync" on the account mapping screen
did nothing — no error, no navigation, nothing.

EnableBanking returned their Société Générale card (`CB Visa`) with
`uid: null`:

```json
{"uid": null, "name": "CB Visa", "cash_account_type": "CARD", "account_id": {"iban": null, "other": {"scheme_name": "CPAN", "identification": "************8210"}}}
```

The page renders one mapping row per pending account, so the form posted
`bank_account_uid: null`. `MapAccountsRequest` requires it, the request
422'd, and since the page never rendered validation errors the button
looked dead. The user retried the connection six times.

A second problem kept them from doing what they actually wanted: both
accounts reported `currency: "XXX"` — ISO 4217 for "no currency".
`getCompatibleAccounts` filtered their existing EUR accounts against
`"XXX"`, matched nothing, and the "Link to existing account" option was
never rendered. The backend already knew `XXX` isn't a currency
(`AccountUserCurrencyService::resolveImportedCurrency`); the frontend
didn't.

## Fix

- Accounts without a uid are filtered out of the mapping screen. They
can never be synced anyway — every sync service early-returns on an
empty `external_account_id` — and `CreatesAccountsFromPending` already
skipped them during onboarding. That rule now lives in one place,
`BankingConnection::mappablePendingAccounts()`.
- The skipped accounts are named on the page, so users don't go hunting
for an account they can see in their bank app.
- A connection where *no* account has a uid is closed out instead of
parking on a mapping page that could only ever 422.
- Validation errors surface as a toast, with app-authored messages in
`MapAccountsRequest::messages()` instead of raw field paths.
- `XXX` (and a blank/lowercase variant) is treated as "unknown
currency": the code isn't displayed, and it no longer filters out every
linkable account.

## Scope

One user affected in production (the reporter). Their connection has one
valid account alongside the card, so this fix unblocks them on deploy —
no data change needed.

## Testing

- `tests/Feature/OpenBanking` — 315 passed, including two new cases:
uid-less accounts are hidden and named, and an all-uid-less connection
is closed rather than left awaiting mapping.
- Browser QA against a local reproduction of the exact production
payload: only `Compte Bancaire` is offered, `CB Visa` is named as
skipped, "Link to existing account" appears despite the `XXX` currency,
submitting without picking an account toasts the error, and picking
`Dany SG` links it (`external_account_id` set, connection `active`).

## Demo


https://github.com/user-attachments/assets/6275834a-a518-47b9-9015-a698e5926d71
<!-- PLACEHOLDER: drag account-mapping-fix-qa.mp4 here -->

## Not in this PR

`AuthorizationController::refreshAccountIds()` consumes the raw pending
list on reconnect; its positional fallback can pair a legacy account
with a uid-less entry. Not reachable for any account in production
today, it belongs to a different flow, and it deserves its own test —
filed separately rather than smuggled in here.
2026-08-09 18:41:35 +02:00
Víctor Falcón a3eafecf60
fix(onboarding): don't trap users on the syncing step when a bank sync fails (#745)
Reported by a user who spent over an hour and a half on the onboarding
syncing step, on two devices, without ever getting into the app.

## What was happening

When Enable Banking rate limits a connection, `SyncBankingConnectionJob`
records the error and backs off, but leaves the connection **Active with
`last_synced_at` still NULL** — the exact shape `syncStatus` treated as
"still syncing". The step polled that endpoint forever, and there was no
deadline or escape on the client.

Confirmed in production for the reporter: a Trade Republic connection
returned `429` on every scheduled sync for two days straight. They
unblocked themselves by deleting the connection — `onboarded_at` was set
four seconds later. Three other users are in the same state right now,
one of them from today.

## What changed

- **`syncStatus` no longer waits on a connection that already failed**,
and reports it as `failed` separately from `pending`.
- **The step says so instead of pretending it worked.** Advancing
silently dropped the user on a "You are all set!" screen with an empty
dashboard and no way to find out why. Now they get a short explanation
and a Continue button.
- **Client deadline raised to 5 minutes** — the previous 2 was under the
worst case of a healthy first sync (3 attempts of a 120s job, 30s apart)
— and the status request now has a timeout, so a hanging poll can't
stall the step either. A failing status check keeps polling until the
deadline rather than skipping the user ahead.
- **`AccountMappingController` clears the stale error** when it
reactivates a connection, so a genuine sync in flight isn't reported as
failed.

## Testing

- Feature tests for the rate-limited case, for a healthy connection
syncing alongside a failed one, and for the failed flag; a
`rateLimited()` factory state replaces the hand-rolled attributes.
- Vitest coverage for the three client branches: failed, deadline
reached, and the normal advance.
- Browser QA against the real app, reproducing the production state: the
honest screen appears instead of the spinner, Continue moves on, the
user completes onboarding and reaches the app; and a genuinely pending
sync still spins and then advances by itself once the connection syncs.
No console errors.

## Demo


https://github.com/user-attachments/assets/e54e029d-db7a-47b0-8b93-0da5569aa363


<!-- PLACEHOLDER: drag the QA video here -->

## Not in this PR

`settings/connections.tsx` has the same `active && !last_synced_at` =
"syncing" heuristic, so a rate-limited connection shows a permanent
green "Syncing" badge there and its error is never rendered (the error
block is gated on `status === 'error'`). Same bug class, separate
surface — worth a follow-up.
2026-08-09 18:40:49 +02:00
Víctor Falcón b35968b456
fix(banking): strip the ISO 20022 remittance tag from transaction descriptions (#744)
## Why

A support ticket: Bankinter transactions arrive with the raw ISO 20022
remittance tag in front of the text, so AI categorization reads the tag
instead of the merchant.

```
/TXT/D|SumUp *GELATERIA SALV
/TXT/H|TRANSF NOMI /AIGUA DE RIGAT, S      ← the payroll that got categorized as Fuel
/TXT/CONDIS SANT JUST DESV07/07/26|20260714
```

`/TXT/` is the unstructured remittance tag, `D|`/`H|` is the debe/haber
marker (which only repeats the sign of the amount), and card payments
append the purchase and settlement dates. None of it describes the
transaction.

In production this hits **7297 transactions across 20 users** —
Bankinter (6569) and Unicaja Banco (728), which ships the same shape.

## What

**`RemittanceTagFormatter`** strips the tag, the credit/debit marker,
the card dates and the `#` marker on card charges. The tag identifies
itself, so the formatter is keyed on the **description** rather than on
a bank name — it works for any bank shipping the same shape instead of
needing a new class per bank. `BankFormatter::matches()` now takes the
description as well; `BbvaFormatter` keeps matching on the bank name.

**`banking:backfill-descriptions`** fixes the rows that are already
imported. It also rewrites the automation rules that match on the raw
text: **48 user-authored rules across 4 users** contain literals like
`/TXT/D|RECIBO VISA CLASICA`, and rewriting descriptions without
rewriting those rules would silently stop them from ever matching again.
A test pins that a rule still matches its transaction after both are
rewritten.

```
banking:backfill-descriptions [--user=email] [--dry-run] [-v]
```

## QA

Ran the formatter over **all 2755 distinct tagged descriptions in
production**: 0 no-ops, 0 leftover tags/dates/markers, 0 degenerate
output.

Ran the command against a database seeded with production-shaped rows
and rules:

```
===== DRY RUN (-v) =====
DRY RUN — no changes will be saved.
  /TXT/D|SumUp *GELATERIA SALV            →  SumUp *GELATERIA SALV
  /TXT/H|TRANSF NOMI /AIGUA DE RIGAT, S   →  TRANSF NOMI /AIGUA DE RIGAT, S
  /TXT/EL CLANDESTI 27/07/26|20260803     →  EL CLANDESTI
  /TXT/CONDIS SANT JUST DESV07/07/26|20260714  →  CONDIS SANT JUST DESV
  /TXT/RECIBO MES TARJETA|20260806        →  RECIBO MES TARJETA
  /TXT/D|#RECOBRO RECIBO VISA             →  RECOBRO RECIBO VISA
  /TXT/OPENAI *CHATGPT SUBSCR MP          →  OPENAI *CHATGPT SUBSCR MP
  rule …080: {"in":["RECIBO VISA CLASICA",{"var":"description"}]}
8 transaction(s) and 2 automation rule(s) would be reformatted.

===== SECOND RUN =====
0 transaction(s) and 0 automation rule(s) reformatted.     ← idempotent
```

The raw text is kept in `original_description`; an already-stored
original is never overwritten; untagged descriptions and rules are left
alone; transactions the server cannot read (`description_iv`) are
skipped.

## Not in this PR

**Already-categorized transactions keep their category.** The backfill
fixes the text, not the past AI decisions — 4005 of the affected rows
already have a category (1024 of them AI-sourced), and
`ai:categorize-backfill` only picks up uncategorized ones.
Rule-categorized rows are unaffected because the rules are migrated. If
we want the AI ones re-run, that's a separate deliberate step: clear
`category_source = 'ai'` on the affected rows, then run the existing
backfill command.

## Rollout

```bash
php artisan banking:backfill-descriptions --dry-run -v     # inspect
php artisan banking:backfill-descriptions                  # apply
```
2026-08-09 18:11:05 +02:00
Víctor Falcón 275b77e640
fix(ai): stop a learned rule title from 500-ing the user's category change (#741)
## The bug

Sentry
[PHP-LARAVEL-53](https://whisper-money.sentry.io/issues/PHP-LARAVEL-53)
— `SQLSTATE[22001]: Data too long for column 'title'` on `PATCH
/transactions/{transaction}`. 6 events, 1 user.

Changing a transaction's category learns a forward-looking automation
rule, and `AiRuleLearner::title()` rebuilds the rule's title from the
merchant names it matches. This user's bank puts the **entire statement
line** in `creditor_name`:

```
15/06 12/06 Pago Con Tarjeta En Discos, Libros, Fotos Y Pc's -59,00 189,27 | 4940197152806468 Classpass* Monthly
```

Two corrections into the same category produced a 279-char title against
a `varchar(255)` column, so `$rule->save()` threw and took the whole
request with it. Since `creditor_name` is itself capped at 255 on
ingest, a single correction can overflow it too.

## The fix

1. **`AiRuleLearner::title()`** caps each merchant token (40 chars) and
the category name (60), so the title stays readable instead of merely
short — the `→ Category` tail is the part that carries the meaning.
2. **A `title` mutator on `AutomationRule`** truncates to the column
width. Both reviews flagged that fixing the learner alone leaves the
sibling generator, `ApplyRuleSuggestions::title()`, unguarded: it joins
three AI match tokens that are each validated at `max:255`, so it can
overflow the same column and 500 the accept-suggestions step **during
onboarding**. The mutator covers every generator, present and future, in
one place. User-authored titles never reach it —
`StoreAutomationRuleRequest` already rejects longer ones with a 422.
3. **Learning can no longer abort the correction.**
`CategoryOverrideHandler::record()` runs before the transaction is saved
and outside any DB transaction, so the incident left the correction
logged and the ai rules stripped while the category the user asked for
was never written. `bulkUpdate` is worse: it records every transaction
before the mass update, so one throw mutated rules for the earlier ones
and categorized none of them. A learning failure is now reported and
swallowed — both callers already handle "nothing learned".

## Tests

- `AiRuleLearnerTest` — replays the exact production payload; reproduces
the identical `SQLSTATE[22001]` on the pre-fix code and asserts the
title stays inside the column with the category still visible.
- `AutomationRuleTest` — the mutator truncates rather than failing the
write.
- `CategoryOverrideHandlerTest` — a throwing learner is reported, not
propagated.

191 tests green locally (`tests/Feature/Ai` + the three automation-rule
suites) against the MySQL testcontainer; `pint --test` clean.

## Deliberately out of scope

- **Dead-weight rules.** With such a merchant name the learned clause is
`creditor_name == "…-59,00 189,27 | …"` — it contains amounts and a
running balance, so it can never match again, yet it accumulates one
clause per correction and the UI toasts *"Learned: similar transactions
will be categorized automatically"*. The review's prod data says length
is the wrong guard (62 long merchant names DO repeat, across 490
transactions); the right one is rejecting the statement-line *signature*
(an embedded `dd/mm` or `nn,nn`) in `merchantKey()` so it falls through
to the already-guarded description-token path. Worth its own PR.
- **Rules list UI**: a long title sits in a `whitespace-nowrap` cell and
pushes the actions column off-screen (`settings/automation-rules.tsx`).
- **Unbounded writes of the same class elsewhere**, found while
reviewing: `transactions.currency_code` `varchar(3)` written unvalidated
from the Enable Banking payload (`TransactionSyncService.php:179`), and
`banking_connections.aspsp_name`/`aspsp_logo` with no `max:` rule in
`StartAuthorizationRequest`.

Fixes PHP-LARAVEL-53
2026-08-09 15:39:14 +00:00
Víctor Falcón 239317f7f9
fix(ui): stop unusable web storage from white-screening the app (#743)
## The bug

Two Sentry issues share one minified boot frame, `vq` →
`initializeTheme()`:

-
[PHP-LARAVEL-57](https://whisper-money.sentry.io/issues/PHP-LARAVEL-57)
— `TypeError: Cannot read properties of null (reading 'getItem')`.
Chrome Mobile WebView 131 / Android 15: the host app disabled DOM
storage, so `window.localStorage` is `null`.
-
[PHP-LARAVEL-4Y](https://whisper-money.sentry.io/issues/PHP-LARAVEL-4Y)
— `SecurityError: The operation is insecure.`, 17 events. Blocking
cookies/site data makes the very first access throw.

`app.tsx` runs `initializeTheme()` and `initializeChartColorScheme()` at
module scope, before React mounts, so either one white-screens the app.
Same class as PHP-LARAVEL-41 (Safari <14 `addEventListener`), which is
why `lib/media-query.ts` exists — `lib/safe-storage.ts` is its sibling.

## What both reviews caught

My first pass only routed the two initializers, and **that would not
have closed either issue**. Both events carry url
`https://whisper.money/`, and the landing page reads `localStorage`
unguarded in a mount effect (`welcome.tsx:2105`) — those users would
have white-screened a few milliseconds later instead. There is also **no
error boundary anywhere in this app**, so any throw in render or an
effect unmounts the whole root; there is no "broken widget" failure
mode.

So the fix also covers:

- **`welcome.tsx`** — the landing page's locale effect, the url both
issues carry.
- **`chunk-load-recovery.ts:61,71`** — `window.sessionStorage` was
evaluated in an argument list, *outside* the try/catch that guards its
use. For the SecurityError cohort the global `error` listener itself
threw, and that throw was reported as another error event, re-entering
the same listener. It also meant chunk-load auto-recovery was dead
precisely on the browsers most likely to hold stale assets.
- **`edit-transaction-dialog.tsx:104`** — a read inside a lazy
`useState`, i.e. during render, on `/transactions` and account pages.
Its `typeof window !== 'undefined'` guard checks the wrong axis:
`window` exists, `window.localStorage` is null.

## Not just "doesn't crash" — the preference still works

Making the crash survivable exposed what happens next. The `appearance`
cookie is unencrypted, `HandleAppearance` renders the page from it, and
the blade applies it before any JS runs. Then `initializeTheme` read an
empty localStorage, fell back to `'system'`, and stripped the `dark`
class again — so a no-storage user who chose Dark got light on every
load. The mount effect was worse: it called `updateAppearance`, which
writes the cookie, so simply opening the app reset the one channel that
still persisted for these users.

Now the cookie is read as a fallback, the mount effect hydrates without
writing back, and `initializeChartColorScheme` only overrides the
blade-rendered `data-chart-color` when something is actually stored
(previously it reset everyone to `colorful`, leaving the CSS palette
fighting the colors the charts draw with).

For users whose storage works, behaviour is unchanged: `readStoredValue`
returns exactly what `getItem` returned, `null` included.

## Tests

7 vitest cases. The helper's four (working storage, null global,
throwing getter, throwing `setItem`) plus three that pin the invariant
that actually regressed — the boot initializers survive a null and a
throwing storage, and leave the server's theme alone when nothing is
stored. Verified they fail if `initializeTheme` goes back to a bare
`localStorage` call; the helper-only tests do not.

## Follow-ups (not here)

- **An error boundary in `app.tsx`** — both reviews called this the
highest-leverage item in the whole change. ~10 unguarded storage sites
remain, and without a boundary each is a fresh white screen rather than
a contained failure plus a Sentry report. It needs fallback UI and a
visual check, so it deserves its own PR.
- **The remaining unguarded sites**, in blast-radius order:
`lib/debug.ts:4` (called ~30× per rule evaluation from the rule engine,
so auto-categorization dies for these users),
`transaction-analysis-drawer.tsx` / `category-analysis-drawer.tsx`
(drawers fail to open), `lib/key-storage.ts` (on a 1s interval, but
gated behind the deprecated encryption setup — and note storage that
silently fails to persist is the *wrong* policy for a key),
`hooks/use-admin.tsx` (no call sites — delete it).
- Six call sites already hand-roll this exact try/catch idiom, which is
the argument for the helper existing; folding them in would also remove
three duplicated localStorage stubs from the test suite.

Fixes PHP-LARAVEL-57
Fixes PHP-LARAVEL-4Y
2026-08-09 15:33:22 +00:00
Víctor Falcón 5e38c583b9
fix(banking): stop unclassified bank responses from silently killing a connection (#742)
> **Draft on purpose.** The migration can put connections into
`Expired`, which sends `BankingConnectionExpiredEmail` to real users —
up to ~18 of them shortly after deploy. That is the right outcome (they
have been broken for weeks without being told), but outbound email to
real users should be a human's call, not an autonomous one. Everything
else here is ready.

## The bug

Sentry
[PHP-LARAVEL-3J](https://whisper-money.sentry.io/issues/PHP-LARAVEL-3J)
— `RequestException: HTTP 403` in
`EnableBankingProvider::getTransactions`. 45 events, 10 users,
regressed.

`EnableBankingProvider` classifies known upstream failures into domain
exceptions and rethrows the rest as a bare `RequestException`. Two
responses were unclassified:

- `401 {"error":"CLOSED_SESSION"}`
- `403 {"detail":{"error_name":"PsuActionRequiredException"}}`

`SyncBankingConnectionJob` reads any bare 401/403 as an auth failure:
the connection goes to `Error` with `consecutive_sync_failures =
MAX_SCHEDULED_RETRIES + 1`. Both the scheduler and `banking:sync` filter
that out, so **the connection is never dispatched again**. Enable
Banking's syncer has `notifiesOnAuthFailure() === false`, and the
"reconnect your bank" notice only counts `Expired` connections — so
nothing told the user. Their bank sync was dead, silently.

Prod confirms the damage: **18 connections across 17 users** stranded
that way, 14 with this bug's exact error message, the oldest not synced
since **2026-05-06**.

## What each response now does

**`401 CLOSED_SESSION` → expired session.** The session is genuinely
gone (revoked at the bank, or superseded by a newer authorization) and
only the user can fix it. It now joins `EXPIRED_SESSION`: connection
marked `Expired`, reconnect email sent, notice shown, not reported as an
application error.

**`403 PsuActionRequiredException` → transient.** My first pass expired
these too; the product review pulled the prod data and it says
otherwise. The nine connections that hit this on 2026-08-05 had all
synced cleanly at 18:00 the evening before, failed inside the same
**nine-minute** window, all had months of consent left, and none has
recurred in the four days since. Nine users at nine different banks do
not revoke consent inside nine minutes — that is the provider faulting
behind a generic `"Internal error."` envelope.

Expiring is a one-way door: expired connections are never dispatched,
manual sync is refused, and the only way out is a full reauthorization
with SCA. Expiring on first sight would have pushed nine users through a
re-consent they did not need. So it is classified transient: the
connection stays schedulable and self-heals next cycle, and the error
logs as a warning instead of being reported. If a PSU action really is
required, the consent lapses on its own and the 401 path takes over.

A 403 or 401 the bank sends for any other reason still surfaces exactly
as before — tested, because widening either check to "any 401/403" would
silently expire every connection during a credentials bug of our own.

## Rescuing the stranded connections

The classification fix cannot reach the 18 already-parked rows: they are
excluded from dispatch before any of this code runs. The migration
clears their failure counter so the next scheduled cycle re-evaluates
them through the fixed path — they resume, or they expire properly, with
the email and the notice the user should have had months ago.

Also: the reconnect email's five keys were missing from `lang/es.json`,
so Spanish users got it in English. Unenforced because the localization
test only scans `resources/js`.

## Tests

`tests/Feature/OpenBanking` — 319 green, including 6 new provider cases
(both new codes on `getTransactions` and `getBalances`, plus negative
cases for an unrecognised 401 code, a bare 403, and a non-object
`detail`). The job-level behaviour — `Expired` + email + not reported —
is already covered end to end in `SyncRetryAndLoggingTest`, through the
real syncer.

## Follow-ups (not in this PR)

- **`Expired` badge next to a future "Expires:" date.** `markExpired()`
doesn't touch `valid_until`, and this fix expires connections whose
window hasn't lapsed, so `settings/connections.tsx:411` will show both.
Hide the line for expired connections or backdate the field.
- **Forensics gap.** `logSyncAttempt` records no
`error_class`/`error_message` on the expired path, so a provider-wide
wave becomes indistinguishable from ordinary consent churn in
`banking_sync_logs` — that is exactly the data that disproved my first
reading here.
- **Reconnect loop.** `AuthorizationController` sets the connection back
to `Active` and syncs immediately; if the bank refuses again the user
gets a second "reconnect" email seconds later.
- **`banking:sync --connection=<id>` obeys the health filter**, so ops
has no escape hatch for a stranded connection.
- **Duplicated catch ladders** in `getTransactions`/`getBalances` — the
shape that let a code get classified in one and not the other.

Fixes PHP-LARAVEL-3J
2026-08-09 17:26:34 +02:00
Jesús Mejías Leiva df9d62f76c
fix(docker): keep the client port in the URLs the app generates (#739)
## The bug

Self-hosted production image published on a non-default port (`docker
run -p 8080:80`, the default `APP_PORT` in
`docker-compose.production.yml`) serves the page but with **no CSS and
no JS**: every Vite asset is requested from
`http://<host>/build/assets/...` — port 80, where nothing listens —
while the page itself is on `:8080`.

## Root cause

Debian's nginx package now ships `/etc/nginx/fastcgi_params` with a
security workaround:

```nginx
# !!! Security workaround !!!
# Do not use HTTP_HOST as "$http_host".
...
# Note: this changes behaviour compared to previous versions, because "$host"
# does not preserve the client-supplied port [...] Existing deployments that
# rely on "$http_host" containing a port number may therefore break.
fastcgi_param  HTTP_HOST        $host;
```

`docker/nginx/nginx.conf` does `include fastcgi_params;`, so PHP
receives `HTTP_HOST=192.168.20.46` instead of `192.168.20.46:8080`.
`Request::getPort()` then falls back to the scheme default,
`$request->root()` loses the port, and every absolute URL Laravel builds
— Vite assets, the `Link: rel=preload` header, redirects, mail links,
OAuth redirect URIs — points at port 80.

Deployments behind a reverse proxy on 80/443 don't see it: the proxy
sends `X-Forwarded-Port`, which takes precedence.

## The fix

Ship our own `docker/nginx/fastcgi_params` with `HTTP_HOST $http_host`,
so the value no longer depends on what the base image happens to
install.

## Verification

Reproduced in a minimal container (`php:8.4-fpm` + apt nginx + this
repo's `nginx.conf`, repo bind-mounted at `/app`), printing
`$_SERVER['HTTP_HOST']` and `app('url')->asset('build/assets/app.css')`:

| fastcgi_params | `HTTP_HOST` | `asset()` |
| --- | --- | --- |
| from the base image | `127.0.0.1` |
`http://127.0.0.1/build/assets/app.css`  |
| this PR | `127.0.0.1:8096` |
`http://127.0.0.1:8096/build/assets/app.css`  |

`nginx -t` passes, and a request with a domain `Host` (no port) still
generates `http://whispermoney.example/build/...` unchanged.

Guarded by `tests/Unit/ProductionNginxConfigTest.php`.

## Note

Restoring `$http_host` re-exposes the case Debian's workaround targets
(a raw client `Host` that differs from an absolute-form request target).
The image already forwards the client `Host` — `server_name _` accepts
anything and there is no `TrustHosts` middleware — so this doesn't widen
the surface, but closing it properly would mean an explicit
`server_name` plus a `default_server` that rejects unknown hosts.

---------

Co-authored-by: Víctor Falcón <victor.falcon@factorial.co>
2026-08-09 14:25:19 +00:00
Ideal bd0481486d
feat(currency): add THB (Thai Baht) (#740)
## What
Add the Thai Baht as a supported currency.

## Compatibility
Provider covers `thb` (standard ISO 4217). The conversion service
lowercases codes and fetches `thb.min.json` — same path RSD/NZD use.
`exchange_rates` stores rates as JSON, so any 3-letter code works.
Validation rules and Inertia currency props auto-derive from config.

## Changes
- `config/currencies.php` — THB entry (`allows_primary` +
`allows_account`)
- `lang/es.json` — Spanish translation
- `lang/fr.json` — French translation
- `resources/js/utils/currency.ts` — short symbol (฿) for THB

Follows the RSD addition (#567) exactly; no code changes needed.
2026-08-09 14:24:58 +00:00
Víctor Falcón 616495d8e4
chore: add /release slash command (#738)
Adds `.claude/commands/release.md`, a `/release` slash command that cuts
a new release (patch by default, `/release minor|major` to override).

`bun run release` on its own can't work here: `main` is protected (PR
required + 5 required status checks), so release-it always dies at the
push step and rolls back. The command encodes the flow that does work:

1. Release branch, pushed first — release-it errors out with no upstream
2. `bun run release -- <bump> --ci --no-git.push --no-git.tag
--no-github.release` for the version bump + changelog
3. PR titled `chore: release vX.Y.Z`, wait for CI, squash-merge
4. Tag and GitHub release created on `main` after the merge

Docs only, no runtime code touched.
2026-07-26 16:00:45 +00:00
Víctor Falcón 007fb58d41
chore: release v0.2.7 (#737)
Patch release cut with `release-it`.

- Bumps `package.json` to `0.2.7`
- Regenerates `CHANGELOG.md` (conventional-changelog, angular preset)
and enriches it via `scripts/enrich-changelog.js`

Tag `v0.2.7` and the GitHub release will be created on `main` once this
is merged.
2026-07-26 17:14:23 +02:00
Víctor Falcón d32d1ff40b
feat(transactions): add a monthly trend view to the analysis drawer (#736)
## Why

The analysis drawer was built for **bounded** filters — a trip, a
project — where "total spent" and "avg / day" are the answer.

Filter by something open-ended instead, like a single category, and it
surfaces a year or two of expenses. There both numbers stop meaning
anything: the cumulative line only ever climbs, `€12.32 / day` is not a
figure anyone decides on, and the largest-expenses table fills with the
same monthly transfer repeated five times.

## What

A fourth analysis view that answers the open-ended question instead:
**the monthly rate, and where the recent months sit against it**.
Automatic picks it past a 120-day span; the existing per-filter override
now carries four options, each named after the number it produces.

`Automatic` · `Total spent` · `Income & expenses` · **`Monthly trend`**

| Panel | Bounded view | Monthly trend |
|---|---|---|
| Rate | Total spent + avg / day | **Monthly average** and **last 3
months** with the change between them |
| Chart | Bars + cumulative line | **Monthly bars**, dashed line at the
average, no cumulative |
| Largest expenses | top 10 | **not rendered** — across an open-ended
span the biggest single transaction is trivia, and the payee and
category breakdowns already answer where the money went |
| Category · payee · account · label | unchanged | unchanged |

Footer names the months covered rather than counting days. When income
is a meaningful share the cards report net figures and the chart adds
income bars.

### Only whole months count

Every monthly figure covers calendar months the series spans end to end.
Both edges would otherwise drag the average down, in the same direction:

- The **trailing** month is still in progress — on the 2nd it holds two
days of spending.
- The **leading** month is partial whenever the series does not start on
its 1st, whether a filter clipped it or the first transaction simply
landed on the 18th.

Skipping only the trailing one manufactured a rise: flat €300/month over
a 120-day span starting 18 March reported **+16%** in amber on spending
that never changed. Both are excluded now, which is what the one new
backend field (`summary.first_date`) is for. The part-month bars are
faded rather than dropped, so the solid bars are exactly the months
behind the average.

The average card states how many whole months it spans and the
percentage says it is against the average — two figures that otherwise
silently covered less than they appeared to.

### Edge cases

- Forcing the view onto a span with no whole month falls back to the
bounded shape, toggle label included, and the popover says why.
- The recent card is hidden when whole months do not outnumber its own
window, rather than repeating the overall average.
- A **day override** is the user stating the real duration, so it
decides the automatic view too: a trip whose transactions posted over
eight months stays bounded instead of jumping to trend and leaving that
override inert.

## Cost

**Backend: one enum case and one summary field.** No migration —
`analysis_mode` is already a nullable string behind `Rule::enum`. Every
other figure is derived in the browser from the `over_time` series the
endpoint already returned.

## Tests

`resolveAnalysisView`, `monthlyRates` and `isAdverseChange` are pure and
unit-tested directly — the part-month cutoff, the change against a
negative average, the zero-average guard, and the adverse-direction rule
that inverts for net. 32 component tests, plus feature coverage for the
new field and the persisted mode.

## QA

Browser QA against a year of grocery spending on the demo account (352
transactions, July 2025 – July 2026): the trend view resolves
automatically, all four options switch correctly, and a 30-day date
filter still lands on the bounded view. 22 assertions, no console
errors.

## Demo


https://github.com/user-attachments/assets/f4a14349-3d58-4da4-b85c-9a4ca076551f
2026-07-26 17:03:52 +02:00
Víctor Falcón 1bd2d80b14
fix(budgets): keep per-transaction email notifications opt-in (#735)
Budget email notifications shipped opt-in, then #733 turned all three on
by default. The per-transaction notice is the wrong one to force on: it
emails on **every single transaction** assigned to a budget, and a
catch-all budget matches all of them. This puts it back to opt-in and
leaves the limit alerts (close to limit, over limit) on by default.

## Why a second migration instead of editing the first one

`2026_07_24_100000_enable_budget_notifications_by_default` **has already
run in production** (batch 76). Laravel never re-runs an applied
migration, so editing it in place would have been inert: 382 budgets and
174 settings rows would keep the flag on, and the `user_settings` column
default would stay `true`.

That default matters beyond new signups: every settings controller
writes its own column through `setting()->updateOrCreate(...)`, so a
user who merely changed their chart colour scheme would get a settings
row with `budget_notify_on_new_transaction = 1` filled in by MySQL —
silently opted in, with the checkbox rendering as checked.

So the original migration is restored to its merged form and a new one
resets the flag: column default back to `false`, plus a one-off reset of
existing `user_settings` and `budgets` rows. It uses the query builder,
so `updated_at` is untouched — same as the force-enable did. 381 of the
382 affected budgets had not been touched by their owner since the
deploy, so the reset undoes a force-enable rather than a user's choice.

## Changes

- New migration resetting
`user_settings.budget_notify_on_new_transaction` (default + rows) and
`budgets.notify_on_new_transaction`.
- `BudgetController::store` and
`NotificationPreferenceController::index` fall back to `false` for the
per-transaction flag when a user has no settings row.
- `UserSettingFactory` matches the new default.

Users who want the per-transaction notice can still turn it on per
budget, or as their default for new budgets, in Settings →
Notifications.

## QA

Ran the migration against a real database and checked the end state:
`budget_notify_on_new_transaction` default `0` with all 151 settings
rows and 333 budgets reset, both limit flags default `1` and left on.

Then drove real transactions through the listener and queue on a live
budget (limit €300) and read the resulting mail off Mailhog:

| Event | Spent / limit | Email |
| --- | --- | --- |
| New transaction, default settings | €50 / €300 | none |
| Reaches 90% | €270 / €300 | «Presupuesto de Ocio» está cerca de su
límite |
| Exceeds the limit | €320 / €300 | «Presupuesto de Ocio» ha superado su
límite |
| New transaction, after opting in | €10 / €5000 | Nueva transacción en
«Presupuesto de Ocio» |

Assignment still happens in every case — only the email is suppressed.
265 tests green across the Budget/Setting/Notification suites, including
new assertions that the rendered defaults have the per-transaction flag
off and that a settings row created without the budget columns does not
opt the user in.
2026-07-25 12:36:13 +02:00
Víctor Falcón 21b1b74fb5
feat(landing): add Marta Bordiu testimonial (#734)
## What
Adds a testimonial from Marta Bordiu to the landing page testimonial
wall, placed just before the co-owner's entry.

Sourced from a user email: she'd held off on finance apps over
data-privacy concerns, trusted Whisper Money enough to go premium, and
loves centralizing everything (investments included).

## Changes
- `resources/js/pages/welcome.tsx` — new testimonial entry (name +
Gravatar hash, no email stored in source)
- `lang/es.json` — Spanish translation for the new `__()` string

## Notes
Only the display name and the Gravatar MD5 hash are stored — no customer
email is exposed.
2026-07-24 13:45:50 +00:00
Víctor Falcón 045466f70d
feat(budgets): enable email notifications by default and coalesce alerts per transaction (#733)
## What

Follow-up to #731 (per-budget email notifications). Two changes:

1. **Enable budget email notifications by default.** They shipped opt-in
with every toggle defaulting to `false`, so no one received them. They
are now on by default.
2. **Coalesce budget alerts into one email per transaction.** A single
transaction that crossed a budget's limit could send two emails for the
same budget (the "new transaction" notice *and* the over/close-limit
alert). Now at most one email is sent per budget per assignment.

## Enable by default

- `user_settings.budget_notify_on_*` column defaults flipped to `true`,
and **all existing `user_settings` and `budgets` rows are backfilled to
`true`** so current users and budgets start notifying — not just new
ones.
- `BudgetController::store` and
`NotificationPreferenceController::index` fall back to `true` when a
user has no settings row yet.
- `UserSettingFactory` reflects the new default.
- The `budgets` columns keep their own `false` DB default on purpose:
new budgets are seeded from the user's `user_settings` defaults at
creation, so only the one-off backfill is needed there.

## Coalescing

`BudgetNotificationService::processPeriod` now sends **at most one email
per budget per transaction assignment**, picking the most severe
applicable event with priority **over-limit > close-to-limit >
new-transaction**, and passes the triggering transaction through to
whichever fires. So a transaction that pushes a budget over its limit
produces a single over-limit email that still names the transaction and
shows how far over the budget is.

Preserved from #731: the atomic per-period `close_to_limit_notified` /
`over_limit_notified` claim (one email per crossing, safe under
concurrent workers), the reset-and-re-notify path when spending drops
back below the threshold, and the no-emails-on-historical-backfill
guarantee. Coalescing is **per budget** — a transaction matching two
different budgets still sends one email to each.

## Trade-offs (deliberate)

- **`notify_on_new_transaction` is on by default**, which means one
email per transaction assigned to any budget (no batching yet — flagged
in #731). A catch-all budget matches every expense, so this can be
high-volume; the whole-user-base backfill also produces a send spike on
first sync after deploy. Batching the new-transaction type into a daily
digest (mirroring the bank-sync digest) is the natural follow-up if
volume proves noisy.
- The migration backfill is intentionally unconditional and one-way for
data: `down()` restores the column defaults but not the backfilled row
values.

## Every email links to the settings page

Each budget email already carries a "Manage notifications in
notification settings" link (`route('notifications.index')`) so users
can turn any of them off. A render-test assertion now locks this in.

## Tests

- Coalescing: a single limit-crossing transaction sends exactly one
over-limit email that references the triggering transaction.
- On-by-default: a new budget created without custom preferences enables
all three types.
- All existing #731 sending/preference tests still pass (dedup,
re-notify after drop, no-limit budgets, historical backfill sends
nothing, enabling while already over).

QA (backend): rendered the coalesced over-limit email and confirmed it
names the transaction, shows "Over by", and links to the settings page;
verified the migration backfill flips pre-existing `false` rows to
`true` against a real DB.
2026-07-24 15:33:14 +02:00
Jesús Mejías Leiva 24fcdef098
feat(docker): run the Laravel scheduler in the production image (#732)
## Problem

The production image runs the queue workers via supervisor but **nothing
runs the Laravel scheduler** (there is no `schedule:work` program and no
cron running `schedule:run`). As a result, none of the commands in
`routes/console.php` ever fire automatically — most notably
`banking:sync` (every 6h), so self-hosted users have to trigger bank
synchronization by hand. The manual "sync" button works because it
dispatches the same job to the queue, which the existing workers pick
up; only the scheduled trigger was missing.

## Changes

- **`docker/supervisor/supervisord.conf`**: add a `[program:scheduler]`
running `php artisan schedule:work`, mirroring the existing worker
programs (autostart/autorestart, dedicated log). This is what makes
every scheduled command fire on its own cadence.
- **Gate the operator-only stats reports** (`stats:daily-report`,
`stats:subscription-funnel`, `stats:ai-cohort-report`,
`stats:experiment-funnel`) behind `config('subscriptions.enabled')` with
an early return. These are subscription-conversion telemetry destined
for the admin Discord; on a self-hosted instance
(`subscriptions.enabled=false`) `stats:daily-report` would otherwise
make an unnecessary live Stripe API call, and the others would build
reports for an unconfigured Discord channel. On the SaaS (subscriptions
enabled) behavior is unchanged.

The guard lives **inside each command** (not in `routes/console.php`) so
it stays unit-testable. `banking:cancel-free-enablebanking` was left
alone (already a safe no-op via `hasProPlan()` when subscriptions are
off), as were the drip-email commands (already gated by
`mail.drip_emails_enabled`).

## Testing

- `vendor/bin/pint --test` passes.
- New Pest test per gated command asserting it skips and makes no
external call when subscriptions are disabled; existing tests updated to
enable subscriptions so they still exercise the real path.
- Full suite green except 5 unrelated pre-existing environment failures
(timezone alias, dashboard 409, Passport OAuth key) that fail
identically on `main`.
- Verified end-to-end with a real supervisor run: the `scheduler`
program reaches `RUNNING`, `schedule:work` boots, and autorestart
resurrects it; `php artisan schedule:test --name=banking:sync`
dispatches successfully.

> Takes effect after rebuilding the production image.
2026-07-24 13:30:33 +02:00
Víctor Falcón 0351dbfb38
feat(budgets): add per-budget email notifications (#731)
## What

Adds opt-in **email notifications per budget** for three events, plus a
dedicated **Notifications** settings page.

Each budget can independently enable:
- **New transaction** — a transaction was assigned to the budget
- **Close to limit** — spending crossed 90% of the limit
- **Over limit** — spending reached/passed the limit

A **Default (new budgets)** row lets you set the toggles that newly
created budgets inherit.

The existing *bank-transactions-synced* email toggle was **moved** from
the account page into this new Notifications page, so all email
preferences live in one place.

## UI

`Settings → Notifications`: one "Email notifications" section containing
the bank-sync toggle and a "Budgets" table (rows = Default + each
budget, columns = the three events).

<img width="1265" height="638" alt="budget-notifications-settings"
src="https://github.com/user-attachments/assets/b8386410-98dd-4a5e-9dee-6e5bf7effa31"
/>

## How it works

- Notifications fire from the **live transaction-assignment path**
(`BudgetTransactionService::assignTransaction`, already a queued
listener), never from historical backfill when a budget is created.
- Only the budget's **current period** is considered (the emails
describe the live "available before the limit" state).
- **New transaction** fires for a genuinely newly-assigned transaction;
the email includes the transaction.
- **Close/over** use two atomic per-period flags
(`close_to_limit_notified` / `over_limit_notified`) flipped with a
compare-and-set `UPDATE`, so exactly one email is sent per crossing even
under concurrent queue workers. The flags reset once spending drops back
below the close threshold, so a later crossing can notify again.
- Budgets with no limit (`allocated_amount <= 0`) never send close/over
emails; the "new transaction" email for such a budget omits the
limit/available rows.
- Every email shows the budget's current status (period, spent, limit,
available or over-by). Subcopy links back to the Notifications page.
- New budgets inherit the user's default toggles at creation time.

## Data model

- `budgets`: `notify_on_new_transaction`, `notify_on_close_to_limit`,
`notify_on_over_limit` (default `false`)
- `user_settings`: `budget_notify_on_*` defaults for new budgets
(default `false`)
- `budget_periods`: `close_to_limit_notified`, `over_limit_notified`
(dedup flags)

## Deliberate decisions

- **Threshold is a fixed 90%** for "close to limit" (not configurable) —
kept simple; easy to make per-budget later if requested.
- **"New transaction" sends one email per assigned transaction.** It is
opt-in and defaults to off. A bank sync importing many matching
transactions into an opted-in budget will therefore send several emails;
if this proves noisy we can batch per sync run (mirroring the daily
bank-sync digest). Flagged here rather than pre-building batching.
- **Limit basis is `allocated_amount`** (matches the budget
cards/spending chart), carry-over excluded.

## Tests

- Preference endpoints: page renders budgets + defaults, per-budget
toggle update, cross-user update forbidden, user-settings defaults
update, new budget inherits defaults.
- Sending: new-transaction opt-in/out, over-limit send, close-limit at
90%, no-resend dedup, re-notify after dropping below and crossing again,
no-limit budget skips close/over, historical backfill sends nothing,
notify after enabling the preference while already over. Plus a render
test covering all three email variants.

## Notes

- CI-enforced `es.json` keys for the new page and emails are included.
- All new PHP follows existing mail/queue conventions (`ShouldQueue`
mailable, `emails` queue, `RateLimited` middleware).
2026-07-24 12:52:03 +02:00
Víctor Falcón 2be0df25c6
feat(billing): explain what AI categorization does and the data it sends (#730)
## What

Makes the **AI Categorization** feature more transparent on the Manage
Plan screen:

- **Moves the AI Categorization section to the top** of the page — it's
an important, privacy-relevant choice and shouldn't be buried below the
plan details.
- **Spells out exactly what enabling it does**, as two ordered steps:
1. **Categorize new transactions** that don't match any of your
automation rules.
2. **Learn your automation rules** — suggest and create automation rules
for recurring transactions, based on the corrections you make.
- **States exactly what data leaves the app**: each transaction's
description, amount, and merchant/sender name, plus the names of your
categories so the model can pick one. It also makes clear we **never
send your full financial picture** and your **data is never used to
train AI models**.

The copy was verified against the actual payload sent to the provider
(`app/Services/Ai/CategorizeTransactions.php`), which sends
`description`, `amount`, `creditor_name`/`debtor_name`, and the user's
category list.

## Screenshots
<img width="2840" height="2636" alt="manage-plan-ai-light"
src="https://github.com/user-attachments/assets/87e1451b-d224-444e-957d-2b401e4c766a"
/>
<img width="2840" height="2636" alt="manage-plan-ai-dark"
src="https://github.com/user-attachments/assets/807d715a-61f7-493a-b4fd-2fb014966564"
/>

Manage Plan → AI Categorization (light & dark), section now at the top
with the two steps and the transparency note.

## Part of #725

This delivers the **transparency** half of #725 (a plain-language
explanation of what the AI does and what data it receives). Still open
from that issue:

- The dedicated **"AI" settings section visible regardless of
`SUBSCRIPTIONS_ENABLED`** — this copy currently lives on the
(subscription-gated) Manage Plan screen, not a standalone AI section.
- The **connection status / "Test connection" health check** for the
configured provider.

## Testing

- `bun run format`, `bun run lint` clean.
- New `__()` keys added to `lang/es.json` and `lang/fr.json`; retired
the now-unused consent string.
- QA'd in the browser (light + dark) on the demo Pro account.
2026-07-24 08:22:10 +00:00
Víctor Falcón 8382a56e98
feat(ai): add command to delete a user's AI consent by email (#729)
## What

Adds an Artisan command to delete a specific user's AI consent by email:

```bash
php artisan ai:delete-consent user@example.com
```

It looks up the user by email and **hard-deletes** all their AI consent
records — as if they had never granted it (no `revoked_at` trail left
behind). Since `AiCategorizationGate` requires `hasActiveAiConsent()`,
AI stops being used for that account immediately (queued categorization
jobs re-check the gate at execution time and early-return).

The command is idempotent: it reports "nothing to do" when there's no
consent on record and fails cleanly when the email doesn't exist.

## Why

Two goals:

1. **Stop using AI for a given user** on request, with no lingering
consent record.
2. **Let users who enabled AI by mistake fall back to a free plan.**
Non-Pro users with active AI consent are pushed toward the paid plan by
`EnsureUserIsSubscribed`. Deleting consent moves them back into the
free-plan-eligible bucket. This billing-gating change is **intended**,
not a side effect.

## Notes / scope decisions

- **Hard delete, not revoke.** Removes every consent row for the user
(all scopes/versions) so there's no trace they ever consented.
- **Prompt flag untouched.** `ai_consent_prompt_dismissed_at` is left
as-is, so the in-app consent banner does not re-appear to nudge them
back on.
- **Live users only.** Deleted (soft-deleted) accounts are out of scope
— they can't use the app, so their consent is moot.
- **No subscription changes.** The command only touches AI consent; it
doesn't cancel Stripe subscriptions (`user:delete` already handles that
separately).

## Tests

New Pest feature test covering all three paths (delete all consent
records incl. a revoked one / no consent on record / user not found).
Green locally.
2026-07-23 08:35:28 +00:00
Víctor Falcón ca084ce5d1
feat(commands): delete transactions and balances of a user's non-connected accounts (#728)
## What

Adds an artisan command that deletes all transactions and balances of a
specific user's **non-connected** (manual) accounts, identified by
email.

```bash
php artisan user:delete-manual-account-data user@example.com
```

## Behavior

- Looks up the user by email (`withTrashed`, matching `user:delete`).
- Selects accounts with `banking_connection_id IS NULL` (manual
accounts).
- Shows a confirmation prompt with the transaction/balance counts and
the number of affected accounts.
- On confirm, deletes inside a `DB::transaction`:
- Transactions via `forceDelete()` (they use `SoftDeletes`, so this also
purges already soft-deleted rows).
- Balances via `delete()` (`AccountBalance` has no `SoftDeletes`, so
it's a hard delete).
- The accounts themselves are **not** deleted — only their transactions
and balances.

Related `label_transaction`, `budget_transactions` and
`category_corrections` rows are cleaned up by existing
`cascadeOnDelete()` foreign keys.

## Tests

Pest feature test covering: manual-only deletion (connected accounts
untouched), cross-user isolation, soft-deleted transactions counted and
purged, connected-only user reports zero, cancellation, and
user-not-found.

QA skipped per request (backend maintenance command, covered by feature
tests).
2026-07-23 08:26:11 +00:00
Víctor Falcón bd1ad633f8
feat(mcp): filter search_transactions by label (#724)
## What

Adds label filtering to the `search_transactions` MCP tool. It's the one
filter the web transactions view has that the MCP surface was missing.

- New optional `label_ids` array param. Returns transactions carrying
**any** of the given labels (OR-semantics), matching the web app's label
filter (`Transaction::scopeApplyFilters`).
- Combines with the other filters (account, category, date, amount) with
AND, consistent with how the tool already treats them — so `category_id`
+ `label_ids` means "in that category **and** carrying one of these
labels".
- Each returned transaction now also exposes its `labels` (`id`,
`name`), so the agent can see why a row matched, consistent with what
the write tools already return.

## Validation & consistency

- `label_ids` are validated against the space via `labelsInSpace`,
promoted from `WriteTool` to the shared `McpTool` base so read and write
tools use one implementation. An unknown or stale label id now returns
the same actionable *"call list_labels"* error the rest of the MCP
surface gives, instead of a silent empty result.
- The tool `#[Description]` now mentions `label`, so agents discover the
capability without inspecting each param.

## Tests

- `search_transactions` filters by label id (matching row in, unlabelled
row out).
- A foreign/unknown label id is rejected with an error.
- Full MCP read + write suites stay green (26 tests) — confirms moving
`labelsInSpace` to the base didn't regress the write tools.

Pint, Larastan and the affected Pest suites pass locally.
2026-07-22 15:13:03 +02:00
Víctor Falcón fb5027b321
fix(oauth): stop reporting client-facing OAuthServerException to Sentry (#723)
## Problem
Sentry **PHP-LARAVEL-4Q** fires on POST `/mcp/oauth`: a client presents
a bearer token with a bad/expired/wrong JWT signature ("Token signature
mismatch"), Passport's `TokenGuard` → league/oauth2-server throws
`OAuthServerException::accessDenied` (HTTP **401**). Laravel returns the
correct 401 to the client (`handled: yes`) **but also reports it to
Sentry as an error** — noise, not a server fault. It's recurring (fresh
events after the initial ones).

These OAuth exceptions are, by design, client-facing 4xx protocol
responses (expired/invalid tokens, denied consent, bad grants). Any
public OAuth endpoint — and the MCP endpoint accepts
dynamically-registered Claude/ChatGPT clients — sees a steady stream of
them. They should not page as errors.

`OAuthServerException` does not implement `HttpExceptionInterface`, so
Laravel's built-in `internalDontReport` does not already cover it.

## Fix
Add a `dontReportWhen` rule in `bootstrap/app.php` for
`OAuthServerException` whose HTTP status is **< 500**, mirroring the
existing `MaxAttemptsExceededException` guard right above it.
`serverError` (500) — the only 5xx variant, the genuine "unexpected
condition" case — still reports, so real OAuth-flow faults stay visible.

**Reporting-only change — no user-facing behavior changes.** Clients
still receive the same 4xx OAuth error responses (status/body/headers
unchanged).

## Tests
`tests/Feature/Mcp/McpOAuthTest.php`: assert
`ExceptionHandler::shouldReport()` is `false` for `accessDenied()` (401)
and `invalidCredentials()` (400), and `true` for `serverError()` (500).

## Notes
- Two independent reviews (architecture + product/bug): no must-fix,
both "ship as-is".
- Follow-up (not code): a mass signing-key mismatch would fail as
`access_denied` (401) and thus be suppressed here — the right way to
catch that is an MCP success-rate / 401-rate alert, not error-count.
Worth adding as an alert later.
2026-07-22 12:40:24 +00:00
Víctor Falcón 50d0fccd17
fix(dashboard): render negative net worth as a downward bar (#722)
## Problem

On the dashboard **Net Worth Evolution** monthly bar chart, users with a
large negative net worth (lots of debt) saw an **empty chart** — only
the x-axis month labels rendered, no bars.

Root cause: the chart scales each asset segment so the stacked bar
height equals net worth. For negative net worth the scale factor was
clamped to zero:

```ts
const scaleFactor = hasLiabs && totalAssets > 0
    ? Math.max(0, netWorth / totalAssets) // negative net worth -> 0 -> every bar collapses
    : 1;
```

A stack of positive asset segments simply can't represent a negative
total, so everything collapsed to zero height.

## Fix

- Extract the scaling into a tested pure helper
`computeNetWorthBarScaling`.
- When net worth is **negative**, hide the (meaningless) scaled asset
segments and draw the deficit as a **single downward bar** from a **zero
baseline** (dashed reference line).
- **Positive** periods still stack assets upward. Both directions round
only at their far end and meet the zero line flush, so upward and
downward bars look symmetric.
- Extend the same handling to the **daily area chart**, which shared the
bug through the same scaled dataset.
- Share a single `NetWorthMode` type across the bar/area charts and
tooltip (was duplicated in three places).
- Translate the tooltip **Net Worth / Total** labels (were hardcoded
English; added `Net Worth` to `lang/es.json`).
- Render the chart for **liability-only** users (a debtor with just a
loan) instead of the "No account data available" empty state.

## Tests

- Unit tests for `computeNetWorthBarScaling`: no-liabilities, positive,
negative-with-assets, liabilities-only, net-worth-exactly-zero, and
no-assets cases.
- `bun run test`, `prettier --check`, `eslint` all green on the touched
files.

## QA

Verified in the running app (Playwright) with two seeded users:

- **Heavily indebted** (net worth −56.250,00 €): the chart now renders
red downward bars instead of an empty area.
- **Net worth crossing zero**: negative months draw downward, positive
months stack upward, sharing the zero baseline; tooltip shows
per-account balances + the (now translated) "Patrimonio Neto" total.

## Demo


https://github.com/user-attachments/assets/7a9b167f-c037-4c82-8b68-f32932be99fe

## Screenshots

**Before** — empty chart, only x-axis labels:

<!-- PLACEHOLDER: before screenshot -->
<img width="1440" height="900" alt="net-worth-before"
src="https://github.com/user-attachments/assets/3bf9b3e3-ae75-4230-bca7-e7246a9a35d9"
/>


**After** — negative net worth as downward bars:
<img width="1440" height="900" alt="net-worth-after-tooltip"
src="https://github.com/user-attachments/assets/85302f0a-e427-4cbf-baba-5b1414049e9f"
/>
<img width="1440" height="900" alt="net-worth-after-mixed"
src="https://github.com/user-attachments/assets/41f08331-f055-4245-beeb-8d071c0d5d6d"
/>
<img width="1440" height="900" alt="net-worth-after-negative"
src="https://github.com/user-attachments/assets/c8610b03-dcff-46de-8987-d47c477ddd85"
/>
2026-07-22 09:32:18 +00:00
Víctor Falcón 9e1aedcccd
feat(settings): make mobile settings nav read as a tappable menu (#721)
## Problem

On mobile, many users don't realize the dropdown at the top of Settings
is a navigation menu — they don't know they can tap it. The trigger was
a shadcn `Select` left with the default form-field look (transparent
background, faint chevron), so once you're on a page it reads as a
static label rather than a control.

## Change

Restyle the mobile settings-nav `SelectTrigger` (in
`resources/js/layouts/settings/layout.tsx`) so it reads as a tappable
menu button:

- `bg-muted` — filled background instead of a transparent input.
- `h-11` — 44px touch target (recommended mobile minimum, up from 36px).
- `font-medium` — the label reads as a control, not plain text.
- `[&>svg:last-child]:opacity-100` — the chevron goes from
barely-visible to a clear "this opens" affordance.

Scope is the mobile block only (`lg:hidden`); the desktop sidebar is
untouched. Uses theme tokens, so light and dark mode are both covered.

## Demo
<img width="390" height="844" alt="settings-menu-dark-open"
src="https://github.com/user-attachments/assets/9ed7856a-0048-40a2-8e6e-07b24b4cb844"
/>
<img width="390" height="844" alt="settings-menu-dark-closed"
src="https://github.com/user-attachments/assets/5b8b2b7a-c31c-4c55-b224-1f87f554e361"
/>
<img width="390" height="844" alt="settings-menu-light-open"
src="https://github.com/user-attachments/assets/4f6abb55-38b8-4e38-9322-12b555082dad"
/>
<img width="390" height="844" alt="settings-menu-light-closed"
src="https://github.com/user-attachments/assets/e08babf7-fe9d-46d7-abd6-329962d34eaf"
/>

## Testing

Pure Tailwind class change with no behavior change (the `Select` →
`router.visit` navigation is unchanged), so no unit test is added — a
CSS-class assertion would be brittle. Verified live in the browser at
mobile width in both light and dark mode, closed and open.
2026-07-22 11:03:27 +02:00
Víctor Falcón 87c63f2100
fix(auth): make build deterministic when REGISTRATION_ENABLED=false (#720)
## Problem

`bun run build` failed whenever `REGISTRATION_ENABLED=false`.

`config/fortify.php` only added `Features::registration()` when the env
flag
was truthy, so with the flag off Fortify never registered the
`/register`
routes. Wayfinder only generates helpers for registered routes, so the
`register` / `register.store` helpers imported by
`resources/js/pages/auth/login.tsx`
and `resources/js/pages/auth/register.tsx` no longer resolved and the
build
broke. The build outcome depended on an env flag — not deterministic.

## Fix

Decouple *route registration* from *whether sign-ups are accepted*:

- **Always register** `Features::registration()` in
`config/fortify.php`, so the
`/register` routes (and their Wayfinder helpers) always exist and the
build is
  deterministic regardless of the flag.
- Gate acceptance at **runtime** via a new
`config('auth.registration_enabled')`
value (mapped from `env('REGISTRATION_ENABLED', true)`), the single
source of truth.
- When registration is disabled:
- `GET /register` (Fortify register view) and `POST /register`
(`CreateNewUser`)
    return **403**.
- Registration CTAs stay hidden via `canRegister` (login view + landing
page).
- Guests are redirected to `/login`
(`AuthEntryPointService::guestRedirectRoute`).
- With the flag enabled (the default), registration behaves exactly as
before.

## Tests

- Rewrote `tests/Feature/Auth/RegistrationDisabledTest.php` to the
runtime
mechanism: registration enabled by default, route helpers always
registered
regardless of the flag, `GET`/`POST /register` return 403 when disabled
(and no
  user is created), and the landing/login CTAs hide.
- Updated the `DashboardTest` disabled-registration case to toggle
`config('auth.registration_enabled')` instead of filtering the Fortify
feature.
- Verified `bun run build` succeeds with `REGISTRATION_ENABLED=false`
and that the
  `register` / `register.store` Wayfinder helpers are generated.

## Docs

- Updated `README.md` and `.env.example` to describe the 403 behavior
(routes stay
  registered rather than being removed).
2026-07-22 07:04:20 +00:00
Jesús Mejías Leiva 350e0031f1
feat(ai): make the AI provider configurable (any laravel/ai provider, incl. local Ollama) (#718)
## Summary

Closes #716.

Both AI execution paths hard-coded `provider: Lab::Gemini`, so even
though `laravel/ai` already understands `OLLAMA_URL` and the model was
env-overridable, no other provider could ever be reached by the actual
UI features. This makes the **AI provider configurable**, keeping
**Gemini as the default** so existing deployments are unaffected.

Although issue #716 asked specifically for **Ollama**, the fix is
generic: because the provider is resolved through the
`Laravel\Ai\Enums\Lab` enum, this unlocks **any text provider
`laravel/ai` supports** — `gemini`, `openai`, `anthropic`, `azure`,
`groq`, `xai`, `deepseek`, `mistral`, and self-hosted `ollama`. Ollama
is the headline case (fully local, private processing), but nothing in
the code is Ollama-specific.

> Note: each provider still needs its own credentials configured for
`laravel/ai` (e.g. `GEMINI_API_KEY`, `OPENAI_API_KEY`, `OLLAMA_URL`),
and only text-capable providers apply — a non-text or unknown provider
fails fast.

## Changes

- **`config/ai_suggestions.php` / `config/ai_categorization.php`** — add
a `provider` key. Each reads its own `AI_SUGGESTIONS_PROVIDER` /
`AI_CATEGORIZATION_PROVIDER`, both falling back to a shared
`AI_PROVIDER` and finally `gemini`. So `AI_PROVIDER=<provider>` flips
every AI feature at once, and either feature can still be overridden
individually.
- **`app/Services/Ai/CategorizeTransactions.php` /
`app/Services/Ai/LaravelAiRuleSuggestionGenerator.php`** — resolve the
configured provider to the `Laravel\Ai\Enums\Lab` enum via
`Lab::from((string) config('...provider'))` and pass it to `prompt()`
(the SDK recommends referencing providers by the `Lab` enum rather than
a plain string). `Lab::from()` also **validates** the value: an unknown
provider fails fast with a clear `ValueError` instead of erroring deep
in the provider stack.
- **`.env.example`** — document the provider vars plus an Ollama block
(`OLLAMA_URL`, `OLLAMA_API_KEY`, `AI_CATEGORIZATION_MODEL`), kept
commented so defaults stay Gemini.
- **`README.md`** — new *AI Provider* section: the generic provider
switch, the list of supported text providers, and a local-Ollama
example.
- **Tests** — cover the `gemini` default and a non-Gemini (`ollama`)
override for both the categorization and rule-suggestion paths, plus the
fail-fast `ValueError` on an unknown provider.

## Usage

Any supported provider follows the same pattern — set `AI_PROVIDER`,
that provider's credentials, and the `*_MODEL` vars. Example, fully
local/private with Ollama:

```dotenv
AI_PROVIDER=ollama
OLLAMA_URL=http://ollama.example.local:11434
AI_SUGGESTIONS_MODEL=gemma3:12b
AI_CATEGORIZATION_MODEL=gemma3:12b
```

## Validation

- `./vendor/bin/pest tests/Feature/Ai` → **128 passed**.
- `vendor/bin/pint` and `vendor/bin/phpstan` (level 5) → clean.
- **End-to-end against a real Ollama server** (`gemma3:12b`), through
the actual application code (not faked):
  - Categorization: `MERCADONA COMPRA` → *Groceries*, confidence 0.95.
- Rule suggestion: `netflix` → *Subscriptions*, structured output
intact.

## Backward compatibility

Default provider is unchanged (`gemini`); no env changes are required
for existing installs.
2026-07-22 09:01:51 +02:00
Víctor Falcón a5117aaae6
refactor: remove HIDE_AUTH_BUTTONS launch gate and waitlist apparatus (#717)
## What & why

The `HIDE_AUTH_BUTTONS` flag and its signed-link auth-override existed
only to gate registration/login behind a waitlist during the launch
period. That period is long over, so this removes the flag and the whole
waitlist apparatus. Registration and login are now always open, still
governed by `REGISTRATION_ENABLED` (Fortify's registration feature),
which is untouched.

## Removed

- **`HIDE_AUTH_BUTTONS`** config/env and
**`LandingAuthOverrideService`** — the signed-link override, override
cookie, and `?force=` bypass — plus its
`GenerateLandingAuthLinkCommand`.
- **Waitlist lead-capture + invitation apparatus**: `UserLeadController`
+ `waitlist.*`/`user-leads.*` routes, `StoreUserLeadRequest`, the
landing `WaitlistForm`, `waitlist/*` pages, waitlist/invitation mails,
invitation & re-invitation commands, the lead verification notification,
`LeadCohort`/`LeadCohortResolver`/`LeadPromoCodeAllocator`, and the
lead→Resend segment sync (scheduled tasks removed too).
- Frontend `hideAuthButtons`/`forcedRegistration` threading and the
`?force=` query on auth links (header, welcome, register, login).
- All tests for the removed features; `landing.hide_auth_buttons` config
stubs stripped from surviving tests.

## Kept on purpose (data preservation)

The `user_leads` **table, its migrations, and a lean `UserLead` model
are retained** — no destructive migration. Pre-launch contacts are not
lost, and new signups whose email matches a preserved lead still receive
that lead's promo code at Stripe checkout
(`SubscriptionController::resolveLeadPromotionCodeId`, unchanged).

## Testing

- Full non-Browser Pest suite green locally (**1948 passed**), plus
Pint, Prettier, ESLint.
- Browser QA (Playwright) on the running app: landing no longer shows
the waitlist form and renders the register/login CTAs; `/register`
renders the form (previously returned null when hidden); `/login` shows
the "Sign up" link pointing to `/register` with no `?force`. 16/16
functional checks passed; only pre-existing external-resource 404s in
console (gravatar `d=404`, `via.placeholder.com` seed images).

## Demo


https://github.com/user-attachments/assets/18a70f6d-b82f-4d92-b9de-da2610dc017a
2026-07-22 08:51:48 +02:00
Jesús Mejías Leiva d55ee5bdcd
feat(auth): add REGISTRATION_ENABLED env to disable public sign-ups (#713)
## Summary

Adds a dedicated `REGISTRATION_ENABLED` env var (default `true`) so
self-hosters on a publicly reachable instance can **close public
sign-ups while keeping login open** — the exact "sign-ups closed, login
open, permanently" case from #711 that `HIDE_AUTH_BUTTONS` can't cover.

Closes #711.

## What changed

- **`config/fortify.php`** — the Fortify `registration()` feature is now
conditional on `env('REGISTRATION_ENABLED', true)`. When disabled:
- Fortify **never registers the `/register` routes** (GET form + POST
submit → `404`), i.e. a real server-side block, not just a hidden
button.
- The existing `canRegister =
Features::enabled(Features::registration())` flag flips to `false`
automatically everywhere it's used (`routes/web.php`,
`FortifyServiceProvider`, login page).
- **`resources/js/pages/welcome.tsx`** — the hardcoded `/register` CTAs
(hero button, Free/paid pricing cards, final "Ready to take control"
CTA) now respect `canRegister`, falling back to a `Log in` → `/login`
button when sign-ups are closed. The header already gated its `Register`
button on `canRegister`.
- **`.env.example` / `README.md`** — document the new variable.

**Backward compatible / optional:** `env('REGISTRATION_ENABLED', true)`
defaults to `true`, so existing installs that upgrade without setting
the var keep public sign-ups exactly as today. It's shown as a
commented, optional example in `.env.example`.

`/login` and the "Iniciar sesión / Log in" button stay fully available
in all cases. `AuthEntryPointService::guestRedirectRoute()` already
redirects guests to `/login` when registration is disabled, so no dead
`route('register')` calls remain.

## Tests

New `tests/Feature/Auth/RegistrationDisabledTest.php`:

- registration feature present by default / removed when
`REGISTRATION_ENABLED=false` (config-level).
- landing page exposes `canRegister=true` by default and `false` when
the feature is disabled.
- login page hides its sign-up link when registration is disabled.
- **`/register` GET + POST return 404 and the named routes are gone**
when disabled (via `refreshApplication()` with the env set), while
`/login` still returns 200.

All new tests pass; the wider `tests/Feature/Auth` + landing-override
suites stay green (the one unrelated `Asia/Calcutta` legacy-timezone
failure is a pre-existing tzdata quirk of the CI-less local box, not
touched here). `pint`, `prettier --check`, and `eslint` are clean.

## Manual QA

Verified against a running instance (headless Chromium) in both states:

| `REGISTRATION_ENABLED=true` (default) | `REGISTRATION_ENABLED=false` |
| --- | --- |
| Header: `Log in` + `Register`; hero CTA `Get Started` → `/register` |
Header: `Register` gone, only `Log in`; hero CTA `Log in` → `/login` |
| `GET /register` → `200` | `GET /register` → `404`, `GET /login` →
`200`, `Route::has('register')` → `false` |
2026-07-21 16:22:45 +02:00
Víctor Falcón d1f3b0203b
fix(mcp): correct the ChatGPT and Claude connector steps (#714)
Fixes the step-by-step instructions on the AI Connector screen to match
the current app UIs.

**ChatGPT**
- Developer mode is under **Settings → Security and login → Developer
mode** (was: Settings → Connectors → Advanced).
- Add a connector via the **+ button in Plugins, top right** (was: a
"Create" button under Connectors).

**Claude Desktop**
- Click **"Add" in the top right, then "Add custom connector"** (was:
just "Add custom connector").

Spanish translations updated in `lang/es.json` accordingly.
2026-07-21 13:37:47 +00:00
Víctor Falcón 2827df9685
feat(mcp): recommend desktop for AI connector setup (#712)
## What

Adds a short note at the top of the "How to connect" card on the AI
Connector screen (`settings/mcp.tsx`):

> **Set this up on a computer.** Signing in and approving works fine in
a desktop browser, but usually breaks in a phone's in-app browser. Once
it's connected, you can chat with Whisper Money from Claude or ChatGPT
on your phone as usual.

## Why

The OAuth sign-in + consent step is unreliable inside a phone's in-app
browser (the installed PWA captures the authorize link on Android).
Rather than fight every mobile edge case, steer people to create the
connection on desktop, where it works cleanly — the connection then
carries over, so they can chat from the mobile apps normally.

Copy run through the humanizer (no em dashes, plain and direct). Spanish
translation added to `lang/es.json` (required by the i18n CI check).
2026-07-21 12:58:13 +00:00
Víctor Falcón 2041181dc2
fix(mcp): serve OAuth authorize on a dedicated host so the PWA can't capture it (#709)
## Problem

Connecting the MCP connector from **ChatGPT on Android** fails. The
installed Whisper Money PWA is a Chrome **WebAPK** that auto-verifies as
an Android **App Link handler** for the whole app origin (manifest
`scope: "/"`), so `https://whisper.money/oauth/authorize` gets routed
**into the app**. Once inside the standalone app, the redirect back to
the OAuth client can't complete → the connection fails. (Claude works
because it opens OAuth in a Custom Tab.)

Confirmed on an Android emulator: the WebAPK shows `AutoVerify=true`,
`whisper.money: verified`. DB evidence: ChatGPT registers + reaches
consent (auth codes issued) but never exchanges a token.

## Why not `handle_links`

`handle_links: "not-preferred"` (tried in #707, reverted in #708) is
**origin-wide** — it would push *every* `whisper.money` link (bank-auth
callback, email verification, shared deep links) to the browser, not
just `/oauth`. We want links to keep opening the installed app.

## Fix (surgical)

Move the OAuth **authorization server** to a dedicated host outside the
PWA scope. `config('mcp.authorization_server')` becomes env-driven
(`MCP_AUTHORIZATION_SERVER`); in prod → `https://oauth.whisper.money`
(DNS already points at the same app).

Every endpoint derives from the request host (no forced root URL), so
pointing the auth server at the subdomain makes `issuer` +
`authorize`/`token`/`register` all resolve to `oauth.whisper.money` —
**same origin as each other**, no cross-origin metadata mismatch. The
protected resource (`/mcp/oauth`) and **all other app links stay on
`whisper.money`**, so deep-linking into the app is fully preserved. Only
the OAuth flow leaves the app — into the browser, where the round-trip
completes.

## Activation (after merge + deploy)

1. Set `MCP_AUTHORIZATION_SERVER=https://oauth.whisper.money` in prod
env, redeploy.
2. I'll curl the discovery chain to confirm it resolves to the
subdomain.
3. Test the ChatGPT connect on a real phone.

Safe until step 1: env unset → `authorization_server` stays `null` →
current behavior. No effect on local/dev.

## Tests

Added a Pest test: with `mcp.authorization_server` configured,
protected-resource metadata advertises the dedicated host and
auth-server metadata (fetched from that host) keeps `issuer` + all
endpoints on it. App has no `TrustHosts` restriction (already serves the
subdomain) and `SESSION_DOMAIN=null` (host-only cookies — subdomain gets
its own session, no security downgrade).
2026-07-21 13:51:03 +02:00
Víctor Falcón 13360ce0b8
revert(pwa): drop handle_links to keep app deep-linking (#708)
Reverts the `handle_links: "not-preferred"` manifest change from #707.

It's origin-wide: it would route **every** `whisper.money` link (bank
auth callback, email verification, shared deep links) to the browser
instead of the installed app — not just `/oauth`. We want links to keep
opening the app when it's installed.

The OAuth-capture fix will instead be surgical: move the interactive
`/oauth/authorize` endpoint to a dedicated host (`oauth.whisper.money`)
outside the PWA scope, so only OAuth leaves the app and all other
deep-linking is untouched. That lands in a follow-up PR (needs DNS +
testing).

This restores the manifest to its original state (no PWA link-handling
hacks).
2026-07-21 13:40:13 +02:00
Víctor Falcón 1b30e7edc0
fix(pwa): open OAuth links in the browser instead of the installed app (#707)
## Problem

Connecting the MCP connector from **ChatGPT on Android mobile** fails.
Claude works because it opens the OAuth flow in an in-app browser
(Custom Tab); ChatGPT's link gets routed into the installed Whisper
Money PWA, and once the flow is inside the standalone app the redirect
back to the OAuth client can't complete.

## Root cause (confirmed on an Android emulator)

The installed PWA is a Chrome **WebAPK** that auto-verifies as an
**Android App Link handler** for the whole origin (`scope: "/"`):

```
AutoVerify=true
Domain verification state: whisper.money: verified
```

So Android routes `https://whisper.money/*` — including
`/oauth/authorize` — into the app instead of a browser. Narrowing
`scope` to exclude `/oauth` isn't viable: the app's routes are flat and
share no prefix.

## Fix

Set `"handle_links": "not-preferred"` in the web app manifest, which
tells the browser **not** to route in-scope links into the installed app
— they open in the browser, where the OAuth round-trip (authorize →
consent → redirect back to the client) completes. The app still launches
normally from its home-screen icon.

This **replaces** the `launch_handler` + `launchQueue` approach from
#701, which targeted the wrong stage (it kept the flow *inside* the
PWA). That change is reverted here.

## Verification / caveat

`handle_links` on Android WebAPKs has incomplete/uncertain support, and
it couldn't be validated in isolation on the emulator (a throwaway test
domain never minted its own WebAPK). It's a safe, additive, reversible
manifest field — worst case it's a no-op.

**Must be verified on a real device:** after deploy, reinstall the PWA
on the phone (forces the WebAPK to re-mint from the new manifest) and
retry the ChatGPT connect → the authorize page should open in the
browser, not the app.

If Android ignores `handle_links`, the guaranteed fallback is narrowing
the PWA `scope` so `/oauth` is out of it (at the cost of the browser
toolbar appearing on hard reloads of non-`/dashboard` pages).
2026-07-21 13:24:50 +02:00
Jesús Mejías Leiva a2dfdb7442
fix(ci): publish the production image as :latest so Docker/Coolify deploys work (#706)
## Problem

Following the official production deployment instructions (Docker
Compose or Coolify), the app container enters a restart loop with:

```
Could not open input file: artisan
```

Reproducible outside Coolify by pulling the published image directly:

```bash
docker run --rm --entrypoint sh \
  ghcr.io/whisper-money/whisper-money:latest \
  -c 'ls -la /app; test -f /app/artisan && echo OK || echo MISSING'
# /app is empty -> ARTISAN_MISSING
```

## Root cause

The `:latest` tag (and the bare `:<sha>` tag) were assigned to the
**development** image, not the production one:

| Image | Dockerfile | `COPY`s code into `/app`? | Tags (before) |
|---|---|---|---|
| Development | `Dockerfile` (`php:8.4-cli`) |  No — relies on the dev
`compose.yaml` bind-mount `.:/app` | **`latest`**, `<sha>` |
| Production | `Dockerfile.production` |  Yes (`COPY . /app/.`) |
`production`, `<sha>-production`, `v<ver>-production` |

The development image never copies the code into the container (it only
works with the `compose.yaml` bind-mount). Pulled standalone, `/app` is
empty and `artisan` is missing, hence the boot crash.

Both official deployment entrypoints point at that tag:

- `docker-compose.production.yml` → `image:
${WHISPER_IMAGE:-ghcr.io/whisper-money/whisper-money:latest}`
- `templates/coolify/whisper-money.yaml` → `image:
ghcr.io/whisper-money/whisper-money:latest`

Nothing in the repo consumes the development `:latest`/`:<sha>` (the dev
`compose.yaml` builds locally, it doesn't `pull`), so publishing the
code-less image under `:latest` was purely a footgun.

## Fix

Reassign the tags to the industry-standard convention (`:latest` = the
deployable production image), touching only the `docker/metadata-action`
metadata blocks in `ci.yml`:

- `:latest` and bare `:<sha>` → **production image**
(`Dockerfile.production`).
- The development image is now published as `:development` /
`:<sha>-development`.
- Existing `:production` and `:v<version>-production` tags are kept, so
current pins remain backward compatible.

Applied to both jobs (`build-image` amd64 and `build-arm64-images`
arm64) so the multi-platform manifests stay consistent.

With this, `docker pull …:latest`, `docker-compose.production.yml`, and
the Coolify template all work with no further changes.
2026-07-21 08:28:42 +00:00
Víctor Falcón d3ec96b845
fix(onboarding): stop the AI rule-suggestion step from hanging forever (#705)
## Problem

A user reported being stuck forever on the onboarding "Looking for
patterns" step (the "Polishing your suggestions…" spinner). Confirmed in
prod: their `suggestion_runs` row has been stuck in `processing` for a
week, and `failed_jobs` shows `TimeoutExceededException:
GenerateRuleSuggestionsJob has timed out`.

### Root cause

- The user has 4,163 transactions — the largest onboarding dataset (max
with a completed run was 3,481). The Gemini generation exceeded the
job's `$timeout = 120`.
- The worker timeout is raised **outside** the `try/catch` in
`GenerateRuleSuggestions::run()`, so the code that sets `status =
Failed` never ran.
- `GenerateRuleSuggestionsJob` had **no `failed()` handler** (5 other
jobs do), so nothing flipped the run to `Failed`. It stayed
`processing`, `show()` kept returning `processing`, and the client
polled every 3s forever.
- The timeout never reached Sentry, so it was invisible. Only 1 user
affected, but it's a latent bug that recurs on any large account.

## Fix

**Backend** — add `failed()` to `GenerateRuleSuggestionsJob`: mark the
run `Failed` (only if not already terminal) and `report()` the exception
so these surface in Sentry.

**Frontend** (`step-ai-suggestions.tsx`) — belt-and-suspenders so the
client never spins forever even if the worker dies before it can mark
the run:
- `poll()` now guards against transient errors (network blip / expired
session / 5xx) instead of silently dying.
- A client-side deadline (3 min, just beyond the "up to two minutes"
copy) surfaces the existing "couldn't generate" screen with **Try again
/ Skip**.

Not included: raising the timeout / capping the number of groups sent to
Gemini so large accounts *complete* instead of just being able to skip.
Follow-up if we want big accounts to get suggestions.

## Tests

- `tests/Feature/Ai/GenerateRuleSuggestionsJobTest.php` — `failed()`
marks the run `Failed` + reports; doesn't overwrite an already-terminal
run.
-
`resources/js/components/onboarding/step-ai-suggestions-timeout.test.tsx`
— after the deadline the spinner gives way to the failed screen.

Green locally: pint, prettier, eslint, backend + frontend tests.
2026-07-20 18:10:51 +00:00
Víctor Falcón 8172ca78d7
feat(welcome): add Miguel Ángel SB testimonial to the landing page (#703)
## What

Adds a new user testimonial from **Miguel Ángel SB** to the landing page
testimonials marquee (`resources/js/pages/welcome.tsx`), plus its
Spanish translation in `lang/es.json`.

The quote is a distilled English version of the positive closing of a
feedback email he sent us. The Spanish translation stays faithful to his
original wording.

> I love the style, the intuitive interface, how easy it is to use. If
it keeps growing like this, Whisper Money will be my finance app of
choice. You can tell it is built with passion — and things made with
passion can only end up a success.

## Notes

- Inserted just before the `Víctor Falcón (co-owner)` entry, which stays
last.
- `gravatar` is the MD5 of his email; he has no Gravatar, so the card
falls back to the generated Facehash avatar (same `d=404` mechanism as
most other entries).
- The English `__()` key is mirrored in `lang/es.json`, so the
localization test passes and Spanish users see the translated copy.

## QA

-  English card renders with the quote and Facehash fallback avatar.
-  Spanish (`?lang=es`) renders the translated quote — no English
fallback.
-  Row-splitting balances correctly with the new count; co-owner entry
remains last.
-  No new console errors (the Gravatar 404s are the intended fallback
path, shared by existing entries).
-  `bun run format` and `bun run lint` clean.

## Demo


https://github.com/user-attachments/assets/f7973c65-b719-4db5-801f-724784947e2b
2026-07-20 13:34:53 +00:00