Skip to content

Open source personal finance application

docs(rates): document fetch-rates edge function and daily cron

Ilya Komichev159c3b827adc
diff --git a/CLAUDE.md b/CLAUDE.md
index b78a86e9..962b0ad5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,6 +32,7 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supab
- Postgres schema migration: `app/supabase/migrations/` - tables `categories`, `wallets`, `trns`, `user_settings`, `rates`. All id columns are `text` (client-generated UUIDs, no FK constraints - PowerSync upload order is not guaranteed). Columns are camelCase (quoted) to match the client item shapes. RLS scoped to `auth.uid()`. A trigger auto-creates `user_settings` on signup.
- PowerSync replication setup: `app/supabase/powersync_setup.sql` (a `powersync_role` with REPLICATION + BYPASSRLS, and a `powersync` publication).
- Self-hosted PowerSync service: `app/powersync/` (`docker-compose.yaml`, `config/service.yaml`, `config/sync-config.yaml`). It replicates the Supabase Postgres and validates Supabase JWTs via the JWKS endpoint. Sync rules are per-user (`WHERE "userId" = auth.user_id()`).
+- Exchange rates: the `rates` table is populated server-side by the `fetch-rates` edge function (`app/supabase/functions/fetch-rates/`) - Coinbase (base, fiat + crypto) + OER (fiat overlay, needs `OPEN_EXCHANGE_RATES_KEY` secret) merged into one daily `source='merged'` row. Scheduled via `pg_cron` (migration `*_schedule_fetch_rates.sql`, 06:00 UTC), which reads the function URL + anon key from Vault secrets `project_url` / `anon_key`. Clients never write rates.
- `TrnType` in `app/app/components/trns/types.ts`: Expense (0), Income (1), Transfer (2).
- Adjustment is determined by `categoryId === 'adjustment'`, NOT by `TrnType`. It uses Expense or Income type, excluded from income/expense statistics. `categoryId` also holds the literal `'transfer'` for transfers.
diff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.md
index 14556955..76544a31 100644
--- a/docs/content/en/2.development/05.deployment.md
+++ b/docs/content/en/2.development/05.deployment.md
@@ -136,6 +136,39 @@ Two options; both replicate from the Supabase Postgres and validate Supabase JWT
`VITE_POWERSYNC_URL` is the public URL of that service.
+### Exchange rates (`fetch-rates`)
+
+Currency conversion needs the `rates` table populated. A Supabase **edge function** (`app/supabase/functions/fetch-rates/`) does that: it pulls two USD-based sources - **Coinbase** (no API key, ~all fiat + crypto, the base layer) and **Open Exchange Rates** (better fiat precision, overlaid on top) - merges them into one map and writes a single `source = 'merged'` row per day. The client reads only the latest row (`SELECT * FROM rates ORDER BY date DESC LIMIT 1`), so the merge happens at write time. Writes use the auto-injected `service_role` - `rates` has a global read policy but no client INSERT policy.
+
+1. Deploy the function:
+
+ ```bash [Terminal]
+ cd app
+ supabase functions deploy fetch-rates
+ ```
+
+2. **OER key (optional).** Set it as a function secret to add precise fiat; without it the function runs Coinbase-only (still ~630 currencies, crypto included). Get a free App ID at [openexchangerates.org](https://openexchangerates.org/signup):
+
+ ```bash [Terminal]
+ supabase secrets set OPEN_EXCHANGE_RATES_KEY=<app_id>
+ ```
+
+3. **Daily schedule.** The migration `supabase/migrations/*_schedule_fetch_rates.sql` enables `pg_cron` + `pg_net` and schedules `fetch-rates-daily` at `06:00 UTC`; it ships with `supabase db push` (same IPv6/pooler caveat as above). The cron reads the function URL and anon key from **Vault secrets** - kept out of the migration so it stays portable - so set them once per project (until they exist the scheduled run is a harmless no-op):
+
+ ```bash [Terminal]
+ supabase db query --linked "select vault.create_secret('https://<ref>.supabase.co', 'project_url')"
+ supabase db query --linked "select vault.create_secret('<anon-key>', 'anon_key')"
+ ```
+
+::callout{icon="i-lucide-terminal" color="info"}
+**Seed it once.** `supabase functions` has no `invoke` subcommand - trigger a run with a plain POST so `rates` is populated before the first scheduled run:
+
+```bash [Terminal]
+curl -X POST "https://<ref>.supabase.co/functions/v1/fetch-rates" \
+ -H "Authorization: Bearer <anon-key>"
+```
+::
+
## Google Sign-In (Production)
In production the Google provider is configured in the **hosted Supabase dashboard**, not in `config.toml` (that file only drives the local stack).
diff --git a/docs/content/en/3.reference/01.architecture.md b/docs/content/en/3.reference/01.architecture.md
index b73e37ee..1ecfb23f 100644
--- a/docs/content/en/3.reference/01.architecture.md
+++ b/docs/content/en/3.reference/01.architecture.md
@@ -156,7 +156,7 @@ Hard navigation instead of Vue Router - see [Technical Decisions](/en/reference/
## Exchange Rates
-- **Source:** OpenExchangeRates API (free tier), populated server-side
+- **Source:** Coinbase (base, fiat + crypto) + OpenExchangeRates (fiat overlay), merged into one daily `source='merged'` row by the `fetch-rates` edge function (`pg_cron`, 06:00 UTC)
- **Storage:** `rates` table in Postgres; global PowerSync stream syncs all rows to every authenticated user
- **Frontend:** `useCurrenciesStore` subscribes via `watchTable('SELECT * FROM rates', ...)`
- **Usage:** `getAmountInRate()` converts amounts to base currency for statistics
diff --git a/docs/content/en/3.reference/03.sync.md b/docs/content/en/3.reference/03.sync.md
index 3a7bb6ba..2634a06f 100644
--- a/docs/content/en/3.reference/03.sync.md
+++ b/docs/content/en/3.reference/03.sync.md
@@ -36,7 +36,7 @@ SELECT * FROM trns WHERE "userId" = auth.user_id()
SELECT * FROM user_settings WHERE "userId" = auth.user_id()
```
-**Global stream (`rates`):**
+**Global stream (`rates`):** all rows go to every authenticated user; rows are written server-side by the `fetch-rates` edge function, never by clients.
```sql
SELECT * FROM rates
```
diff --git a/docs/content/en/3.reference/06.validation-strategy.md b/docs/content/en/3.reference/06.validation-strategy.md
index c4373f28..aaf3388e 100644
--- a/docs/content/en/3.reference/06.validation-strategy.md
+++ b/docs/content/en/3.reference/06.validation-strategy.md
@@ -42,7 +42,7 @@ Validation is **client-only**. There are no server-side business-rule validators
- Column types: `text`, `numeric`, `integer`, `boolean`, `jsonb`
- `NOT NULL` on required columns
- RLS: every per-user table has `(select auth.uid())::text = "userId"` - rows from other users are invisible and writes are rejected
-- `rates` table is read-only for authenticated users (no client writes)
+- `rates` table is read-only for authenticated users (no client writes); rows are written server-side by the `fetch-rates` edge function
- A trigger auto-creates `user_settings` on signup (no client-side bootstrap needed)
There are **no server-side business-rule validators** (no string length limits enforced server-side, no numeric range checks, no cross-field validation). Those rules live only in the Zod schemas on the client.
diff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.md
index 9e9d42be..b623f7bb 100644
--- a/docs/content/ru/2.development/05.deployment.md
+++ b/docs/content/ru/2.development/05.deployment.md
@@ -136,6 +136,39 @@ Nuxt SPA хостится статически (выше описан Vercel, н
`VITE_POWERSYNC_URL` - публичный URL этого сервиса.
+### Курсы валют (`fetch-rates`)
+
+Для конвертации валют нужна наполненная таблица `rates`. Этим занимается **edge-функция** Supabase (`app/supabase/functions/fetch-rates/`): она тянет два USD-базовых источника - **Coinbase** (без API-ключа, ~весь фиат + крипта, базовый слой) и **Open Exchange Rates** (точнее по фиату, накладывается сверху), - сливает их в одну карту и пишет одну строку `source = 'merged'` в день. Клиент читает только последнюю строку (`SELECT * FROM rates ORDER BY date DESC LIMIT 1`), поэтому мёрдж происходит при записи. Запись идёт под авто-инжектируемым `service_role` - у `rates` есть глобальная политика чтения, но нет клиентской политики INSERT.
+
+1. Задеплоить функцию:
+
+ ```bash [Terminal]
+ cd app
+ supabase functions deploy fetch-rates
+ ```
+
+2. **Ключ OER (опционально).** Задайте его секретом функции, чтобы добавить точный фиат; без него функция работает только на Coinbase (всё равно ~630 валют, включая крипту). Бесплатный App ID - на [openexchangerates.org](https://openexchangerates.org/signup):
+
+ ```bash [Terminal]
+ supabase secrets set OPEN_EXCHANGE_RATES_KEY=<app_id>
+ ```
+
+3. **Ежедневное расписание.** Миграция `supabase/migrations/*_schedule_fetch_rates.sql` включает `pg_cron` + `pg_net` и ставит `fetch-rates-daily` на `06:00 UTC`; применяется через `supabase db push` (та же оговорка про IPv6/pooler, что и выше). Крон читает URL функции и anon-ключ из **секретов Vault** - они вынесены из миграции ради переносимости, - поэтому задайте их один раз на проект (пока их нет, запуск по расписанию безвредно ничего не делает):
+
+ ```bash [Terminal]
+ supabase db query --linked "select vault.create_secret('https://<ref>.supabase.co', 'project_url')"
+ supabase db query --linked "select vault.create_secret('<anon-key>', 'anon_key')"
+ ```
+
+::callout{icon="i-lucide-terminal" color="info"}
+**Засидить один раз.** У `supabase functions` нет подкоманды `invoke` - запустите функцию обычным POST, чтобы `rates` наполнилась до первого запуска по расписанию:
+
+```bash [Terminal]
+curl -X POST "https://<ref>.supabase.co/functions/v1/fetch-rates" \
+ -H "Authorization: Bearer <anon-key>"
+```
+::
+
## Вход через Google (продакшен)
В продакшене провайдер Google настраивается в **дашборде хостируемого Supabase**, а не в `config.toml` (этот файл управляет только локальным стеком).
diff --git a/docs/content/ru/3.reference/01.architecture.md b/docs/content/ru/3.reference/01.architecture.md
index 5e9d1353..62bfa835 100644
--- a/docs/content/ru/3.reference/01.architecture.md
+++ b/docs/content/ru/3.reference/01.architecture.md
@@ -156,7 +156,7 @@ signOut()
## Курсы валют
-- **Источник:** OpenExchangeRates API (бесплатный тариф), заполняется на стороне сервера
+- **Источник:** Coinbase (база, фиат + крипта) + OpenExchangeRates (фиат сверху), сливаются в одну дневную строку `source='merged'` edge-функцией `fetch-rates` (`pg_cron`, 06:00 UTC)
- **Хранение:** таблица `rates` в Postgres; глобальный поток PowerSync синхронизирует все строки каждому авторизованному пользователю
- **Фронтенд:** `useCurrenciesStore` подписывается через `watchTable('SELECT * FROM rates', ...)`
- **Использование:** `getAmountInRate()` конвертирует суммы в базовую валюту для статистики
diff --git a/docs/content/ru/3.reference/03.sync.md b/docs/content/ru/3.reference/03.sync.md
index 8b40123f..09840af6 100644
--- a/docs/content/ru/3.reference/03.sync.md
+++ b/docs/content/ru/3.reference/03.sync.md
@@ -36,7 +36,7 @@ SELECT * FROM trns WHERE "userId" = auth.user_id()
SELECT * FROM user_settings WHERE "userId" = auth.user_id()
```
-**Глобальный поток (`rates`):**
+**Глобальный поток (`rates`):** все строки доступны каждому авторизованному пользователю; строки пишет серверная edge-функция `fetch-rates`, не клиент.
```sql
SELECT * FROM rates
```
diff --git a/docs/content/ru/3.reference/06.validation-strategy.md b/docs/content/ru/3.reference/06.validation-strategy.md
index 113cb7c2..8d3c631d 100644
--- a/docs/content/ru/3.reference/06.validation-strategy.md
+++ b/docs/content/ru/3.reference/06.validation-strategy.md
@@ -42,7 +42,7 @@ seo:
- Типы колонок: `text`, `numeric`, `integer`, `boolean`, `jsonb`
- `NOT NULL` на обязательных колонках
- RLS: каждая пользовательская таблица имеет `(select auth.uid())::text = "userId"` - строки других пользователей невидимы, запись отклоняется
-- Таблица `rates` доступна только для чтения аутентифицированным пользователям (без записи с клиента)
+- Таблица `rates` доступна только для чтения аутентифицированным пользователям (без записи с клиента); строки пишет серверная edge-функция `fetch-rates`
- Триггер автоматически создаёт `user_settings` при регистрации (начальная инициализация на сервере не нужна)
**Серверных валидаторов бизнес-правил нет** (нет серверных ограничений длины строк, диапазонов чисел, кросс-полевой валидации). Эти правила живут только в Zod-схемах на клиенте.