Skip to content

Open source personal finance application

docs: rewrite docs and READMEs for supabase and powersync

Ilya Komichevca66519bd9c2
diff --git a/CLAUDE.md b/CLAUDE.md
index 3d7a3a88..59ff9f30 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,6 +1,6 @@
# Finapp
-Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Convex backend, Better Auth. Repo is a pnpm monorepo: `app/` (`@finapp/app`, Nuxt source under `app/app/`, Convex backend under `app/convex/`) and `docs/` (`@finapp/docs`).
+Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supabase (Postgres) backend, PowerSync offline-first sync, Supabase Auth (email/password). Repo is a pnpm monorepo: `app/` (`@finapp/app`, Nuxt source under `app/app/`, Supabase config under `app/supabase/`, self-hosted PowerSync under `app/powersync/`) and `docs/` (`@finapp/docs`).
- Node.js >= v24.12.0
- Package manager: pnpm
@@ -10,8 +10,7 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Conve
## Commands
- `pnpm dev` - Nuxt dev server on port 3050
-- `pnpm dev:convex` - Convex backend (watches and auto-deploys changes)
-- Both must run simultaneously in separate terminals
+- Local backend (run once, in `app/`): `supabase start` (Postgres + Auth on :54321), then `docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersync_setup.sql` (replication role + publication), then `docker compose -f powersync/docker-compose.yaml up -d` (PowerSync service on :8080)
- `pnpm build` - SPA build
- `pnpm generate` - static generation
- `pnpm lint` / `pnpm lint:fix` - ESLint
@@ -28,28 +27,32 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Conve
- i18n: `no_prefix` strategy, two locales (en-US, ru-RU)
- Always run `pnpm lint:fix` before committing
-## Convex Backend
+## Backend: Supabase + PowerSync
-- Schema in `app/convex/schema.ts`: `categories`, `wallets`, `trns`, `userSettings`, `rates`, `syncMeta`, `tombstones`
-- `TrnType` enum in `convex/validators.ts` (re-exported from `convex/shared.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
-- Auth: `@convex-dev/better-auth` with `cors: true` in `http.ts`
-- Generated types in `convex/_generated/` - do not edit
-- `convex/tsconfig.json` is separate from the app tsconfig
+- 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()`).
+- `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.
-### Convex Client Access
+### Client data layer
-Both composables live in `app/app/composables/useConvex.ts`:
-
-| Composable | Returns | Purpose |
-|------------|---------|---------|
-| `useConvexClient()` | `ConvexClient` | WebSocket client |
-| `useConvexClientWithApi()` | `{ api, client }` | Client + typed `api` object for queries/mutations |
-
-Stores use imperative `client.query()` and `client.mutation()` because they manage their own caching and offline merge.
+- `app/services/powersync/` - `AppSchema.ts` (client SQLite schema), `db.ts` (the `PowerSyncDatabase` singleton + `connectPowerSync` / `watchTable` / `waitForFirstSync`), `connector.ts` (`SupabaseConnector`: `fetchCredentials` + `uploadData`), `transforms.ts` (row↔item: booleans 0/1, `parentId` null↔0, `rates` JSON), `mutations.ts` (`upsertRow` / `deleteRow` - INSERT/UPDATE, never `ON CONFLICT`, since PowerSync tables are views).
+- `app/app/composables/useSupabase.ts` - the supabase-js client + `useSupabaseAuth()` (reactive session, sign in/up/out).
+- `app/app/plugins/powersync.client.ts` - connects PowerSync when a session resolves; sets the `finapp.localAuthUid` cookie (the synchronous route-guard gate).
+- Stores hydrate via `db.watch('SELECT * FROM ...')` (one subscription handles both initial load and realtime, local + synced) and write via `upsertRow`/`deleteRow`. Demo mode bypasses PowerSync and uses in-memory + localforage.
## Documentation
- Setup, env vars, scripts: `README.md`
-- Architecture, store pattern, sync, offline queue, auth flow: `docs/content/en/3.reference/`
-- Convex CLI gotchas, Better Auth incident fixes: `docs/content/en/2.development/08.troubleshooting.md`
+- Architecture, store pattern: `docs/content/en/3.reference/` (note: reference docs still describe the old Convex layer and need updating)
+
+## graphify
+
+This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
+
+Rules:
+- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
+- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
+- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
+- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
diff --git a/README.md b/README.md
index 70bf95fc..0b31d813 100644
--- a/README.md
+++ b/README.md
@@ -2,11 +2,11 @@
<img src="https://finapp.ilko.me/logo.png" alt="Finapp Logo" width="320" />
</p>
-# Finapp — Open Source Finance App
+# Finapp - Open Source Finance App
**English** | [Русский](./README.ru.md)
-> Your money, your control — anywhere, anytime.
+> Your money, your control - anywhere, anytime.
**Finapp** helps you easily track and manage personal finances. The repository is a pnpm monorepo with the Nuxt application and the documentation site.
@@ -24,9 +24,9 @@ Interactive map of the codebase architecture: [finapp-graph.ilko.me/en](https://
## Why Finapp?
-- **Simple**: No clutter, no distractions — just your transactions and balances.
+- **Simple**: No clutter, no distractions - just your transactions and balances.
- **Fast**: Works offline and syncs instantly across devices.
-- **Private**: You own your data — securely stored via Convex.
+- **Private**: You own your data - stored locally first and synced through your own Supabase backend.
- **Flexible**: Supports multiple currencies with automatic exchange rates.
- **Portable**: Optimized for mobile and desktop, installable as a PWA.
@@ -34,7 +34,7 @@ Interactive map of the codebase architecture: [finapp-graph.ilko.me/en](https://
### Finance
-- **Wallets**: 6 types — cash, bank accounts, credit cards, deposits, crypto, debt.
+- **Wallets**: 6 types - cash, bank accounts, credit cards, deposits, crypto, debt.
- **Transactions**: expense, income, transfer, adjustment with a built-in calculator.
- **Categories**: hierarchical parent-child categories with custom icons and colors.
- **Multi-currency**: 165+ currencies with automatic daily exchange rates.
@@ -50,8 +50,8 @@ Interactive map of the codebase architecture: [finapp-graph.ilko.me/en](https://
### Offline & Sync
- Offline-first PWA that works without an internet connection.
-- Offline queue with automatic sync on reconnect.
-- Real-time sync across devices via Convex.
+- Local-first SQLite storage with automatic background sync on reconnect.
+- Real-time sync across devices via PowerSync.
### Customization
@@ -67,8 +67,9 @@ Interactive map of the codebase architecture: [finapp-graph.ilko.me/en](https://
- Nuxt 4
- Pinia
- @nuxt/ui v4 and Tailwind CSS v4
-- Convex
-- Better Auth
+- Supabase (Postgres)
+- PowerSync
+- Supabase Auth
- Docus
- pnpm workspaces
@@ -76,7 +77,7 @@ Interactive map of the codebase architecture: [finapp-graph.ilko.me/en](https://
```text
finapp/
- app/ # Nuxt application, Convex backend, tests, app assets
+ app/ # Nuxt application, Supabase + PowerSync config, tests, app assets
docs/ # Docus documentation site
```
@@ -88,7 +89,7 @@ The root package contains workspace scripts only. App and docs dependencies are
- Node.js `>=24.12.0`
- pnpm `10.x`
-- A Convex project for local backend development
+- Docker and the [Supabase CLI](https://supabase.com/docs/guides/cli) for the local backend
### Install
@@ -100,31 +101,40 @@ pnpm install
### Configure the app
-Copy the app environment example and fill in your Convex deployment values:
+Copy the app environment example and fill in your Supabase and PowerSync values:
```bash
cp app/.env.example app/.env
```
-Required Nuxt environment variables:
+Required environment variables:
```bash
-CONVEX_DEPLOYMENT=your_deployment
-VITE_CONVEX_URL=your_convex_url
-VITE_CONVEX_SITE_URL=your_convex_site_url
+VITE_SUPABASE_URL=your_supabase_url
+VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
+VITE_POWERSYNC_URL=your_powersync_url
```
-Set Convex backend environment variables from the app workspace:
+For local development these point at the local stack started below: Supabase on `http://localhost:54321` and PowerSync on `http://localhost:8080`.
+
+### Local backend
+
+The backend is local self-hosted Supabase (Postgres + Auth) plus a self-hosted PowerSync service. Run these once from the `app/` workspace:
```bash
-pnpm --filter @finapp/app exec convex env set BETTER_AUTH_SECRET your_secret
-pnpm --filter @finapp/app exec convex env set APP_URL http://localhost:3050
-pnpm --filter @finapp/app exec convex env set GOOGLE_CLIENT_ID your_client_id
-pnpm --filter @finapp/app exec convex env set GOOGLE_CLIENT_SECRET your_client_secret
-pnpm --filter @finapp/app exec convex env set OPEN_EXCHANGE_RATES_KEY your_app_id
+cd app
+
+# 1. Start Supabase (Postgres + Auth on :54321)
+supabase start
+
+# 2. Apply the PowerSync replication setup (role + publication)
+docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersync_setup.sql
+
+# 3. Start the PowerSync service (:8080)
+docker compose -f powersync/docker-compose.yaml up -d
```
-`BETTER_AUTH_SECRET` is required. Without it, auth endpoints, including CORS preflight requests, will fail.
+Auth is Supabase email/password. Sign up a new account from the login screen, or create one with the Supabase CLI.
### Environment files
@@ -132,17 +142,12 @@ The app workspace uses several `.env` files (all gitignored except `.env.example
| File | Purpose |
| --- | --- |
-| `app/.env` | Dev deployment values, read by Nuxt |
-| `app/.env.local` | Auto-created by `convex dev`, used by the Convex CLI |
-| `app/.env.prod` | Prod deployment values, used by `pnpm dev:prod` |
+| `app/.env` | Dev values, read by Nuxt |
+| `app/.env.prod` | Prod values, used by `pnpm dev:prod` |
## Development
-Run the Convex backend and the Nuxt app in separate terminals:
-
-```bash
-pnpm dev:convex
-```
+With the local backend running, start the Nuxt app:
```bash
pnpm dev
@@ -158,7 +163,7 @@ pnpm docs:dev
The docs run at `http://localhost:3051`.
-Run app and docs dev servers together. Convex still runs separately with `pnpm dev:convex`.
+Run the app and docs dev servers together:
```bash
pnpm dev:all
@@ -169,7 +174,6 @@ pnpm dev:all
| Command | Description |
| --- | --- |
| `pnpm dev` | Start the app dev server |
-| `pnpm dev:convex` | Start the Convex dev backend |
| `pnpm docs:dev` | Start the documentation dev server |
| `pnpm dev:all` | Start app and docs dev servers in parallel |
| `pnpm build` | Build all workspace packages that define `build` |
diff --git a/README.ru.md b/README.ru.md
index 145a1a75..d1cb8a6e 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -26,7 +26,7 @@
- **Просто**: ничего лишнего - только ваши транзакции и балансы.
- **Быстро**: работает офлайн и мгновенно синхронизируется между устройствами.
-- **Приватно**: данные принадлежат вам и безопасно хранятся в Convex.
+- **Приватно**: данные принадлежат вам - сначала хранятся локально и синхронизируются через ваш собственный бэкенд Supabase.
- **Гибко**: поддержка нескольких валют с автоматическими курсами обмена.
- **Удобно**: оптимизировано для мобильных и десктопных устройств, устанавливается как PWA.
@@ -50,8 +50,8 @@
### Офлайн и синхронизация
- Offline-first PWA, работает без интернета.
-- Очередь офлайн-операций с автоматической синхронизацией при подключении.
-- Синхронизация между устройствами в реальном времени через Convex.
+- Локальное хранилище SQLite с автоматической фоновой синхронизацией при подключении.
+- Синхронизация между устройствами в реальном времени через PowerSync.
### Кастомизация
@@ -67,8 +67,9 @@
- Nuxt 4
- Pinia
- @nuxt/ui v4 и Tailwind CSS v4
-- Convex
-- Better Auth
+- Supabase (Postgres)
+- PowerSync
+- Supabase Auth
- Docus
- pnpm workspaces
@@ -76,7 +77,7 @@
```text
finapp/
- app/ # Nuxt-приложение, Convex-бэкенд, тесты, ассеты
+ app/ # Nuxt-приложение, конфигурация Supabase + PowerSync, тесты, ассеты
docs/ # Сайт документации на Docus
```
@@ -88,7 +89,7 @@ finapp/
- Node.js `>=24.12.0`
- pnpm `10.x`
-- Проект Convex для локальной разработки бэкенда
+- Docker и [Supabase CLI](https://supabase.com/docs/guides/cli) для локального бэкенда
### Установка
@@ -100,31 +101,40 @@ pnpm install
### Настройка приложения
-Скопируйте пример env-файла приложения и заполните значениями вашего деплоя Convex:
+Скопируйте пример env-файла приложения и заполните значениями Supabase и PowerSync:
```bash
cp app/.env.example app/.env
```
-Обязательные переменные окружения Nuxt:
+Обязательные переменные окружения:
```bash
-CONVEX_DEPLOYMENT=your_deployment
-VITE_CONVEX_URL=your_convex_url
-VITE_CONVEX_SITE_URL=your_convex_site_url
+VITE_SUPABASE_URL=your_supabase_url
+VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
+VITE_POWERSYNC_URL=your_powersync_url
```
-Установите переменные окружения Convex-бэкенда из workspace приложения:
+Для локальной разработки они указывают на локальный стек, запускаемый ниже: Supabase на `http://localhost:54321` и PowerSync на `http://localhost:8080`.
+
+### Локальный бэкенд
+
+Бэкенд - это локальный self-hosted Supabase (Postgres + Auth) плюс self-hosted сервис PowerSync. Выполните один раз из workspace `app/`:
```bash
-pnpm --filter @finapp/app exec convex env set BETTER_AUTH_SECRET your_secret
-pnpm --filter @finapp/app exec convex env set APP_URL http://localhost:3050
-pnpm --filter @finapp/app exec convex env set GOOGLE_CLIENT_ID your_client_id
-pnpm --filter @finapp/app exec convex env set GOOGLE_CLIENT_SECRET your_client_secret
-pnpm --filter @finapp/app exec convex env set OPEN_EXCHANGE_RATES_KEY your_app_id
+cd app
+
+# 1. Запустить Supabase (Postgres + Auth на :54321)
+supabase start
+
+# 2. Применить настройку репликации PowerSync (роль + публикация)
+docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersync_setup.sql
+
+# 3. Запустить сервис PowerSync (:8080)
+docker compose -f powersync/docker-compose.yaml up -d
```
-`BETTER_AUTH_SECRET` обязателен. Без него эндпоинты аутентификации, включая preflight-запросы CORS, не будут работать.
+Аутентификация - Supabase email/password. Зарегистрируйте новый аккаунт на экране входа или создайте его через Supabase CLI.
### Env-файлы
@@ -132,17 +142,12 @@ Workspace приложения использует несколько `.env` ф
| Файл | Назначение |
| --- | --- |
-| `app/.env` | Значения dev-деплоя, читаются Nuxt |
-| `app/.env.local` | Создаётся автоматически `convex dev`, используется Convex CLI |
+| `app/.env` | Значения dev, читаются Nuxt |
| `app/.env.prod` | Значения prod-деплоя, используются `pnpm dev:prod` |
## Разработка
-Запустите Convex-бэкенд и Nuxt-приложение в разных терминалах:
-
-```bash
-pnpm dev:convex
-```
+Когда локальный бэкенд запущен, запустите Nuxt-приложение:
```bash
pnpm dev
@@ -158,7 +163,7 @@ pnpm docs:dev
Документация доступна на `http://localhost:3051`.
-Запуск dev-серверов приложения и документации одновременно. Convex по-прежнему запускается отдельно через `pnpm dev:convex`.
+Запуск dev-серверов приложения и документации одновременно:
```bash
pnpm dev:all
@@ -169,7 +174,6 @@ pnpm dev:all
| Команда | Описание |
| --- | --- |
| `pnpm dev` | Запуск dev-сервера приложения |
-| `pnpm dev:convex` | Запуск dev-бэкенда Convex |
| `pnpm docs:dev` | Запуск dev-сервера документации |
| `pnpm dev:all` | Параллельный запуск dev-серверов приложения и документации |
| `pnpm build` | Сборка всех workspace-пакетов с командой `build` |
diff --git a/app/README.md b/app/README.md
index 106bb863..8cf98078 100644
--- a/app/README.md
+++ b/app/README.md
@@ -7,6 +7,5 @@ Nuxt application package for Finapp.
Use the root README ([English](../README.md) | [Русский](../README.ru.md)) for installation, environment setup, and development commands:
- App dev server: `pnpm dev`
-- Convex dev backend: `pnpm dev:convex`
- App build: `pnpm --filter @finapp/app build`
- App lint: `pnpm lint:app`
diff --git a/app/README.ru.md b/app/README.ru.md
index 03cc2b18..a410497e 100644
--- a/app/README.ru.md
+++ b/app/README.ru.md
@@ -7,6 +7,5 @@
Установка, настройка окружения и команды разработки описаны в корневом README ([English](../README.md) | [Русский](../README.ru.md)):
- Dev-сервер приложения: `pnpm dev`
-- Dev-бэкенд Convex: `pnpm dev:convex`
- Сборка приложения: `pnpm --filter @finapp/app build`
- Линтинг приложения: `pnpm lint:app`
diff --git a/docs/content/en/1.guide/01.introduction.md b/docs/content/en/1.guide/01.introduction.md
index 1301d94b..ea7d21c9 100644
--- a/docs/content/en/1.guide/01.introduction.md
+++ b/docs/content/en/1.guide/01.introduction.md
@@ -113,8 +113,9 @@ On Windows and Linux, use `Ctrl` instead of `Cmd`.
- [Nuxt 4](https://nuxt.com) - Vue meta-framework
- [Nuxt UI](https://ui.nuxt.com) - component library
- [Tailwind CSS](https://tailwindcss.com) - utility-first styling
-- [Convex](https://convex.dev) - backend and real-time database
-- [Better Auth](https://better-auth.com) - authentication
+- [Supabase](https://supabase.com) (Postgres) - backend database
+- [PowerSync](https://www.powersync.com) - offline-first sync
+- [Supabase Auth](https://supabase.com/docs/guides/auth) - authentication (email/password)
## Next Steps
diff --git a/docs/content/en/2.development/01.installation.md b/docs/content/en/2.development/01.installation.md
index b5cc0ada..574ad48d 100644
--- a/docs/content/en/2.development/01.installation.md
+++ b/docs/content/en/2.development/01.installation.md
@@ -1,17 +1,19 @@
---
title: Installation
-description: Get started with Finapp.
+description: Get started with Finapp - clone, configure env vars, start the local backend, and run the dev server.
navigation:
icon: i-lucide-download
seo:
title: Installation
- description: How to install and run Finapp locally.
+ description: How to install and run Finapp locally with Supabase and PowerSync.
---
## Requirements
- [Node.js](https://nodejs.org) v24.12.0 or later
- [pnpm](https://pnpm.io) >= 10.28.2
+- [Supabase CLI](https://supabase.com/docs/guides/cli) (for local Supabase)
+- [Docker](https://docs.docker.com/get-docker/) (for Supabase and PowerSync)
## Installation
@@ -29,78 +31,55 @@ cd finapp
pnpm install
```
-### Start development server
+### Configure environment variables
-You need two terminals — one for the frontend and one for the backend.
+Copy the example env file and fill in your values:
-```bash [Terminal 1 — Frontend]
-pnpm dev
+```bash [Terminal]
+cp app/.env.example app/.env
```
-```bash [Terminal 2 — Backend]
-pnpm dev:convex
+```bash [app/.env]
+VITE_SUPABASE_URL=http://localhost:54321
+VITE_SUPABASE_ANON_KEY=<anon key from supabase start output>
+VITE_POWERSYNC_URL=http://localhost:8080
```
-The app will be available at [http://localhost:3050](http://localhost:3050).
-
-A design system playground is available at [http://localhost:3050/dev](http://localhost:3050/dev) during development (hidden in production).
-::
-
-## Env Files
-
-- `.env` — dev deployment values, read by Nuxt (default `--dotenv`)
-- `.env.local` — auto-created by `convex dev`, used by Convex CLI (gitignored)
-- `.env.prod` — prod deployment values, used by `pnpm dev:prod`
+For local development, `supabase start` prints the `API URL` (use as `VITE_SUPABASE_URL`) and `anon key` (use as `VITE_SUPABASE_ANON_KEY`). `VITE_POWERSYNC_URL` is the PowerSync service started in the next step.
-All `.env*` files are gitignored except `.env.example`.
+### Start the local backend
-## Backend Setup
+Run these three commands once from the `app/` directory. After the initial setup you only need to start the containers again if they are stopped.
-Finapp uses [Convex](https://convex.dev) as a backend. To set up your own instance:
+**1. Start Supabase (Postgres + Auth on port 54321):**
-1. Create a project at [convex.dev](https://convex.dev)
-2. Copy `.env.example` to `.env` and fill in your Convex credentials:
-
-```bash [.env]
-CONVEX_DEPLOYMENT=your_deployment
-VITE_CONVEX_URL=your_convex_url
-VITE_CONVEX_SITE_URL=your_convex_site_url
+```bash [Terminal - from app/]
+supabase start
```
-### Nuxt Env Vars
-
-| Variable | Description |
-|----------|-------------|
-| `CONVEX_DEPLOYMENT` | Deployment identifier for Convex CLI |
-| `VITE_CONVEX_URL` | Convex deployment URL (Nuxt frontend) |
-| `VITE_CONVEX_SITE_URL` | Convex site URL (Nuxt auth client) |
+**2. Apply the PowerSync replication setup:**
-### Convex Backend Env Vars
+```bash [Terminal - from app/]
+docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersync_setup.sql
+```
-Set via `npx convex env set`:
+This creates a `powersync_role` with replication privileges and a `powersync` publication scoped to the five Finapp tables.
-| Variable | Description |
-|----------|-------------|
-| `BETTER_AUTH_SECRET` | Secret key for Better Auth (required — without it all auth endpoints including CORS preflight will fail) |
-| `APP_URL` | App URL for cross-domain auth and CORS/trustedOrigins |
-| `GOOGLE_CLIENT_ID` | Google OAuth client ID |
-| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret |
-| `OPENEXCHANGERATES_APP_ID` | Exchange rates API key |
+**3. Start the PowerSync service (port 8080):**
-### First-Time Convex Setup
+```bash [Terminal - from app/]
+docker compose -f powersync/docker-compose.yaml up -d
+```
-When connecting to a new Convex dev deployment, configure its environment:
+### Start the development server
```bash [Terminal]
-npx convex env set BETTER_AUTH_SECRET <value>
-npx convex env set APP_URL http://localhost:3050
-npx convex env set GOOGLE_CLIENT_ID <value>
-npx convex env set GOOGLE_CLIENT_SECRET <value>
-npx convex env set OPENEXCHANGERATES_APP_ID <value>
+pnpm dev
```
-::callout{icon="i-lucide-alert-triangle" color="warning"}
-`BETTER_AUTH_SECRET` is required — without it, all auth endpoints (including CORS preflight) will fail with `BetterAuthError`.
+The app will be available at [http://localhost:3050](http://localhost:3050).
+
+A design system playground is available at [http://localhost:3050/dev](http://localhost:3050/dev) during development (hidden in production).
::
## Production Build
diff --git a/docs/content/en/2.development/02.understand-anything.md b/docs/content/en/2.development/02.understand-anything.md
index 96638954..afa06369 100644
--- a/docs/content/en/2.development/02.understand-anything.md
+++ b/docs/content/en/2.development/02.understand-anything.md
@@ -108,8 +108,8 @@ Files are assigned to one of 9 layers:
|-------|-------------|
| **Entry** | App entry points and Nuxt config |
| **Config** | Build config, ESLint, TypeScript config |
-| **Backend** | Convex schema, mutations, queries, HTTP handlers |
-| **Auth** | Better Auth configuration and middleware |
+| **Backend** | Supabase Postgres schema + RLS + PowerSync sync rules (`app/supabase/`, `app/powersync/`) |
+| **Auth** | Supabase Auth (email/password); two-layer route guard |
| **Store** | Pinia stores (categories, wallets, trns, rates, settings) |
| **Composables** | Vue composables and utilities |
| **Components** | Vue components grouped by feature |
diff --git a/docs/content/en/2.development/03.offline.md b/docs/content/en/2.development/03.offline.md
index 6ee4ab3b..74a9cd0e 100644
--- a/docs/content/en/2.development/03.offline.md
+++ b/docs/content/en/2.development/03.offline.md
@@ -5,41 +5,37 @@ navigation:
icon: i-lucide-wifi-off
seo:
title: Offline & PWA
- description: How Finapp works offline as a Progressive Web App.
+ description: How Finapp works offline as a Progressive Web App, backed by PowerSync's local-first sync.
---
## PWA Installation
Finapp is a Progressive Web App (PWA). You can install it on your device for a native app-like experience:
-- **Desktop** — click the install icon in your browser's address bar
-- **Mobile** — use "Add to Home Screen" from the browser menu
+- **Desktop** - click the install icon in your browser's address bar
+- **Mobile** - use "Add to Home Screen" from the browser menu
The installed app runs in standalone mode without browser UI.
## Working Offline
-All your data is stored locally. You can create, edit, and delete transactions, wallets, and categories while offline.
+Finapp is offline-first. All your data lives in a local SQLite database in the browser (backed by PowerSync, persisted in IndexedDB). You can create, edit, and delete transactions, wallets, and categories while offline - reads and writes always hit the local database first, so the UI never waits on the network.
-### Offline Queue
+### How writes sync
-When you make changes offline, they are saved to a local queue. Each operation records:
+Every write goes to local SQLite immediately and is recorded in PowerSync's built-in upload queue. While you are offline the queue simply waits.
-- The entity type (transaction, wallet, or category)
-- The operation type (create, update, or delete)
-- The data and timestamp
+When connectivity is restored, PowerSync drains the queue to the server (Supabase) automatically and in order. There is no manual queue and no client-generated temporary IDs to remap - every row carries the client-generated UUID it was created with, on both the device and the server.
-The queue automatically optimizes itself — for example, if you create and then update the same item offline, they merge into a single create operation.
+If the server permanently rejects a write (for example a row-level-security or constraint violation), that change is discarded so the queue is not blocked forever, and the app shows a sync-error toast so you know your local copy is now ahead of the server.
-### Sync on Reconnect
+### How reads stay fresh
-When connectivity is restored, the offline queue is processed automatically. Operations are sent to the server in order, and local IDs are remapped to server IDs upon success.
+The app subscribes to the local database. Any change - whether it came from your own write or from an incoming sync from another device - re-runs the relevant queries and updates the UI. The same subscription handles the initial load and live updates, so a second device sees your changes shortly after they sync.
## Sync Strategy
-Finapp uses different sync strategies depending on the data type:
+PowerSync replicates each user's rows incrementally: after the first full sync it streams only the changes (inserts, updates, and deletes) for the tables you are subscribed to. Exchange rates are a shared, read-only stream available to every user. You do not pick a strategy per data type - it is incremental for everything.
-- **Transactions** — delta sync. Only changed transactions since the last sync are fetched, using a sync timestamp.
-- **Wallets and Categories** — full sync. The complete list is fetched each time, since these collections are typically small.
-
-Data is cached locally using `localforage` for fast access between sessions.
+Demo mode is the one exception: it has no backend and persists to `localforage` instead, so a reload works without signing in.
+</content>
diff --git a/docs/content/en/2.development/04.migration.md b/docs/content/en/2.development/04.migration.md
index 9590d431..460dae0a 100644
--- a/docs/content/en/2.development/04.migration.md
+++ b/docs/content/en/2.development/04.migration.md
@@ -1,22 +1,22 @@
---
-title: Migration from Firebase
-description: How to migrate user data from Finapp v6 (Firebase) to Finapp v7 (Convex).
+title: Data Migration History
+description: Historical overview of Finapp backend migrations - Firebase to Convex (v6 to v7) and Convex to Supabase+PowerSync.
navigation:
icon: i-lucide-database
seo:
- title: Migration from Firebase
- description: Step-by-step guide to migrate data from Firebase Realtime Database to Convex backend.
+ title: Data Migration History
+ description: Historical note on Finapp backend migrations - from Firebase Realtime Database through Convex to Supabase Postgres with PowerSync.
---
-Finapp v6 used Firebase Realtime Database. Finapp v7 uses [Convex](https://convex.dev). This guide describes how to migrate existing user data.
+Finapp has gone through two major backend changes. This page documents both for historical reference.
-The legacy v6 source code lives on the [`firebase`](https://github.com/ilkome/finapp/tree/firebase) branch.
+## Firebase to Convex (v6 to v7)
-## Overview
+Finapp v6 used Firebase Realtime Database. Finapp v7 replaced it with Convex (backend-as-code, WebSocket sync).
-The migration script reads a Firebase JSON export, transforms the data to match the Convex schema, and imports it via internal mutations.
+The legacy v6 source code lives on the [`firebase`](https://github.com/ilkome/finapp/tree/firebase) branch.
-### What changes
+### What changed
| Entity | Firebase (v6) | Convex (v7) |
|--------|---------------|-------------|
@@ -26,84 +26,24 @@ The migration script reads a Firebase JSON export, transforms the data to match
| Settings | `settings.lang` (`en`, `ru`) | `userSettings.locale` (`en`, `ru`) |
| Icons | `mdi mdi-xxx` format | `mdi:xxx` format |
-## Prerequisites
-
-- Convex backend deployed (both dev and prod)
-- User account created on the target deployment (sign in at least once to get a userId)
-- Firebase JSON export file
-
-## Export data from Firebase
-
-Export your data from the [Firebase Console](https://console.firebase.google.com):
-
-1. Open your Firebase project
-2. Go to Realtime Database
-3. Click the three-dot menu on the root node for the user
-4. Select "Export JSON"
-5. Save the file as `data.json` in `utils/migrate/`
-
-The file should have this structure:
-
-```json [data.json]
-{
- "accounts": { ... },
- "categories": { ... },
- "settings": { "baseCurrency": "USD", "lang": "en" },
- "trns": { ... }
-}
-```
-
-## Find your Convex userId
-
-You need the Convex userId for the target user on each deployment. Find it in the [Convex Dashboard](https://dashboard.convex.dev) in the `users` table.
-
-## Run the migration
-
-The script deletes existing user data before importing.
-
-::callout{icon="i-lucide-alert-triangle" color="warning"}
-The script will delete all existing data for the specified userId before importing. Make sure you have the correct userId.
-::
-
-```bash [Dev]
-node utils/migrate/firebase.js <userId>
-```
-
-```bash [Prod]
-node utils/migrate/firebase.js <userId> --prod
-```
-
-The script will:
+### Migration tooling (historical - no longer in the repo)
-1. Delete existing data for the userId
-2. Import wallets (from `accounts`) and return an ID mapping
-3. Import categories with icon fixes and parent/child remapping
-4. Import transactions in batches of 200, remapping all wallet and category references
-5. Import user settings
+This migration was a one-off operation. The scripts that performed it (`utils/migrate/firebase.js`, `convex/migrate.ts`) have been deleted from the repository because they are no longer relevant. Do not attempt to run them.
-## Data transformations
+The scripts read a Firebase JSON export, transformed the data to match the Convex schema (remapping IDs, fixing icon formats, normalizing settings), and imported it via Convex internal mutations in batches of 200.
-The script applies these transformations during import:
+## Convex to Supabase+PowerSync (current backend)
-### Wallets
-- `accounts` key renamed to `wallets`
-- Missing fields get defaults: `isArchived: false`, `isExcludeInTotal: false`, `isWithdrawal: false`, `order: 0`
+Finapp v7+ (Convex) has been migrated to **Supabase Postgres + PowerSync** (offline-first sync) with **Supabase Auth (email/password)**.
-### Categories
-- Icons: `mdi mdi-xxx` → `mdi:xxx`, empty → `mdi:category-outline`
-- `parentId` remapped from old string IDs to new Convex IDs (`childIds` no longer stored — computed from `parentId`)
-- Missing fields get defaults: `showInLastUsed: false`, `showInQuickSelector: false`
+This was a one-off development-time operation, not a recurring user-facing flow:
-### Transactions
-- `walletId`, `categoryId`, `expenseWalletId`, `incomeWalletId` remapped to new Convex IDs
-- Special `categoryId` values preserved as-is: `transfer`, `adjustment`
+1. Export all data from the Convex deployment using `convex export --prod`.
+2. Transform the export with a Python script that kept Convex `_id` values as Postgres `text` ids (no UUID conversion needed - the ids remain stable) and remapped `userId` values to the corresponding Supabase Auth uids.
+3. Import via `psql` into the Supabase Postgres instance.
-### Settings
-- `settings.lang` → `userSettings.locale` (values stay the same: `en`, `ru`)
+No FK constraints exist in the Postgres schema, so import order does not matter. RLS policies and PowerSync sync rules ensure per-user data isolation going forward.
-## Files
+## Current backend
-| File | Description |
-|------|-------------|
-| `utils/migrate/firebase.js` | Node.js script that reads JSON, transforms data, calls Convex mutations |
-| `convex/migrate.ts` | Convex internal mutations: `deleteUserData`, `insertWallets`, `insertCategories`, `insertTrnsBatch`, `insertUserSettings` |
+The current backend is **Supabase Postgres + PowerSync**. See [Architecture](/en/reference/architecture) for a full description and [Installation](/en/development/installation) for local setup.
diff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.md
index 8aceb1d5..a9864301 100644
--- a/docs/content/en/2.development/05.deployment.md
+++ b/docs/content/en/2.development/05.deployment.md
@@ -1,11 +1,11 @@
---
title: Deployment
-description: Deploy Finapp and docs to Vercel from a monorepo.
+description: Deploy Finapp and docs to Vercel from a monorepo, with Supabase and PowerSync as the backend.
navigation:
icon: i-lucide-rocket
seo:
title: Deployment
- description: How to deploy Finapp app and docs to Vercel.
+ description: How to deploy Finapp app and docs to Vercel with Supabase Postgres and PowerSync.
---
Finapp is a pnpm workspace monorepo. Both the app and docs deploy from the same repository as separate Vercel projects.
@@ -15,7 +15,7 @@ Finapp is a pnpm workspace monorepo. Both the app and docs deploy from the same
Create **two projects** in Vercel, both pointing to the same GitHub repository.
::callout{icon="i-lucide-info" color="info"}
-**Settings split: file vs project.** Most build settings live in each project's `vercel.json` (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory cannot live in `vercel.json`** because Vercel needs it to know where to look for the file. Set it once in the project's dashboard (Settings → General → Root Directory) or via the API:
+**Settings split: file vs project.** Most build settings live in each project's `vercel.json` (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory cannot live in `vercel.json`** because Vercel needs it to know where to look for the file. Set it once in the project's dashboard (Settings -> General -> Root Directory) or via the API:
```bash
TOKEN=$(jq -r .token "$HOME/Library/Application Support/com.vercel.cli/auth.json")
@@ -37,12 +37,13 @@ curl -X PATCH \
| Output Directory | `.output/public` |
| Install Command | `pnpm install` |
-Add the following environment variables:
+Add the following environment variables pointing at your hosted Supabase project and PowerSync service:
| Variable | Value |
|----------|-------|
-| `VITE_CONVEX_URL` | Your Convex deployment URL |
-| `VITE_CONVEX_SITE_URL` | Your Convex site URL |
+| `VITE_SUPABASE_URL` | Your Supabase project URL |
+| `VITE_SUPABASE_ANON_KEY` | Your Supabase publishable (anon) key |
+| `VITE_POWERSYNC_URL` | Your PowerSync service URL |
### Docs Project
@@ -55,7 +56,7 @@ Add the following environment variables:
## Ignored Build Step
-To avoid unnecessary builds, configure **Ignored Build Step** in each Vercel project settings (Settings → Git → Ignored Build Step):
+To avoid unnecessary builds, configure **Ignored Build Step** in each Vercel project settings (Settings -> Git -> Ignored Build Step):
::code-group
```bash [App]
@@ -69,6 +70,15 @@ git diff --quiet HEAD^ HEAD -- docs
This way the app won't redeploy when only docs change, and vice versa.
+## Backend: Supabase + PowerSync
+
+The Nuxt SPA is statically hosted on Vercel. The backend services are separate:
+
+- **Supabase** - hosted Supabase project (cloud or self-hosted) provides Postgres, Auth, and the PostgREST/supabase-js write path.
+- **PowerSync** - a PowerSync service (self-hosted via Docker or a hosted option) handles offline-first sync by replicating from the Supabase Postgres via logical replication.
+
+Set the three `VITE_*` env vars in Vercel to point at your production Supabase project and PowerSync instance. See [Installation](/en/development/installation#env-variables) for the variable descriptions.
+
## Premium (Finapp Premium)
Finapp Premium lives in a separate repository ([finapp-premium](https://github.com/ilkome/finapp-premium)) and extends the base app as a **Nuxt layer**.
@@ -88,8 +98,8 @@ No `FINAPP_BASE_PATH` environment variable is needed on Vercel. The default path
### How It Works
- `nuxt.config.ts` uses `FINAPP_BASE_PATH` env var to resolve the base layer
-- Default (CI/Vercel): `./base/app` — the `app/` subdirectory inside the `base` Git submodule
-- `base/` is a Git submodule pointing to the `convex` branch of `ilkome/finapp`
+- Default (CI/Vercel): `./base/app` - the `app/` subdirectory inside the `base` Git submodule
+- `base/` is a Git submodule pointing to the `main` branch of `ilkome/finapp`
- `npx nuxt prepare base/app` generates `base/app/.nuxt/tsconfig.json`, which Vite needs to resolve TypeScript config from the submodule layer
- Local dev: set `FINAPP_BASE_PATH=../mono/app` in `.env` to use the local monorepo with hot reload
@@ -107,10 +117,10 @@ FINAPP_BASE_PATH=../mono/app
### Git Submodule
-The submodule should point to the `convex` branch of `ilkome/finapp`:
+The submodule should point to the `main` branch of `ilkome/finapp`:
```bash [Terminal]
-git submodule add -b convex https://github.com/ilkome/finapp.git base
+git submodule add -b main https://github.com/ilkome/finapp.git base
```
After a fresh clone:
@@ -118,15 +128,3 @@ After a fresh clone:
```bash [Terminal]
git submodule update --init
```
-
-## Convex Backend
-
-Convex deploys separately from Vercel. Use the Convex dashboard or CLI:
-
-```bash [Terminal]
-npx convex deploy
-```
-
-::callout{icon="i-lucide-info" color="info"}
-Make sure all required environment variables are set in your Convex production deployment. See [Installation](/development/installation#convex-backend-env-vars) for the full list.
-::
diff --git a/docs/content/en/2.development/06.testing.md b/docs/content/en/2.development/06.testing.md
index 5cf1cf9e..8aa8db62 100644
--- a/docs/content/en/2.development/06.testing.md
+++ b/docs/content/en/2.development/06.testing.md
@@ -37,4 +37,4 @@ E2E tests run with [Playwright](https://playwright.dev). Playwright ships browse
3. CI / full sweep: `pnpm test:e2e`
4. Investigating a failure: `pnpm test:e2e:report`
-Only `test:e2e` and `test:e2e:install` are strictly required — the rest are convenience wrappers around `playwright` CLI flags.
+Only `test:e2e` and `test:e2e:install` are strictly required - the rest are convenience wrappers around `playwright` CLI flags.
diff --git a/docs/content/en/2.development/08.ai-workflow/01.overview.md b/docs/content/en/2.development/08.ai-workflow/01.overview.md
index 4f694c37..5b720896 100644
--- a/docs/content/en/2.development/08.ai-workflow/01.overview.md
+++ b/docs/content/en/2.development/08.ai-workflow/01.overview.md
@@ -47,14 +47,14 @@ Agents are specialized subprocesses for complex tasks. Claude can delegate to th
## What's Configured
### Security
-- **Skill**: comprehensive OWASP checklist adapted for Convex and Better Auth
+- **Skill**: comprehensive OWASP checklist adapted for Supabase + PowerSync (RLS, JWT, sync rules)
### Testing
-- **Skill**: Vitest patterns, TDD workflow, mocking Convex, Pinia, localStorage
+- **Skill**: Vitest patterns, TDD workflow, mocking PowerSync, Pinia, localStorage
- **Skill**: Playwright E2E testing patterns
### Code Quality
-- **Agent**: general code reviewer (Vue, Nuxt, Convex patterns)
+- **Agent**: general code reviewer (Vue, Nuxt, PowerSync/Supabase patterns)
- **Agent**: TypeScript reviewer (type safety, async correctness, Composition API)
- **Agent**: build error resolver (minimal fixes to get the build green)
@@ -63,4 +63,4 @@ Agents are specialized subprocesses for complex tasks. Claude can delegate to th
## Origin
-Adapted from [everything-claude-code](https://github.com/affaan-m/everything-claude-code) (MIT). All React, Next.js patterns replaced with Vue 3, Nuxt 4. Supabase replaced with Convex. Project specific patterns added (shallowRef stores, offline queue, frontend IDs).
+Adapted from [everything-claude-code](https://github.com/affaan-m/everything-claude-code) (MIT). All React, Next.js patterns replaced with Vue 3, Nuxt 4. Project uses Supabase + PowerSync (offline-first). Project specific patterns added (shallowRef stores, optimistic writes, client-generated UUIDs).
diff --git a/docs/content/en/2.development/08.ai-workflow/02.agents.md b/docs/content/en/2.development/08.ai-workflow/02.agents.md
index 31383b55..fca716ea 100644
--- a/docs/content/en/2.development/08.ai-workflow/02.agents.md
+++ b/docs/content/en/2.development/08.ai-workflow/02.agents.md
@@ -39,13 +39,13 @@ Reviews TypeScript code for type safety, async correctness, and Vue 3 patterns.
**Model:** Sonnet | **Tools:** Read, Grep, Glob, Bash
-General code review covering security, quality, Vue and Nuxt patterns, Convex patterns.
+General code review covering security, quality, Vue and Nuxt patterns, PowerSync/Supabase patterns.
**Checks:**
- Security: secrets, auth checks, input validation
- Code quality: function size, nesting depth, dead code
- Vue patterns: computed purity, reactive destructuring, Lazy prefix
-- Convex patterns: `v.id()` validators, bounded queries, index usage
+- PowerSync/Supabase patterns: RLS policies + sync rules, client-generated UUID ids, optimistic write + rollback
- Performance: bundle size, N+1 queries
**Output format:** findings grouped by severity (CRITICAL, HIGH, MEDIUM, LOW) with a summary table and verdict (APPROVE, WARNING, BLOCK).
@@ -64,7 +64,7 @@ Fixes build and TypeScript errors with minimal diffs. No refactoring, no archite
- Type inference errors, missing types
- Import and module resolution
- Nuxt auto-import issues (`npx nuxi prepare`)
-- Convex type mismatches (regenerate `_generated/`)
+- PowerSync schema mismatches (`AppSchema.ts`) + Supabase migration errors
- Vue template type errors
**When to use:** build broke, `vue-tsc` failing, need a quick fix.
@@ -79,11 +79,11 @@ Creates detailed implementation plans for complex features.
**Plan structure:**
1. Requirements analysis
-2. Architecture review (affected components, stores, Convex functions)
+2. Architecture review (affected components, stores, Supabase/PowerSync data flow)
3. Step breakdown with file paths, dependencies, risks
4. Phased implementation (backend, store, UI)
5. Testing strategy
-**Finapp specifics:** considers offline support, optimistic UI, frontend IDs, shallowRef stores, Convex schema migrations, i18n, premium layer impact.
+**Finapp specifics:** considers offline support, optimistic UI, client-generated UUIDs, shallowRef stores, Supabase migrations + PowerSync sync rules, i18n, premium layer impact.
**When to use:** before starting any non-trivial feature or refactoring.
diff --git a/docs/content/en/2.development/08.ai-workflow/03.skills.md b/docs/content/en/2.development/08.ai-workflow/03.skills.md
index 8abe616e..bd69ae8b 100644
--- a/docs/content/en/2.development/08.ai-workflow/03.skills.md
+++ b/docs/content/en/2.development/08.ai-workflow/03.skills.md
@@ -18,15 +18,15 @@ Skills are detailed guides that Claude loads on demand via slash commands. They
**Invoke:** `/security-review`
-Comprehensive security checklist adapted for Convex + Better Auth + Vue 3.
+Comprehensive security checklist adapted for Supabase + PowerSync + Vue 3.
**Sections:**
-1. **Secrets management** - env vars, `npx convex env set`, `BETTER_AUTH_SECRET`
-2. **Input validation** - Zod schemas (frontend), Convex validators with `v.*` (backend)
-3. **Auth & authorization** - `getAuthUserId(ctx)`, data isolation by `userId`, cookie security
+1. **Secrets management** - env vars, `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_POWERSYNC_URL`
+2. **Input validation** - Zod (frontend) + Postgres constraints/RLS (server); no server-side business validators
+3. **Auth & authorization** - Supabase JWT / RLS, data isolation by `userId`, cookie security
4. **XSS prevention** - `v-html` sanitization, Vue auto-escaping
-5. **CSRF protection** - Convex WebSocket (no traditional CSRF), `trustedOrigins`, webhook secrets
-6. **Sensitive data exposure** - logging, error messages, Convex query results
+5. **CSRF protection** - Supabase JWT / RLS (no traditional CSRF), `trustedOrigins`, webhook secrets
+6. **Sensitive data exposure** - logging, error messages, Supabase/PowerSync query results
7. **Dependency security** - `pnpm audit`
8. **Offline queue security** - localStorage ops, frontend ID trust boundaries
@@ -48,7 +48,7 @@ Test-driven development cycle with Vitest.
**Includes:**
- Project test conventions (file location, structure)
- Running tests: `pnpm test`, `--run`, `--coverage`
-- Mocking patterns for Convex client, Pinia stores, localStorage
+- Mocking patterns for PowerSync, Pinia stores, localStorage
- What to test vs what to skip
- 80% coverage target on business logic
@@ -62,7 +62,7 @@ Nuxt 4 patterns adapted for Finapp's SPA mode.
**Sections:**
- **SPA mode notes** - what applies and what doesn't with `ssr: false`
-- **Data fetching** - Convex client (not `useFetch`), `$fetch` for external APIs
+- **Data fetching** - PowerSync `watchTable` + supabase-js (not `useFetch`), `$fetch` for external APIs
- **Lazy loading** - `Lazy` prefix, `v-if` for deferred chunks, when to use/skip
- **Component organization** - feature grouping, auto-imports, PascalCase
- **Composables** - `use` prefix, `shallowRef`, `computed` for derived state
@@ -82,6 +82,6 @@ Playwright E2E testing patterns (foundation for future implementation).
- Page Object Model pattern
- Test patterns for auth flow and transaction CRUD
- Locator best practices (`data-testid` > CSS selectors)
-- SPA-specific waits (client render, Convex WebSocket)
+- SPA-specific waits (client render, PowerSync first sync)
- Flaky test quarantine
- Critical user journeys to cover (auth, transactions, wallets, categories, statistics, offline)
diff --git a/docs/content/en/2.development/09.troubleshooting.md b/docs/content/en/2.development/09.troubleshooting.md
index 6f520316..d95c5674 100644
--- a/docs/content/en/2.development/09.troubleshooting.md
+++ b/docs/content/en/2.development/09.troubleshooting.md
@@ -1,65 +1,70 @@
---
title: Troubleshooting
-description: Convex CLI gotchas and known incident fixes.
+description: Known gotchas for the local Supabase+PowerSync dev setup and offline-first data layer.
navigation:
icon: i-lucide-life-buoy
seo:
title: Troubleshooting
- description: Non-obvious Convex CLI behaviors and resolved Better Auth incidents that may resurface during upgrades.
+ description: Verified gotchas from the Supabase+PowerSync migration - Docker, PowerSync client tables, auth cookie timing, and more.
---
-## Convex CLI
+## Local Docker / Supabase
-### Targeting prod
+### Colima: disable Supabase analytics
-Always pass the `--prod` flag explicitly:
+On Colima (macOS Docker alternative), the Supabase `vector` (log analytics) container fails to start because it cannot bind-mount the Docker socket. Disable it in `app/supabase/config.toml`:
-```bash
-npx convex run --prod ...
-npx convex export --prod
+```toml [app/supabase/config.toml]
+[analytics]
+enabled = false
```
-Do **not** rely on the `CONVEX_DEPLOYMENT` environment variable. The CLI auto-loads `.env.local`, which overrides the env var, so commands intended for prod will silently hit the dev deployment.
+Without this, `supabase start` hangs or errors on Colima environments.
-### Directory naming
+### postgres:18 image - wrong volume mount path
-Convex rejects directory names that contain hyphens. Use underscores:
+If you use a `postgres:18` container (for example, for the PowerSync bucket-storage database), mount the data volume at `/var/lib/postgresql`, **not** `/var/lib/postgresql/data`:
-```text
-convex/test_utils/ # OK
-convex/test-utils/ # rejected
+```yaml
+volumes:
+ - pg_storage_data:/var/lib/postgresql
```
-### Multi-dot filenames
+Mounting at `/var/lib/postgresql/data` causes the container to fail on startup because postgres:18 changed the default data directory.
-Files whose names contain more than one dot (e.g. `setup.helper.ts`, `foo.bar.ts`) are automatically skipped by the Convex bundler. Useful for keeping test helpers out of the deployed function set.
+## PowerSync client
-### Deploy with pre-existing TS errors
+### No `INSERT ... ON CONFLICT` on PowerSync tables
-If the Convex function code has pre-existing TypeScript errors that block deploy, run:
+PowerSync client tables are SQLite **views** backed by INSTEAD OF triggers. They accept plain `INSERT`, `UPDATE`, and `DELETE` statements, but **not** `INSERT ... ON CONFLICT (upsert syntax)`.
-```bash
-npx convex deploy --typecheck=disable
-```
+Upsert logic must be done manually - check for row existence first, then INSERT or UPDATE:
-## Better Auth
+```ts
+// from app/services/powersync/mutations.ts
+async function upsertRow(table, id, row) {
+ await db.writeTransaction(async (tx) => {
+ const existing = await tx.getOptional(`SELECT id FROM ${table} WHERE id = ?`, [id])
+ if (existing) {
+ await tx.execute(`UPDATE ${table} SET ... WHERE id = ?`, [...values, id])
+ }
+ else {
+ await tx.execute(`INSERT INTO ${table} (id, ...) VALUES (?, ...)`, [id, ...values])
+ }
+ })
+}
+```
-### `login?error=please_restart_the_process` on Google sign-in
+See `app/services/powersync/mutations.ts` for the full implementation.
-**Symptom in Convex logs:**
+### Every synced table must have an `id` PK
-```text
-Q(adapter:findMany) ArgumentValidationError: Object contains extra field 'mode'
-Failed to parse state
-```
+PowerSync requires an `id` primary key on every synced table. For `user_settings`, the `id` column holds the user's Supabase uid. This is how the table satisfies the requirement while having exactly one row per user.
-**Cause:** Version mismatch between `better-auth` and `@convex-dev/better-auth`. The component declares a peer range and rejects newer Better Auth releases that introduce schema fields it does not know about.
+## Auth cookie race condition
-**Fix:** Align the two packages so the installed Better Auth version satisfies the component's peer range. For example, `@convex-dev/better-auth@^0.12.x` requires `better-auth@>=1.6.9 <1.7.0`. After the version bump:
+The route guard in `app/app/middleware/auth.global.ts` is synchronous - it reads the `finapp.localAuthUid` cookie with no network call, so it works offline. This means the cookie **must be set before navigation happens after sign-in**.
-```bash
-pnpm install
-npx convex dev --once --typecheck=disable
-```
+The PowerSync plugin (`app/app/plugins/powersync.client.ts`) watches the reactive `uid` from `useSupabaseAuth()`. When `uid` resolves (Supabase session ready), it calls `setAuthCookie(userId)` and then `connectPowerSync(...)`. Navigation to the dashboard only happens after the session has resolved and the cookie is set.
-The second command redeploys the auth component against the realigned dependency.
+If you move login flow logic around, make sure the cookie is always set from the resolved session before triggering any router navigation - otherwise the guard will redirect back to `/login`.
diff --git a/docs/content/en/3.reference/01.architecture.md b/docs/content/en/3.reference/01.architecture.md
index 88b91f9a..38c52b46 100644
--- a/docs/content/en/3.reference/01.architecture.md
+++ b/docs/content/en/3.reference/01.architecture.md
@@ -1,11 +1,11 @@
---
title: Architecture
-description: Initialization flow, project structure, store pattern, auth.
+description: Initialization flow, project structure, store pattern, auth - Supabase + PowerSync.
navigation:
icon: i-lucide-boxes
seo:
title: Architecture
- description: Finapp architecture deep-dive - app initialization, project structure, Pinia store pattern, Convex client access, auth flows, offline handling, and PWA setup.
+ description: Finapp architecture deep-dive - app initialization, project structure, Pinia store pattern, Supabase Auth, PowerSync offline-first, and PWA setup.
---
## App Initialization
@@ -15,119 +15,105 @@ app starts
├── Plugins
│ ├── theme.ts (enforce: 'post')
│ │ └── Read theme from localStorage → update appConfig
-│ └── convex.ts
-│ └── Create WebSocket client → setup auth
+│ └── powersync.client.ts
+│ ├── navigator.storage.persist() - protect IndexedDB from eviction
+│ ├── setUploadErrorHandler → showErrorToast('sync.errors.uploadRejected')
+│ └── watch uid (immediate)
+│ ├── uid present → setAuthCookie(uid) + connectPowerSync(...)
+│ └── uid absent → clearAuthCookie() + disconnectPowerSync()
├── app.vue
│ ├── useHead() - theme CSS vars (tagPriority: -2)
│ ├── useGuard() - auth redirect logic
│ └── render layout + page
└── useInitApp (on authenticated page)
- ├── loadDataFromCache() - parallel localforage reads (6 items)
- ├── loadDataFromDB()
- │ ├── await waitForConvexAuth() - ensure WebSocket is authenticated
- │ ├── parallel store init (5 stores)
- │ │ ├── initCurrencies()
- │ │ ├── initUserSettings()
- │ │ ├── initWallets()
- │ │ ├── initCategories()
- │ │ └── initTrns() - delta or full sync
- │ └── replayOfflineQueue() - replay pending offline ops
+ └── stores hydrate automatically via watchTable subscriptions
+ ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)
+ ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)
+ ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)
+ ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)
+ └── useTrnsStore - watchTable('SELECT * FROM trns', ...)
```
+Each `watchTable` fires immediately with current local SQLite rows and again on every change (local write or incoming sync). There is no separate init + subscribe step.
+
## Project Structure
```
-app/ # Nuxt app: components, composables, pages, plugins
-convex/ # Backend: schema, queries, mutations, auth, Telegram bot
-services/ # Client-side infrastructure (Convex client factory, API mappers)
-utils/ # Pure helpers (id, logger, types)
-utils/migrate/ # Firebase → Convex migration scripts (data.json gitignored)
-i18n/locales/ # en-US.js, ru-RU.js
+app/ # @finapp/app - Nuxt source, Supabase config, PowerSync config
+ app/ # Nuxt app root (components, composables, middleware, pages, plugins)
+ services/powersync/ # Client data layer: schema, db singleton, connector, transforms, mutations
+ supabase/ # Supabase config: migrations, RLS policies, powersync_setup.sql
+ powersync/ # Self-hosted PowerSync service: docker-compose, config/
+docs/ # @finapp/docs - documentation site
+i18n/locales/ # en-US.js, ru-RU.js
```
Conventions worth knowing (not obvious from `tree`):
-- `convex/_generated/` is produced by Convex CLI - never edit.
-- `services/convex/` is separate from `convex/` on purpose: `convex/` is the deployed backend, `services/` is frontend-only glue (client factory, doc → map converters).
-- Each feature under `app/components/<feature>/` owns its Pinia store, form, list, and types - there is no separate `stores/` directory.
+- `services/powersync/` is the client data layer: SQLite schema (`AppSchema.ts`), the `PowerSyncDatabase` singleton (`db.ts`), upload connector (`connector.ts`), row/item converters (`transforms.ts`), and write helpers (`mutations.ts`).
+- Each feature under `app/app/components/<feature>/` owns its Pinia store, form, list, and types - there is no separate `stores/` directory.
+- `supabase/migrations/` contains all Postgres schema changes. Never edit manually - use `supabase migration new`.
## Store Pattern
-All Pinia stores (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`) follow the same pattern:
+All Pinia stores (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`, `useUserStore`, `useCurrenciesStore`) follow the same pattern:
```
-items: shallowRef # reactive state (shallow for performance)
-init() # fetch from Convex → mergeOfflineOps → set
-set(data) # items.value = data + debouncedPersist (300ms)
-save({ id, values }) # optimistic UI → pushSaveOp → fire mutation
-delete(id) # optimistic UI → pushDeleteOp → fire mutation
+items: shallowRef<Map|null> # reactive state (shallow for performance)
+watchTable subscription # fires on init + every local write or incoming sync
+save({ id, values }) # optimistic write → upsertRow → rollback on error
+delete(id) # optimistic write → deleteRow → rollback on error
```
-### Data Flow (save)
+### Data Flow (write)
```
user action
→ save({ id, values })
- → isExisting = !isLocalId(id) && id in items
- → optimistic: set({ ...items, [id]: values })
- → pushSaveOp({ entity, id, isDemo, isExisting, values })
- → fire mutation (no await)
- → .then(): removeOfflineOp + remap frontend ID
- → .catch(): show error toast
+ → prev = snapshot of current items
+ → optimistic: items.value = new Map(...items, [id, values])
+ → await upsertRow(table, id, row)
+ → success: watchTable fires → store refreshes from SQLite
+ → failure: items.value = prev + showErrorToast
```
-### Data Flow (init)
+Write failure rollback handles local SQLite errors. Server-side rejection (RLS, constraint) is handled separately by the connector's upload-error handler (shows `sync.errors.uploadRejected` toast).
+
+### Data Flow (watchTable)
```
-init()
- → fetch from Convex (query)
- → convert to map (strip _id, _creationTime, userId)
- → mergeOfflineOps(data, entity)
- → read pending ops from queue
- → apply create/update ops on top of server data
- → remove stale frontend IDs
- → set(data)
+watchTable('SELECT * FROM trns', [], onRows, throttleMs)
+ → fires immediately with current local rows
+ → fires again on every table change (local write OR incoming PowerSync sync)
+ → onRows: rows → transform via rowToTrn() → items.value = new Map(...)
```
-## Convex Client Access
-
-| Composable | Returns | Purpose |
-|------------|---------|---------|
-| `useConvexClient()` | `ConvexClient` | WebSocket client singleton |
-| `useConvexClientWithApi()` | `{ api, client }` | Client + auto-generated `api` object for typed queries/mutations |
+`useTrnsStore` uses `reconcileTrns(prev, rows)` inside `onRows`: returns the same `prev` ref when nothing changed (suppresses the echo of the store's own optimistic write), and reuses unchanged row objects by `updatedAt` so `rowToTrn()` only runs for changed rows.
-Stores use imperative `client.query()` and `client.mutation()` because they manage their own caching and offline merge logic.
+### Cascade Delete
-**Auth flow (client - `plugins/convex.ts`):**
-1. On plugin init: if `hasAuthCookie()` && online → eagerly call `client.setAuth(fetchToken)` to start token fetch in parallel with session resolution
-2. `fetchToken` uses `authClient.convex.token()` (Better Auth `convexClient()` plugin) - the `crossDomainClient` plugin handles cookie forwarding via `localStorage['better-auth_cookie']`
-3. `authReadyPromise` resolves when first token fetch completes (success or failure) - `loadDataFromDB()` awaits this before issuing Convex queries
-4. Watch session state: only act on definitive results (user found → `setAuth()`, user absent without error → `clearAuth()`). Network errors and `isPending` states are ignored to prevent offline logout
-5. `online` event: re-creates `authReadyPromise` and calls `setAuth()` for a fresh token
-6. `ensureConvexAuth()`: called from `/auth/callback` to set auth BEFORE SPA navigation to dashboard
+`deleteWallet` and `deleteCategory` also delete the entity's trns from the local SQLite DB (otherwise the `watchTable` subscription would re-add them after the parent is removed). Rollback on failure restores both the entity and its trns.
-## Frontend ID System
+### Demo Mode
-New entities get temporary IDs with `local_` prefix (e.g., `local_a1b2c3`). `isLocalId(id)` checks `id.startsWith('local_')` to distinguish them. See [rationale](/en/development/tech-decisions#frontend-id-system).
+Demo mode bypasses PowerSync entirely. Stores check `isDemo` and skip all PowerSync calls. In-memory data + localforage persistence is used instead. Demo data (1000 trns, 18 categories, 6 wallets) is generated in `useDemo.ts`. Controlled by the `finapp.isDemo` cookie.
-Frontend IDs are remapped to Convex IDs in `handleMutationResult()` after successful create mutations. The store replaces `items[frontendId]` with `items[convexId]`.
+## Auth
-## Auth Guard
+### Supabase Auth
-### Auth Layers
-
-Auth uses two layers:
+`app/app/composables/useSupabase.ts` provides:
+- A singleton `supabase-js` client (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: false`).
+- `useSupabaseAuth()` composable exposing reactive `session`, `uid`, `user`, `isAuthReady`, plus `signInWithPassword` / `signUp` / `signOut`.
+- Session persists in localStorage and auto-refreshes. `onAuthStateChange` keeps a module-level reactive `session` ref in sync.
-1. **Route middleware** (`auth.global.ts`): checks `finapp.localAuthUid` cookie to decide whether to allow navigation or redirect to `/login`. Skips network calls when offline, trusting the cached cookie.
-2. **Client guard** (`useGuard()` in `app.vue`): watches the Better Auth session asynchronously and handles true session expiry after initial load. On unexpected session loss (not via sign-out), the `finapp.localAuthUid` cookie is cleared.
+Auth method: **email/password only** (no OAuth for the MVP).
-### OTT Auth Flow
+### Auth Guard
-Google OAuth uses a one-time token (OTT) for cross-domain authentication:
+Auth uses two layers:
-1. Google OAuth redirects back with `?ott=...` query parameter
-2. Global middleware intercepts any route with `ott` in the query and redirects to `/auth/callback`
-3. The callback page verifies the OTT with the Convex Better Auth backend
-4. On success: sets auth cookie, calls `ensureConvexAuth()` to start Convex auth immediately, then navigates via `navigateTo()` to the original redirect destination
+1. **Route middleware** (`app/app/middleware/auth.global.ts`): synchronous gate on the `finapp.localAuthUid` cookie (`hasAuthCookie()`), no network call, works offline. Redirects to `/login` (preserving `?redirect=`) when absent; bounces `/login` → `/dashboard` when the cookie is present. Demo mode bypasses this check.
+2. **PowerSync plugin** (`app/app/plugins/powersync.client.ts`): watches the Supabase `uid`. Sets the `finapp.localAuthUid` cookie when a session resolves; clears it on sign-out. This is the only place the cookie is written.
### Redirect Protection
@@ -140,113 +126,83 @@ Google OAuth uses a one-time token (OTT) for cross-domain authentication:
- Not logged in + not on `/login` → redirect to `/login`
- `isSigningOut` flag prevents redirect loop during sign-out
-## Offline / Online Handling
-
-The app preserves auth state and data when offline:
+## Cross-User Local DB Protection
-- **Auth cookie preserved offline:** Session watch ignores network errors (`s.error`) - only definitive "no user" responses clear the cookie. This prevents logout when offline or on flaky connections.
-- **Token fetch skipped offline:** `fetchToken` checks `!navigator.onLine` before making HTTP requests - avoids noisy errors in the console.
-- **Reconnect:** `online` event listener re-creates `authReadyPromise` and calls `setAuth()` so that `loadDataFromDB()` (which awaits `waitForConvexAuth()`) gets a fresh token.
-- **Route middleware:** `auth.global.ts` checks `hasAuthCookie()` synchronously - no network calls, works offline.
-- **PWA:** Service worker precaches all build assets + `NavigationRoute` serves SPA shell for all navigation requests.
+`connectPowerSync(client, powerSyncUrl, userId)` checks a persisted owner marker (`finapp.psDbOwnerUid` in localStorage). If the local SQLite belongs to a different user, the database is **wiped before connecting** (fail-closed). This prevents data leaks when a different account logs in on the same device.
## Sign-Out Flow
```
signOut()
→ isSigningOut = true (prevents auth guard redirect loop)
- → clear store data (trns, categories, wallets, user)
- → clear auth cookie
- → clear localforage
- → authClient.signOut()
- → remove better-auth localStorage keys
+ → supabase.auth.signOut()
+ → disconnectPowerSync() - disconnectAndClear() wipes local SQLite + clears owner marker
+ → clearAuthCookie()
→ window.location.href = '/login' (hard navigation, destroys all JS state)
```
-Hard navigation instead of Vue Router - see [rationale](/en/development/tech-decisions#hard-navigation-on-sign-out).
-
-## Demo Mode
-
-Demo mode works without authentication. Controlled by `finapp.isDemo` cookie.
-
-- **Data:** 1000 random transactions, 18 categories, 6 wallets - generated in `useDemo.ts`
-- **Storage:** localStorage/localforage only, no Convex calls
-- **Store isolation:** all store mutation methods (`saveTrn`, `saveWallet`, etc.) check `isDemo` and skip Convex mutations + offline queue
-- **Sign-out:** clears local data, no `authClient.signOut()` call
+Hard navigation instead of Vue Router - see [Technical Decisions](/en/development/tech-decisions).
## Exchange Rates
-- **Source:** OpenExchangeRates API (free tier)
-- **Schedule:** Daily cron at 6:00 UTC (`convex/crons.ts`)
-- **Storage:** `rates` table with `by_date` index (one row per day)
-- **Frontend:** `useCurrenciesStore` fetches latest rates, triggers refresh if empty
-- **Fallback:** If no rates exist in the database (new deployment), rates must be populated via the daily cron or manual `npx convex run`
+- **Source:** OpenExchangeRates API (free tier), populated server-side
+- **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
-## Modal State
-
-Modals use local `ref`s and `v-if` + `@close` emit pattern. Menu visibility is a module-level `ref` in `useMenuData.ts` (shared across callers). Other modals (e.g., wallet sort) use component-local `ref`s. No global modal registry - modals unmount automatically when parent components unmount (e.g., on sign-out, stores reset to `null` → layout condition becomes false → modals disappear).
-
-## Sidebar Persistence
-
-The desktop sidebar show/hide state is stored in a cookie (`finapp.isShowSidebar`), providing persistent state across page loads.
-
-## Bottom Sheet
-
-The mobile transaction form uses a custom `BottomSheet` component with `useBottomSheetDrag` - a hand-written drag implementation supporting touch and mouse. Features: configurable start-closing offset, direction detection, overlay opacity fade, scroll-aware behavior (ignores drag when content is scrolled), sort handle exclusion.
-
-## Logging
-
-`createLogger(prefix)` (`app/utils/logger.ts`) provides dev-only logging. In production, only `.error()` fires. All store operations and auth flows are instrumented with prefixed logs (`[wallets]`, `[trns]`, `[auth/middleware]`, etc.). Check the browser console during `pnpm dev`.
-
## PWA
- Strategy: `generateSW` from `@vite-pwa/nuxt` (no custom service worker)
-- Precaching: all build assets are precached automatically
+- Precaching: all build assets including `wasm` files; `maximumFileSizeToCacheInBytes: 3 MiB` so the wa-sqlite WASM files are precached for offline start
- `navigateFallback: '/'` serves SPA shell for all navigation (offline support)
- Runtime caching: Google Fonts, Iconify icons (CacheFirst)
- Start URL: `/dashboard`
- Manifest: `display: 'standalone'`
-## Migration Tools
+## Logging
-Convex backend includes internal mutations for data migration, callable via `npx convex run`:
+`createLogger(prefix)` (`app/utils/logger.ts`) provides dev-only logging. In production, only `.error()` fires. All store operations and auth flows are instrumented with prefixed logs (`[wallets]`, `[trns]`, `[auth/middleware]`, etc.). Check the browser console during `pnpm dev`.
-| Function | Purpose |
-|----------|---------|
-| `migrate:deleteUserData` | Delete all data for a user |
-| `migrate:insertWallets` | Bulk import wallets with ID remapping |
-| `migrate:insertCategories` | Bulk import categories with parentId remapping |
-| `migrate:insertTrnsBatch` | Bulk import transactions |
-| `migrate:insertUserSettings` | Import user settings |
+## Modal State
-Migration script: `utils/migrate/firebase.js` - reads Firebase JSON export, transforms data, and calls the mutations above. See [Migration from Firebase](/en/development/migration) for details.
+Modals use local `ref`s and `v-if` + `@close` emit pattern. Menu visibility is a module-level `ref` in `useMenuData.ts` (shared across callers). No global modal registry - modals unmount automatically when parent components unmount (e.g., on sign-out, stores reset to `null` → layout condition becomes false → modals disappear).
+
+## Sidebar Persistence
+
+The desktop sidebar show/hide state is stored in a cookie (`finapp.isShowSidebar`), providing persistent state across page loads.
+
+## Bottom Sheet
+
+The mobile transaction form uses a custom `BottomSheet` component with `useBottomSheetDrag` - a hand-written drag implementation supporting touch and mouse. Features: configurable start-closing offset, direction detection, overlay opacity fade, scroll-aware behavior (ignores drag when content is scrolled), sort handle exclusion.
## Key Files Quick Reference
| What | Where |
|------|-------|
-| App entry | `app/app.vue` |
-| Theme logic | `app/plugins/theme.ts`, `app/app.vue` |
-| Auth setup | `app/plugins/convex.ts`, `app/composables/useAuth.ts` |
-| Auth cookie | `app/composables/useAuthCookie.ts` |
-| Auth guard | `app/middleware/auth.global.ts`, `app/components/user/useGuard.ts` |
-| Store sync | `app/composables/useStoreSync.ts` |
-| Offline queue | `app/components/offline/helpers.ts` |
-| Offline replay | `app/components/offline/replay.ts` |
-| Statistics calc | `app/components/amount/getTotal.ts` |
-| Convex schema | `convex/schema.ts` |
-| Frontend IDs | `app/utils/convexId.ts`, `utils/generateId.ts` |
-| Date utils | `app/components/date/utils.ts` |
-| Logging | `app/utils/logger.ts` |
+| App entry | `app/app/app.vue` |
+| Theme logic | `app/app/plugins/theme.ts`, `app/app/app.vue` |
+| PowerSync plugin | `app/app/plugins/powersync.client.ts` |
+| Supabase client + auth | `app/app/composables/useSupabase.ts` |
+| Auth cookie | `app/app/composables/useAuthCookie.ts` |
+| Auth guard (middleware) | `app/app/middleware/auth.global.ts` |
+| Guard logic (app.vue) | `app/app/components/user/useGuard.ts` |
+| Store sync utils | `app/app/composables/useStoreSync.ts` |
+| PowerSync db singleton | `app/services/powersync/db.ts` |
+| SQLite schema | `app/services/powersync/AppSchema.ts` |
+| Upload connector | `app/services/powersync/connector.ts` |
+| Row/item transforms | `app/services/powersync/transforms.ts` |
+| Write helpers | `app/services/powersync/mutations.ts` |
+| Echo suppression | `app/app/components/trns/reconcile.ts` |
+| Statistics calc | `app/app/components/amount/getTotal.ts` |
| Redirect protection | `app/utils/redirect.ts` |
-| Menu state | `app/components/layout/useMenuData.ts` |
-| Bottom sheet drag | `app/components/bottomSheet/useBottomSheetDrag.ts` |
-| Migration tools | `convex/migrate.ts`, `utils/migrate/firebase.js` |
-| Telegram bot | `convex/telegram/bot.ts`, `convex/telegram/link.ts` |
-| Telegram settings UI | `app/components/telegram/SettingsCard.vue` |
+| Date utils | `app/app/components/date/utils.ts` |
+| Logging | `app/utils/logger.ts` |
+| Menu state | `app/app/components/layout/useMenuData.ts` |
+| Bottom sheet drag | `app/app/components/bottomSheet/useBottomSheetDrag.ts` |
+| Supabase migrations | `app/supabase/migrations/` |
+| PowerSync sync rules | `app/powersync/config/sync-config.yaml` |
## Next Steps
-- [Sync](/en/development/sync) - delta sync mechanism for transactions
-- [Offline Queue](/en/development/offline-queue) - offline operation queue and frontend ID system
+- [Sync](/en/development/sync) - how PowerSync syncs data between server and local SQLite
+- [Offline-first](/en/development/offline-queue) - offline writes, upload queue, and error handling
diff --git a/docs/content/en/3.reference/02.transaction-types.md b/docs/content/en/3.reference/02.transaction-types.md
index d670800c..aadd1b3c 100644
--- a/docs/content/en/3.reference/02.transaction-types.md
+++ b/docs/content/en/3.reference/02.transaction-types.md
@@ -88,13 +88,13 @@ These categories are:
## Type Change Behavior
-When a transaction's type changes via `trns.update`, the Convex backend normalizes the data:
+When a transaction's type changes, normalization happens client-side in `trnToRow` (`services/powersync/transforms.ts`) at write time - there is no server backend doing it:
-- **→ Transfer**: sets `categoryId` to `'transfer'`, clears single-wallet fields (`walletId`, `amount`)
-- **→ Expense/Income**: clears transfer-specific fields (`expenseWalletId`, `incomeWalletId`, `expenseAmount`, `incomeAmount`)
+- **→ Transfer**: `trnToRow` sets `categoryId` to `'transfer'` and writes `expenseWalletId`/`incomeWalletId`/`expenseAmount`/`incomeAmount`; non-transfer fields (`walletId`, `amount`) are written as `null`
+- **→ Expense/Income**: `trnToRow` writes `walletId`/`amount`; transfer-specific fields (`expenseWalletId`, `incomeWalletId`, `expenseAmount`, `incomeAmount`) are written as `null`
- **→ Adjustment**: no extra clearing - adjustment uses regular Expense/Income fields with `categoryId: 'adjustment'`
-This prevents orphaned index entries and ensures only the fields relevant to the current type are stored.
+This ensures only the fields relevant to the current type carry non-null values in the local SQLite row and on the server.
## Statistics
diff --git a/docs/content/en/3.reference/03.sync.md b/docs/content/en/3.reference/03.sync.md
index 4f886983..587ba59d 100644
--- a/docs/content/en/3.reference/03.sync.md
+++ b/docs/content/en/3.reference/03.sync.md
@@ -1,89 +1,115 @@
---
title: Sync
-description: Delta sync for transactions - deletion detection, performance.
+description: How PowerSync keeps local SQLite in sync with Supabase Postgres.
navigation:
icon: i-lucide-refresh-cw
seo:
title: Sync
- description: How Finapp syncs transactions incrementally - delta sync mechanism, deletion detection via hash comparison, offline queue interaction, and key files.
+ description: How Finapp syncs data offline-first with PowerSync - local SQLite as source of truth, per-user sync streams, upload queue, throttle/coalesce, echo suppression, and deletion handling.
---
-Transactions use incremental (delta) sync to avoid re-downloading all data on every app open. Called from `initTrns()` during [app initialization](/en/development/architecture#app-initialization).
+PowerSync is the sync layer between the client (local SQLite via wa-sqlite / IndexedDB) and the server (Supabase Postgres). Local SQLite is the single source of truth for the UI - stores read only from SQLite, never from the network directly.
## How It Works
-1. Read `syncMeta` from LocalForage
-2. **No syncMeta or no cache** → `fullSync()`: fetch all via paginated `trns.list`, save syncMeta
-3. **Has syncMeta + cache** → `deltaSync()`: fetch only changes via paginated `trns.delta` + `trns.idsHash` (parallel)
-4. On delta error or hash mismatch → fallback to `fullSync()`
-5. Both paths end with `mergeOfflineOps()` + `setTrns()`
+```
+Supabase Postgres (server)
+ ↕ logical replication (powersync_role, powersync publication)
+PowerSync service (self-hosted, :8080)
+ ↕ WebSocket sync stream (Sync Streams edition 3, per-user + global)
+Local SQLite (client, IDBBatchAtomicVFS / IndexedDB)
+ ↕ watchTable subscriptions
+Pinia stores (UI)
+```
-## Convex Queries
+On connect, PowerSync replays the server state into local SQLite. After that, every server change streams in via the open WebSocket. Local writes go to SQLite immediately (optimistic) and are queued for upload.
-| Query | Args | Returns | Index |
-|-------|------|---------|-------|
-| `trns.list` | `paginationOpts` | Paginated user trns (`PaginationResult`) | `by_user_date` |
-| `trns.delta` | `paginationOpts`, `since: number` | Paginated trns with `updatedAt > since` (`PaginationResult`) | `by_user_updatedAt` |
-| `trns.idsHash` | - | XOR hash of all trn IDs (string) | `by_user` |
+## Sync Streams
-## Sync Metadata
+Sync rules are defined in `app/powersync/config/sync-config.yaml` using **Sync Streams edition 3**.
-Stored in LocalForage under key `finapp.trns.syncMeta`:
+**Per-user stream (`user_data`, auto_subscribe):**
+```sql
+SELECT * FROM categories WHERE "userId" = auth.user_id()
+SELECT * FROM wallets WHERE "userId" = auth.user_id()
+SELECT * FROM trns WHERE "userId" = auth.user_id()
+SELECT * FROM user_settings WHERE "userId" = auth.user_id()
+```
-```typescript
-type TrnsSyncMeta = {
- lastSyncedAt: number // timestamp of last successful sync
- idsHash: string // XOR hash of all trn IDs at last sync
-}
+**Global stream (`rates`):**
+```sql
+SELECT * FROM rates
```
-## Deletion Detection
+`auth.user_id()` resolves to the Supabase user UUID from the validated JWT. The PowerSync service validates Supabase JWTs (ES256) via the JWKS endpoint, so no custom token logic is required on the client.
+
+## watchTable - the Single Subscription Pattern
+
+`watchTable(sql, params, onRows, throttleMs?)` in `app/services/powersync/db.ts`:
+
+- Executes the SQL query immediately and calls `onRows` with the current local rows.
+- Subscribes to table-change events. Whenever any row in the queried table changes (local write or incoming sync), `onRows` is called again with fresh rows.
+- `throttleMs` coalesces rapid bursts of changes (trailing edge). Default: 30ms. Transactions use 120ms to handle the large burst of rows during initial sync without thrashing the UI.
+- Returns an `AbortController` - call `.abort()` to unsubscribe (stores do this on teardown).
+
+This single mechanism replaces the old init + realtime-subscription split. There is no separate "load from cache, then subscribe" step.
+
+## Echo Suppression (Transactions)
+
+When a store writes optimistically and then `watchTable` fires for that same write, the UI would flicker. `useTrnsStore` avoids this with `reconcileTrns(prev, rows)` (`app/app/components/trns/reconcile.ts`):
+
+- Compares incoming rows to the previous state by `updatedAt`.
+- If nothing has changed, returns the same `prev` ref (Vue sees no change, no re-render).
+- For changed rows, only runs `rowToTrn()` for the delta - unchanged row objects are reused.
+
+## Upload Queue
+
+Local writes are queued by PowerSync automatically. `SupabaseConnector.uploadData()` (`app/services/powersync/connector.ts`) drains the queue:
+
+| PowerSync op | Supabase call |
+|-------------|--------------|
+| `PUT` | `supabase.from(table).upsert(row)` |
+| `PATCH` | `supabase.from(table).update(data).eq('id', id)` |
+| `DELETE` | `supabase.from(table).delete().eq('id', id)` |
-Since Convex uses hard deletes (no `deletedAt` field), deletions are detected by hash comparison:
+The connector runs as the authenticated Supabase user, so RLS policies apply on every upload. This is the write-path security layer - the read path uses the `powersync_role` (BYPASSRLS) for replication, with per-user partitioning enforced by sync rules.
-1. `deltaSync()` applies delta changes to cached data
-2. Computes local XOR hash from all non-local IDs in the resulting data
-3. Compares with `trns.idsHash()` from server
-4. **Hash match** → no deletions, sync complete
-5. **Hash mismatch** → deletions or missed changes detected → fallback to `fullSync()`
+## Fatal vs Retryable Upload Errors
-This approach is simple and reliable. Deletions are rare (1-2 per month), so a one-time `fullSync()` on hash mismatch is an acceptable trade-off.
+| Error class | Postgres codes | Behavior |
+|------------|----------------|----------|
+| Fatal (data / constraint / RLS) | `22xxx`, `23xxx`, `42501` | Transaction **discarded** - queue unblocked; `setUploadErrorHandler` fires `sync.errors.uploadRejected` toast |
+| Retryable (network, timeout) | everything else | Error **rethrown** - PowerSync retries with backoff |
-## Full Sync Triggers
+Discarding a fatal op means the local write and server have silently diverged for that row. The user sees a toast and can correct the data manually.
-Full sync runs when:
-- First app open (no syncMeta in LocalForage)
-- LocalForage cache is cleared
-- Delta sync fails (network error, corrupt data)
-- Hash mismatch after applying delta (deletions detected)
+## Deletion Handling
-## Interaction with Offline Queue
+PowerSync syncs hard deletes natively - when a row is deleted on the server the PowerSync service streams a delete event to the client and SQLite removes the row. No hash comparison or full-refetch is needed.
-Delta sync is fully compatible with the [offline queue](/en/development/offline-queue):
-- `mergeOfflineOps()` runs after both full and delta sync
-- `cleanupFrontendIds()` removes stale frontend IDs from the merged data that are no longer in pending ops (already synced in a previous session but still cached)
-- Offline-created trns (frontend IDs) are not affected by deletion detection (only Convex IDs are compared)
-- The offline queue replay happens after `initTrns()` completes
+**Cascade deletes (client-side):** `deleteWallet` and `deleteCategory` also delete the entity's trns from local SQLite before returning. Without this, the `watchTable` subscription on `trns` would re-add the orphaned rows to the UI after the parent entity is gone.
-## Performance
+## First Sync
-| Metric | Full sync (10K trns) | Delta sync (10 changes) |
-|--------|---------------------|------------------------|
-| Network | ~2 MB (paginated) | ~2 KB (delta) + hash |
-| Parsing | 10K objects | 10 objects |
-| Reduction | - | ~99% network and parsing |
+`waitForFirstSync(timeoutMs=10000)` (`app/services/powersync/db.ts`) resolves once the initial server state has fully streamed into local SQLite (or times out). `useInitApp` waits for this before showing the main UI, ensuring the user never sees an empty app after login.
## Key Files
| File | Role |
|------|------|
-| `convex/trns.ts` | `list`, `delta`, `idsHash` queries |
-| `convex/schema.ts` | `by_user_updatedAt` index |
-| `app/components/trns/useTrnsStore.ts` | `fullSync()`, `deltaSync()`, `initTrns()`, `fetchAllPages()` |
-| `app/composables/useStoreSync.ts` | `mergeOfflineOps()`, `cleanupFrontendIds()` |
-| `app/components/offline/storageKeys.ts` | `trnsSyncMeta` storage key |
+| `app/services/powersync/db.ts` | `PowerSyncDatabase` singleton, `connectPowerSync`, `watchTable`, `waitForFirstSync` |
+| `app/services/powersync/connector.ts` | `SupabaseConnector` - `fetchCredentials` + `uploadData` |
+| `app/services/powersync/AppSchema.ts` | Client SQLite schema |
+| `app/services/powersync/transforms.ts` | `rowToTrn`, `rowToWallet`, `rowToCategory`, `rowToRates`, `trnToRow`, etc. |
+| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow`, `upsertRows` |
+| `app/app/components/trns/useTrnsStore.ts` | `watchTable` subscription + `reconcileTrns` echo suppression |
+| `app/app/components/trns/reconcile.ts` | `reconcileTrns` - dedup and reuse unchanged row objects |
+| `app/app/plugins/powersync.client.ts` | Plugin that connects/disconnects PowerSync on auth state change |
+| `app/powersync/config/sync-config.yaml` | Sync Streams rules (per-user + global rates) |
+| `app/powersync/config/service.yaml` | PowerSync service config (replication, JWT, port 8080) |
+| `app/supabase/powersync_setup.sql` | `powersync_role` + `powersync` publication |
## Next Steps
-- [Offline Queue](/en/development/offline-queue) - how offline operations interact with sync
+- [Offline-first](/en/development/offline-queue) - offline writes, upload queue, and fatal error handling
- [Architecture](/en/development/architecture) - app initialization and store pattern
diff --git a/docs/content/en/3.reference/04.offline-queue.md b/docs/content/en/3.reference/04.offline-queue.md
index f1c98bc5..a60cb085 100644
--- a/docs/content/en/3.reference/04.offline-queue.md
+++ b/docs/content/en/3.reference/04.offline-queue.md
@@ -1,204 +1,84 @@
---
-title: Offline Queue
-description: Queue architecture, collapsing rules, sync scenarios.
+title: Offline-first
+description: How PowerSync enables offline writes, upload queue, and error surfacing.
navigation:
icon: i-lucide-list-ordered
seo:
- title: Offline Queue
- description: Finapp's offline queue stores pending operations locally and syncs on reconnect. Covers collapsing rules, frontend ID system, and edge case scenarios.
+ title: Offline-first
+ description: Finapp is offline-first via PowerSync - local SQLite holds all data, writes are optimistic and queued locally, fatal upload errors are discarded and surfaced via toast.
---
-Unified ordered offline queue with operation collapsing. All pending operations (create/update/delete) for wallets, categories, and trns are stored in a single ordered array in localforage under key `finapp.offline.queue`.
+Finapp is offline-first via PowerSync. Local SQLite is the single source of truth. All reads come from SQLite; all writes go to SQLite first and are queued for upload to Supabase Postgres.
-## Architecture
+## How It Works
-### Key Files
-
-| File | Description |
-|------|-------------|
-| `app/components/offline/types.ts` | Types: `OfflineOp`, `EntityType` |
-| `app/components/offline/helpers.ts` | Queue API: push, remove, get, clear |
-| `app/components/offline/replay.ts` | Replay queue on app restart |
-| `app/components/offline/storageKeys.ts` | LocalForage keys for entity caches |
-
-### Collapsing Rules
-
-When pushing a new operation, the queue finds the last operation with the same `entity + id` and collapses:
-
-| Existing | New | Result |
-|----------|-----|--------|
-| create | update | create (merged data) |
-| create | delete | remove both (never reached server) |
-| update | update | update (merged data) |
-| update | delete | replace with delete |
-| delete | * | ignore new (delete is terminal) |
-| - | * | append as-is |
-
-### Serialization
-
-`pushOfflineOp` uses a promise chain to serialize concurrent writes - no `await` required at call sites.
+```
+user action (create/update/delete)
+ → optimistic: items.value updated in store immediately
+ → upsertRow / deleteRow writes to local SQLite (sync)
+ → success: watchTable fires → store refreshes from SQLite
+ → failure: rollback prev snapshot + showErrorToast (local write error)
+ → PowerSync queues the op for upload
+ → online: connector drains queue → Supabase upsert/update/delete
+ → offline: queue persists in SQLite; drained on reconnect
+```
-### Backend Cascade
+There is no manual queue management, no collapsing rules, and no frontend-local ID system. PowerSync owns the upload queue.
-Both `wallets.remove` and `categories.remove` on the Convex backend cascade-delete all associated trns. The frontend does NOT push separate trns delete operations when deleting a wallet or category - only the parent entity delete goes into the queue. `removeTrnsFromStore()` handles optimistic UI cleanup without mutations.
+## Offline Writes
-## Frontend ID System
+When the device is offline:
+- Reads continue to work - all data is already in local SQLite.
+- Writes go to local SQLite immediately (optimistic). The user sees the change right away.
+- The upload op is added to PowerSync's internal queue.
+- On reconnect, PowerSync drains the queue automatically.
-New entities need IDs before the server responds. The frontend generates temporary IDs that are later remapped to real Convex IDs.
+No user action is needed to trigger sync after reconnect.
-### Generation
+## Upload Error Handling
-`generateId()` (`utils/generateId.ts`) produces IDs with `local_` prefix + 6 random base-36 characters. Example: `local_a1b2c3`.
+`SupabaseConnector.uploadData()` distinguishes fatal errors from retryable ones:
-### Distinguishing from Convex IDs
+### Fatal errors (discarded)
-`isLocalId(id)` (`app/utils/convexId.ts`) checks `id.startsWith('local_')`. Any ID with the `local_` prefix is a frontend ID.
+Postgres error classes `22xxx` (data exception), `23xxx` (integrity constraint violation), and `42501` (RLS - insufficient privilege) are treated as fatal. The failing op is **discarded** so it does not block the rest of the queue. The plugin surfaces the error via `showErrorToast('sync.errors.uploadRejected')`.
-This check is used throughout the codebase:
-- Stores: determine create vs update (`!isLocalId(id) && id in items`)
-- Delta sync: exclude local IDs from deletion detection
-- Batch delete: filter out local IDs for server mutation
-- Replay: skip delete operations for local IDs (nothing to delete on server)
+A discarded op means the local SQLite and the server have silently diverged for that row. The user is notified via toast and can correct the data manually (e.g., re-edit and re-save the record).
-### ID Remapping
+### Retryable errors
-After a successful create mutation, the server returns the new Convex ID. `handleMutationResult()` (`app/composables/useStoreSync.ts`) replaces the frontend ID key in the store map:
+Network errors, timeouts, and all other non-fatal errors cause the error to be **rethrown**. PowerSync catches the rethrow and retries with backoff when connectivity is restored.
-```
-items[frontendId] → items[convexId] (same entity data, new key)
-```
+## Cascade Deletes
-The remapped store is persisted to localforage immediately.
+`deleteWallet` and `deleteCategory` also delete the entity's trns from local SQLite before returning. This is required because the `watchTable` subscription on `trns` would otherwise re-add the orphaned rows to the store after the parent entity is removed from SQLite. Rollback on a local write failure restores both the entity and its trns.
-### Stale ID Cleanup
+The server enforces no foreign key constraints (PowerSync upload order is not guaranteed), so referential integrity lives in app logic.
-`cleanupFrontendIds()` (`app/utils/convexId.ts`) runs during `mergeOfflineOps()` on every init. It removes local IDs from cached data that are no longer in the pending offline queue - these are IDs from a previous session that were either successfully remapped or abandoned.
+## Optimistic Rollback
-### Where Frontend IDs Are Created
-
-| Entity | File | Code |
-|--------|------|------|
-| Transaction | `app/components/trnForm/useTrnsFormStore.ts` | `id: values.trnId ?? generateId()` |
-| Category | `app/components/categories/Form.vue` | `editCategoryId = props.categoryId ?? generateId()` |
-| Wallet | `app/components/wallets/Form.vue` | `editWalletId = props.walletId ?? generateId()` |
-
-### Edge Cases
-
-**Parallel creates:** Each remapping is independent - destructuring extracts the specific frontend ID and rebuilds the object. No conflicts between concurrent create mutations.
-
-**Crash before remapping:** If the app crashes after mutation succeeds but before `.then()` runs, the next session's `cleanupFrontendIds()` removes the stale frontend ID from cache, and the entity exists on the server with its Convex ID.
-
-## Scenarios
-
-### Create
-
-#### Online
-1. User creates entity (wallet/category/trn)
-2. Store generates frontend ID (e.g. `local_abc123`)
-3. Optimistic UI: entity appears in store immediately
-4. `pushOfflineOp({ type: 'create', ... })` saves to queue
-5. Convex mutation fires (fire-and-forget)
-6. `.then()`: removes op from queue, remaps frontend ID to Convex ID in store
-
-#### Offline
-1. Steps 1-4 same as online
-2. Mutation fails (network error) - `.catch()` shows toast
-3. Operation stays in queue
-4. Entity visible in UI with frontend ID
-
-#### Restart after offline create
-1. `initTrns` fetches server data (full sync on first load, [delta sync](/en/development/sync) on subsequent loads); `initWallets/initCategories` fetch full data
-2. Pending ops from queue merged on top (frontend ID entries added to store)
-3. `replayOfflineQueue()` runs:
- - Frontend ID + create/update → dispatches to store method → mutation fires → `.then()` remaps ID
- - Frontend ID + delete → skipped (nothing to delete on server)
-4. Entity gets real Convex ID
-
-### Update
-
-#### Online
-1. User edits entity
-2. `isExisting = !isLocalId(id) && id in items` → `true`
-3. Optimistic UI: store updated immediately
-4. `pushOfflineOp({ type: 'update', ... })` - collapses with existing ops
-5. Convex `update` mutation fires
-6. `.then()`: removes op from queue
-
-#### Offline
-1. Steps 1-4 same as online
-2. Mutation fails - op stays in queue
-3. Multiple edits collapse: update + update → single update with merged data
-
-#### Restart after offline update
-1. Init fetches server data - old version (via [delta sync](/en/development/sync) or full sync)
-2. Pending update merged on top → UI shows latest version
-3. Replay dispatches update → mutation fires → synced
-
-### Delete
-
-#### Online
-1. User deletes entity
-2. Optimistic UI: removed from store immediately
-3. For wallets/categories: `removeTrnsFromStore()` removes child trns from UI
-4. `pushOfflineOp({ type: 'delete', ... })` - collapses with existing ops
-5. Convex `remove` mutation fires (cascade-deletes trns on backend)
-6. `.then()`: removes op from queue
-
-#### Offline
-1. Steps 1-4 same as online
-2. Mutation fails - op stays in queue
-3. Collapsing: if entity was created offline and then deleted → both ops removed (never reached server)
-
-#### Restart after offline delete
-1. Init fetches server data - entity still exists on server (via [delta sync](/en/development/sync) or full sync)
-2. Pending delete removes entity from merged data
-3. Replay dispatches delete → mutation fires → synced
-
-### Edge Cases
-
-#### Create + Edit offline, then restart
-1. Create: `pushOfflineOp({ type: 'create', data: v1 })`
-2. Edit: collapses to `create` with merged data (v1 + v2)
-3. Restart: single create op replayed → server gets final version
-
-#### Create + Delete offline, then restart
-1. Create: `pushOfflineOp({ type: 'create', ... })`
-2. Delete: collapses → both ops removed from queue
-3. Restart: nothing to replay, entity never existed on server
-
-#### Delete wallet/category with trns offline
-1. `pushOfflineOp({ type: 'delete', entity: 'wallets', id })` - only wallet delete in queue
-2. `removeTrnsFromStore(trnsIds)` - optimistic UI cleanup, no queue ops for trns
-3. Restart: wallet delete replayed → backend cascade deletes trns
-
-#### Orphaned trns on replay
-1. Trn created offline referencing wallet/category
-2. That wallet/category deleted (also offline or by another device)
-3. Replay detects orphan: wallet/category no longer in store
-4. Orphaned trn op removed from queue, toast shown to user
-
-#### Concurrent pushOfflineOp calls
-Promise chain serialization ensures writes don't overwrite each other:
-```typescript
-let writeChain = Promise.resolve()
-export function pushOfflineOp(op) {
- writeChain = writeChain.then(() => impl(op), () => impl(op))
- return writeChain
-}
-```
+Every store write snapshots `prev = items.value` before mutating. If the local SQLite write throws, `items.value = prev` is restored and an error toast is shown. This covers local write errors (e.g., SQLite constraint, disk full). Server-rejection errors (RLS, constraint) are handled separately by the upload-error handler.
-#### isReplaying flag
-During replay, store methods skip `pushOfflineOp` to avoid re-queuing operations that are already being replayed. The flag is set before the replay loop and cleared in `finally`.
+## No Manual Offline Queue
-## Known Limitations
+The hand-written offline queue (`components/offline/helpers.ts`, `replay.ts`, `replayHelpers.ts`, `types.ts`) and the `local_`-prefix frontend ID system have been removed. PowerSync provides the upload queue natively. There is no `replay()`, no `mergeOfflineOps()`, no `cleanupFrontendIds()`, and no ID remapping.
-### Wallet order not in offline queue
+Client IDs are regular UUIDs (generated client-side via `crypto.randomUUID()` or equivalent). They are stable and do not need remapping after upload.
-`saveWalletsOrder` uses fire-and-forget without the offline queue. If the user reorders wallets while offline and closes the app before the mutation succeeds, the order is lost on next load (server returns old order, no pending op to merge).
+## Key Files
-This is intentional - wallet reordering is rare and the added complexity of storing order operations in the queue (special `id: 'order'`, separate merge logic in `initWallets`, extra replay branch) is not justified.
+| File | Role |
+|------|------|
+| `app/services/powersync/connector.ts` | `SupabaseConnector.uploadData()` - drains queue, fatal/retryable split |
+| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow` - write to local SQLite |
+| `app/services/powersync/db.ts` | `watchTable` - subscribe to SQLite changes |
+| `app/app/plugins/powersync.client.ts` | Registers upload-error handler (toast) |
+| `app/app/components/trns/useTrnsStore.ts` | Optimistic write + rollback pattern, cascade delete trns |
+| `app/app/components/wallets/useWalletsStore.ts` | Optimistic write + rollback + cascade delete trns |
+| `app/app/components/categories/useCategoriesStore.ts` | Optimistic write + rollback + cascade delete trns |
+| `app/app/composables/useStoreSync.ts` | `showErrorToast`, `showSuccessToast`, demo-only `createDebouncedPersist` |
## Next Steps
-- [Sync](/en/development/sync) - delta sync and hash-based deletion detection
-- [Technical Decisions](/en/development/tech-decisions) - rationale behind fire-and-forget mutations
+- [Sync](/en/development/sync) - PowerSync sync streams, upload queue, and deletion handling
+- [Architecture](/en/development/architecture) - app initialization and store pattern
diff --git a/docs/content/en/3.reference/05.tech-decisions.md b/docs/content/en/3.reference/05.tech-decisions.md
index 52704bad..2b8a3d48 100644
--- a/docs/content/en/3.reference/05.tech-decisions.md
+++ b/docs/content/en/3.reference/05.tech-decisions.md
@@ -5,53 +5,73 @@ navigation:
icon: i-lucide-lightbulb
seo:
title: Technical Decisions
- description: Technical decisions in Finapp and their rationale: delta sync, optimistic UI, frontend IDs, hard sign-out navigation, arithmetic parser, and cascade deletes.
+ description: Technical decisions in Finapp and their rationale - PowerSync offline-first, optimistic UI, client-generated UUIDs, hard sign-out navigation, arithmetic parser, and cascade deletes.
---
Conscious technical decisions and their rationale.
-## `trns.list` / `trns.delta` - Convex pagination
+## PowerSync offline-first (local SQLite as source of truth)
-`convex/trns.ts` uses Convex's built-in `.paginate()` API. The frontend helper `fetchAllPages()` iterates through all pages to collect the full result.
+The app uses PowerSync to replicate Supabase Postgres into a local WASM SQLite database on the client. Stores read exclusively from that local SQLite via `watchTable('SELECT * FROM ...', [], cb)`.
-**Why pagination instead of JSON.stringify:**
-Previously, queries used `JSON.stringify` to bypass the Convex 8,192 array element limit. Pagination is the standard Convex approach - it avoids serialization overhead, provides proper typing, and handles large datasets natively without workarounds.
+**Why local SQLite as the source of truth:**
+This makes the app fully functional without network connectivity. Reads are instant (no round-trip). The single `watchTable` subscription fires immediately with current local rows AND again on every change - whether from a local write or an incoming server sync. This single mechanism replaces the old split between initial load and realtime subscription.
-## Incremental sync (delta)
+**Why PowerSync over a custom offline queue:**
+The previous backend used a hand-written offline queue (`components/offline/replay*`) with XOR-hash deletion detection, local ID remapping, and paginated delta fetching. PowerSync handles all of that automatically: it maintains a local CRUD queue, drains it to Supabase via the connector's `uploadData`, and reconciles server changes via logical replication. No custom queue code, no hash mismatch logic, no ID remapping.
-`initTrns()` uses incremental sync instead of full reload on every open. Details: [Incremental Sync](/en/development/sync).
+**Why IDBBatchAtomicVFS (IndexedDB backend) instead of OPFS:**
+OPFS (Origin Private File System) is faster but requires `SharedArrayBuffer`, which requires COOP/COEP cross-origin isolation headers. Those headers break Google Fonts, Iconify CDN, and other third-party resources. `IDBBatchAtomicVFS` (IndexedDB-backed) needs no cross-origin isolation and works in a standard deployment.
-**Why not Convex reactive queries:**
-Convex supports real-time subscriptions, but they require a constant WebSocket connection and resend the full query result on any change. For 10K+ transactions this is inefficient. Delta sync fetches only changed records.
+## Optimistic writes with rollback
-**Why hash mismatch → fullSync instead of ids query:**
-Previously, deletion detection used a separate `trns.ids` query to fetch all IDs and find deletions. This query was broken at 8,000+ trns (hit the 8,192 array limit). The new approach: after applying delta, compute a local XOR hash and compare with the server hash. On mismatch, fall back to `fullSync()`. Deletions are rare (1-2 per month), so a one-time full sync is an acceptable trade-off - simpler and more reliable than maintaining a paginated IDs query.
+Store methods update `items` immediately (optimistic), then call `upsertRow`/`deleteRow` to write to local SQLite. If the local write fails, the optimistic change is rolled back by restoring a `prev` snapshot, and an error toast is shown.
-**Why not soft-delete:**
-Soft-delete (`deletedAt` field) would require migrating all existing data, modifying all queries to filter deleted records, and periodic cleanup. Hash-based detection is simpler and requires no schema changes.
+**Why optimistic instead of await:**
+Awaiting the SQLite write would block the UI, even though it is a local in-process operation. Optimistic updates give instant feedback. The rollback path handles the rare case where the local write itself fails (e.g., transaction conflict).
-**Why delta sync only for transactions:**
-Categories and wallets are small datasets (tens to hundreds of records). Full sync is fast enough. Transactions are the only entity that grows to thousands of records.
+**Note on server rejection:** server-side errors (Postgres RLS violations, data exceptions) are surfaced separately by the connector's `uploadData` upload-error handler, not the local write catch.
-## Optimistic UI with fire-and-forget mutations
+## `shallowRef` for store items
-Store methods update the UI immediately, then fire Convex mutations without awaiting. The [offline queue](/en/development/offline-queue) captures every operation, so nothing is lost even if the mutation fails.
+All Pinia stores use `shallowRef<Map | null>` instead of `ref` for the items collection. Store methods create new object references on every mutation to trigger reactivity.
-**Why fire-and-forget:**
-Awaiting mutations would block the UI and make the app feel slow. Optimistic updates give instant feedback. The offline queue + replay mechanism ensures eventual consistency.
+**Why:**
+`ref` would deep-track every nested property of potentially thousands of transaction/wallet/category objects. `shallowRef` only tracks the top-level reference. The explicit "create new object" pattern on write is a deliberate trade-off: slightly more verbose stores, significantly lower reactivity overhead.
+
+## Client-generated UUIDs (no `local_` prefix, no remapping)
+
+Every new entity gets a UUID generated on the client (`crypto.randomUUID()` or equivalent) before the local write. That UUID is the permanent ID - there is no temporary `local_` prefix and no remapping after server acknowledgement.
+
+**Why no `local_` IDs:**
+The previous backend used a temporary `local_abc123` prefix, then remapped to a server-assigned ID after the mutation succeeded. This required tracking pending ID remaps across all stores and cascading updates (e.g., trns referencing a newly-created wallet). With PowerSync, the client owns the ID permanently: Supabase schema uses `text` PKs with `default gen_random_uuid()::text`, so whatever UUID the client generates is accepted as-is. No remapping, no cascade complexity.
+
+**Why no FK constraints in Postgres:**
+PowerSync upload order is not guaranteed. A transaction referencing a wallet may be uploaded before the wallet itself. FK constraints would reject valid data. Referential integrity is enforced by app logic instead.
+
+## SQLite views need INSERT/UPDATE, not upsert
-**Why `shallowRef` for store items:**
-All Pinia stores use `shallowRef` instead of `ref` for the items map. This avoids deep reactivity tracking on potentially thousands of objects, significantly improving performance. Store methods create new object references on mutation to trigger reactivity.
+PowerSync client tables are SQLite views backed by INSTEAD OF triggers. They accept plain `INSERT` and `UPDATE` but do NOT support `INSERT ... ON CONFLICT` (upsert syntax).
-## Frontend ID system
+**How `upsertRow` handles this:**
+It performs an existence check, then either `INSERT` (new row) or `UPDATE` (existing row), wrapped in a `writeTransaction` for atomicity. The caller always owns the ID, so INSERT/UPDATE is unambiguous.
-New entities get temporary IDs with `local_` prefix (e.g., `local_a1b2c3`). After successful server creation, the ID is remapped to a Convex ID. Full lifecycle details: [Offline Queue - Frontend ID System](/en/development/offline-queue#frontend-id-system).
+## `reconcileTrns` throttle and change suppression
-**Why `local_` prefix:**
-Explicit prefix makes intent clear in code - `isLocalId(id)` checks `id.startsWith('local_')`. No dependency on Convex ID format internals.
+`useTrnsStore` uses a 120ms throttle window on its `watchTable` (vs. the default 30ms for other tables). It also uses `reconcileTrns` to suppress the "echo" of its own optimistic write.
-**Why not UUID:**
-A short random suffix is sufficient for a single-user app. UUIDs are longer and harder to read in logs.
+**Why the larger throttle:**
+Transactions are the largest table. During initial sync, PowerSync emits many rapid row-change events. The 120ms trailing coalesce folds the burst into a single re-query, reducing CPU.
+
+**Why `reconcileTrns`:**
+After an optimistic write the watch fires again with the same data (the echo of the write). `reconcileTrns` detects that nothing actually changed (comparing by `updatedAt`) and returns the same `prev` ref unchanged, suppressing a redundant reactivity cycle. It also reuses unchanged row objects so `rowToTrn` only runs for the delta.
+
+## Cross-user wipe before connect (fail-closed)
+
+`connectPowerSync` checks a persisted `finapp.psDbOwnerUid` (localStorage). If local SQLite belongs to a different user, it calls `disconnectAndClear()` before connecting - wiping the local database first.
+
+**Why fail-closed:**
+If the wipe itself fails, the owner marker is kept. The next different-user session will still attempt a wipe before reading any data. This prevents user A's data from leaking to user B on a shared device. Accepting a failed wipe and proceeding would be a data privacy bug.
## Hard navigation on sign-out
@@ -67,12 +87,12 @@ The transaction form calculator uses a recursive descent parser (`app/components
**Why:**
`new Function(expression)` is a code injection vector - a malicious string could execute arbitrary JavaScript. It also requires `unsafe-eval` in Content-Security-Policy. The custom parser supports only `+`, `-`, `*`, `/` on numeric literals, rejecting everything else.
-## Cascade deletes in Convex
+## Cascade deletes in stores
-Convex has no foreign key constraints, so cascade deletes are manual - `wallets.remove` and `categories.remove` delete all associated transactions in the same mutation. The frontend sends only the parent entity delete to the [offline queue](/en/development/offline-queue#backend-cascade).
+Postgres has no FK constraints (see above). When `deleteWallet`/`deleteCategory` is called, the store also deletes the entity's transactions from local SQLite (otherwise the watch subscription would re-add them on the next tick). Rollback restores both the entity and its transactions.
-**Why paginated batches (500 items):**
-Convex limits documents written per transaction to 16,000. A wallet with thousands of transactions could exceed this limit in a single mutation. Cascade deletes now paginate: fetch a batch of 500 transaction IDs, delete them, repeat until none remain, then delete the parent entity.
+**Why not rely on server cascade:**
+There is no server-side cascade (no FK constraints). The client must clean up locally so the local SQLite view stays consistent with the intended state.
## Computed children instead of denormalized `childIds`
@@ -83,7 +103,7 @@ Previously, parent categories stored a `childIds` array. This required keeping b
## Category nesting limited to 2 levels
-Categories support only parent → child, not deeper nesting.
+Categories support only parent to child, not deeper nesting.
**Why:**
Deeper nesting complicates the UI (statistics breakdown, category picker, breadcrumbs) without adding practical value for personal finance tracking. Two levels cover 99% of use cases (e.g., Food > Groceries).
@@ -93,21 +113,10 @@ Deeper nesting complicates the UI (statistics breakdown, category picker, breadc
Theme styles use `tagPriority: -2` in `useHead()`, while plugin scripts use `tagPriority: -1`.
**Why:**
-This ensures theme CSS variables are applied before the first paint. The priority chain: `useHead` styles (-2) → plugin scripts (-1) → `@layer theme` (always loses to non-layered). Non-layered CSS in `theme.css` would override `useHead()` by document order, which is why `--ui-radius` and `--ui-primary` must not be set there.
-
-## Convex limits
-
-Reference ([docs](https://docs.convex.dev/production/state/limits)):
-- Function return value: 16 MiB
-- Data read per transaction: 16 MiB
-- Documents scanned per query: 32,000
-- Document size: 1 MiB
-- Array elements per document: 8,192
-- Documents written per transaction: 16,000
-- Query execution time: 1 sec (user code, excluding DB ops)
+This ensures theme CSS variables are applied before the first paint. The priority chain: `useHead` styles (-2) - plugin scripts (-1) - `@layer theme` (always loses to non-layered). Non-layered CSS in `theme.css` would override `useHead()` by document order, which is why `--ui-radius` and `--ui-primary` must not be set there.
## Next Steps
- [Date Utilities](/en/development/date-utilities) - type-safe period handling, interval computation, formatting
-- [Validation Strategy](/en/development/validation-strategy) - dual validation with Zod and Convex
+- [Validation Strategy](/en/development/validation-strategy) - client-only validation with Zod
- [Architecture](/en/development/architecture) - how decisions shape the project structure
diff --git a/docs/content/en/3.reference/06.validation-strategy.md b/docs/content/en/3.reference/06.validation-strategy.md
index 18bba67c..fe5b3eac 100644
--- a/docs/content/en/3.reference/06.validation-strategy.md
+++ b/docs/content/en/3.reference/06.validation-strategy.md
@@ -1,102 +1,60 @@
---
title: Validation Strategy
-description: Dual validation approach and future considerations.
+description: Client-only validation approach and trade-offs.
navigation:
icon: i-lucide-shield-check
seo:
title: Validation Strategy
- description: Finapp uses dual validation - Zod on the client for UX and Convex validators on the server for data integrity. Explains why schemas are kept separate.
+ description: Finapp uses client-only validation with Zod v4. Explains where schemas live, what each one validates, and what the server enforces.
---
-## Current approach: dual validation
+## Current approach: client-only validation
-The project uses two independent validation systems:
+Validation is **client-only**. There are no server-side business-rule validators. The server (Supabase Postgres) enforces only column types, NOT NULL constraints, RLS owner policies, and per-user sync rules.
| Layer | Framework | Purpose |
|-------|-----------|---------|
-| **Client** (browser) | Zod v4 | Form UX - defaults, trimming, instant error feedback |
-| **Server** (Convex) | `convex/values` (`v.*`) | Data integrity - type-safe ID refs, ownership checks |
+| **Client** (browser) | Zod v4 | Form UX - defaults, trimming, instant error feedback; runtime shape checks |
+| **Server** (Supabase Postgres) | Column types + RLS | Column types, NOT NULL, per-user ownership (RLS policy) |
### Where validation lives
-| Entity | Convex validators | Zod schemas |
-|--------|-------------------|-------------|
-| Wallets | `convex/wallets.ts`, `convex/schema.ts` | `app/components/wallets/types.ts` |
-| Categories | `convex/categories.ts`, `convex/schema.ts` | `app/components/categories/types.ts` |
-| Transactions | `convex/trns.ts`, `convex/schema.ts` | `app/components/trns/types.ts` |
-| User Settings | `convex/userSettings.ts` | - (no client schema) |
-| Rates | `convex/rates.ts` | - (no client schema) |
-| Stat config | - | `app/components/stat/useStatConfig.ts` |
-| Date params | - | `app/components/date/useStatDate.ts` |
+| Entity / use | Zod schema |
+|--------------|------------|
+| Transaction form | `app/app/components/trns/types.ts` (`trnItemSchema`, `transactionSchema`) + `app/app/components/trnForm/utils/validate.ts` |
+| Stat config | `app/app/components/stat/useStatConfig.ts` (`ConfigSchema`) |
+| Date / query params | `app/app/components/date/statDateParams.ts` (`queryParamsSchema`) |
+| User settings | `app/app/components/user/types.ts` (`userSettingsSchema`) |
+| Currency rates shape | `app/app/components/currencies/types.ts` (`ratesSchema`) |
+| Locale | `app/app/components/locale/types.ts` (`localeSchema`) |
### What each side validates
-**Zod (client-only):**
-- `.trim().min(1)` on name/icon - prevents empty after trim
+**Zod (client):**
+- `.trim().min(1)` - prevents empty strings after trim
- `.positive()` on amounts
- `.default()` for form initial values
-- `.transform()` for query param parsing (string → number)
+- `.transform()` for query param parsing (string to number / boolean)
+- Discriminated union for transaction type (`trnItemSchema` = `transactionSchema | transferSchema`)
+- Transfer same-wallet check: `incomeWalletId !== expenseWalletId`
-**Convex (server-only):**
-- `v.id('wallets')`, `v.id('categories')` - type-safe ID references
-- Entity ownership (`userId` match)
-- Category circular reference prevention
-- Category name uniqueness per parent
-- Category nesting depth limit (2 levels)
-- Transfer wallet difference check
-- String length limits: name (100), description (500), icon (50), color (50), currency (10)
-- Numeric ranges: amount (max 1 trillion), creditLimit (max 1 billion), date (2000–2099)
-- `categoryId` enforcement: must be `'transfer'` for Transfer type, cannot be `'transfer'` for non-Transfer
+**Supabase Postgres (server):**
+- 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)
+- A trigger auto-creates `user_settings` on signup (no client-side bootstrap needed)
-**Both sides (redundant ~40%):**
-- Field presence / optionality
-- Basic type checks (string, number, boolean)
-- Union / literal validation (TrnType, WalletType enums)
+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.
-### Why constants are duplicated
+### Trade-off
-`TrnType` enum and `walletTypes` array are defined independently on each side:
-- `convex/validators.ts` - for server (imports `v` from `convex/values`)
-- `app/components/trns/types.ts` / `app/components/wallets/types.ts` - for client
+A determined client that bypasses the form can write arbitrary data to local SQLite, which PowerSync will upload to Supabase. Postgres will accept it as long as it passes column types and RLS. This is an accepted trade-off for a single-user personal finance app - the overhead of duplicating every business rule as Postgres constraints or Row-Level-Security policies was not justified.
-Importing from `convex/` directory into browser code pulls in server-only modules (`_generated/server`, auth) and triggers "Convex functions should not be imported in the browser" warning. See [tech-decisions](/en/development/tech-decisions) for details.
-
-## Evaluated alternatives
-
-### fluent-convex + shared Zod schemas
-
-[fluent-convex](https://github.com/mikecann/fluent-convex) (v0.x) provides a fluent API for Convex functions with a Zod plugin that auto-converts Zod schemas to Convex validators.
-
-**Would enable:** single Zod schema used on both client and server.
-
-**Rejected because:**
-- Library is experimental (v0.x, single author, 90 stars)
-- `v.id('wallets')` has no Zod equivalent - loses type-safe ID references
-- `schema.ts` (table definitions) must stay on `v.*` regardless
-- Extra dependency: `convex-helpers` as peer dep
-
-### Shared Zod schemas with manual convex-helpers conversion
-
-Define Zod schemas in a `shared/` directory. Client uses them directly. Server converts via `convex-helpers/server/zod`.
-
-**Would enable:** single source of truth without fluent-convex dependency.
-
-**Rejected because:**
-- Same `v.id()` limitation
-- Requires configuring Convex tsconfig to import from outside `convex/`
-- Boilerplate for manual Zod → Convex conversion
-- Marginal benefit for 3 stable entities with ~15 fields each
-
-## Decision
-
-Keep dual validation. The duplication is small (~15 fields × 3 entities), schemas change rarely, and each side serves a distinct purpose:
-- **Zod** = UX (defaults, transforms, instant feedback)
-- **Convex** = integrity (ID refs, ownership, business rules)
-
-### When to reconsider
-
-- `convex-helpers/server/zod` gaining native `v.id()` support
-- fluent-convex reaching v1.0 with stable API
+If stricter enforcement is needed in the future, the options are:
+- Postgres `CHECK` constraints for ranges and lengths
+- Supabase Edge Function as an upload proxy with server-side Zod validation
+- Re-evaluating whether Supabase's built-in validation (pg_jsonschema, check constraints) covers the critical rules
## Next Steps
diff --git a/docs/content/en/3.reference/07.convex-migration.md b/docs/content/en/3.reference/07.convex-migration.md
index 195edb3a..a039010d 100644
--- a/docs/content/en/3.reference/07.convex-migration.md
+++ b/docs/content/en/3.reference/07.convex-migration.md
@@ -1,18 +1,25 @@
---
title: Convex Migration
-description: What changed between v6 (Firebase) and v7 (Convex).
+description: What changed between v6 (Firebase) and v7 (Convex). Convex was later replaced by Supabase + PowerSync.
navigation:
icon: i-lucide-hamburger
seo:
title: Convex Migration - What Changed
- description: Side-by-side comparison of Finapp v6 (Firebase) and v7 (Convex) - backend, performance, security, tests, and architecture.
+ description: Side-by-side comparison of Finapp v6 (Firebase) and v7 (Convex) - backend, performance, security, tests, and architecture. Historical reference.
---
-Side-by-side comparison of what the app looks like on the [`firebase`](https://github.com/ilkome/finapp/tree/firebase) branch (v6, Firebase) vs `main` (v7, Convex).
+> **Three eras.** Finapp has gone through three backend generations:
+> - **v6** - Firebase Realtime Database + Firebase Auth
+> - **v7** - Convex (backend-as-code) + Better Auth (described in this document)
+> - **current** - Supabase Postgres + PowerSync (offline-first) + Supabase Auth
+>
+> This document is the historical side-by-side comparison of the Firebase-to-Convex migration. The app-level improvements (performance, refactoring, UX, TypeScript, i18n) described here are still valid and present in the current codebase. The backend, auth, offline queue, and dependency sections reflect the v7 Convex state; see [Architecture](/en/development/architecture) for the current Supabase + PowerSync architecture.
+
+Side-by-side comparison of what the app looks like on the [`firebase`](https://github.com/ilkome/finapp/tree/firebase) branch (v6, Firebase) vs the Convex era (v7).
## Backend
-| | firebase (Firebase) | main (Convex) |
+| | firebase (Firebase) | v7 (Convex) |
|---|---|---|
| **Database** | Firebase Realtime Database | Convex (backend-as-code) |
| **Auth** | Firebase Auth via `nuxt-vuefire` | Better Auth + `@convex-dev/better-auth` |
@@ -22,27 +29,27 @@ Side-by-side comparison of what the app looks like on the [`firebase`](https://g
| **Exchange rates** | Client-side fetch | Server cron (daily at 6:00 UTC) + `rates` table |
| **User settings** | localStorage only | Convex `userSettings` table (baseCurrency, locale) with offline queue |
| **Schema indexes** | N/A | Composite indexes: `by_user_date`, `by_user_wallet`, `by_user_category` for efficient queries |
-| **Migration** | N/A | `utils/migrate/firebase.js` &mdash; CLI to import Firebase JSON exports into Convex |
-| **Account deletion** | N/A | `deleteUserDataFull()` &mdash; paginated wipe of app + auth tables |
+| **Migration** | N/A | `utils/migrate/firebase.js` - CLI to import Firebase JSON exports into Convex |
+| **Account deletion** | N/A | `deleteUserDataFull()` - paginated wipe of app + auth tables |
-### What Convex gives
+### What Convex gave
-- **Typed mutations** &mdash; full TypeScript on both sides, auto-generated API types
-- **Server-side validation** &mdash; string length limits, numeric ranges, field non-emptiness, business rules (see [Validation Strategy](/en/development/validation-strategy))
+- **Typed mutations** - full TypeScript on both sides, auto-generated API types
+- **Server-side validation** - string length limits, numeric ranges, field non-emptiness, business rules
- **Single WebSocket** for all data operations (queries, mutations, auth)
- **Pagination** via `.paginate()` API for large datasets (transactions)
-- **Delta sync** &mdash; only changed records fetched after initial load (see [Sync](/en/development/sync))
+- **Delta sync** - only changed records fetched after initial load
## Store Pattern
-| | firebase | main |
+| | firebase | v7 (Convex) |
|---|---|---|
-| **Data source** | Firebase listener &rarr; `setTrns()` | Convex query &rarr; `mergeOfflineOps()` &rarr; `set()` |
+| **Data source** | Firebase listener -> `setTrns()` | Convex query -> `mergeOfflineOps()` -> `set()` |
| **Persist** | `deepUnref()` + immediate `localforage.setItem()` | Debounced 300ms `localforage.setItem()` (no deep clone) |
| **Offline ops** | Manual helpers in `trns/helpers.ts`, ad-hoc localStorage keys | Explicit queue: `pushSaveOp()`, `pushDeleteOp()`, `replay()` |
-| **ID system** | Firebase push IDs | `local_` prefix &rarr; remapped to Convex ID after mutation |
-| **Optimistic UI** | Partial (fire-and-forget) | Full: update UI &rarr; push op &rarr; fire mutation &rarr; remap ID on success |
-| **Sync verification** | None | XOR hash (`fnv1a`) of transaction IDs; client &harr; server hash comparison on every sync |
+| **ID system** | Firebase push IDs | `local_` prefix -> remapped to Convex ID after mutation |
+| **Optimistic UI** | Partial (fire-and-forget) | Full: update UI -> push op -> fire mutation -> remap ID on success |
+| **Sync verification** | None | XOR hash (`fnv1a`) of transaction IDs; client vs server hash comparison on every sync |
The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep cloning on every persist was unnecessary.
@@ -50,9 +57,9 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
### Algorithm improvements
-| What | firebase | main | Impact |
+| What | firebase | v7 (Convex) | Impact |
|------|----------|------|--------|
-| **Wallet totals** | `getWalletTotal(id)` called per wallet in `reduce` &mdash; each call filters all trns: O(W&times;N) | `getWalletsTotals()` single pass, distributes amounts via `Map`: O(N), then O(1) lookup per wallet | 5 wallets &times; 10K trns: ~50K &rarr; ~10K ops |
+| **Wallet totals** | `getWalletTotal(id)` called per wallet in `reduce` - each call filters all trns: O(W&times;N) | `getWalletsTotals()` single pass, distributes amounts via `Map`: O(N), then O(1) lookup per wallet | 5 wallets &times; 10K trns: ~50K &rarr; ~10K ops |
| **Interval bucketing** | Inline in `Item.vue`: `intervalsInRange.reduce()` filtering all trns per interval: O(N&times;I) | Extracted to `bucketTrnsByIntervals()`: single pass + binary search: O(N&nbsp;log&nbsp;I) | Year/365 days/5K trns: 1.8M &rarr; ~43K comparisons |
| **Transaction filtering** | 6 sequential `.filter()` chained via `reduce` + `walletsIds.some(w => includes(w))` O(W&sup2;) + always sorts O(N&nbsp;log&nbsp;N) | Single `.filter()` with early returns + `Set.has()` O(1) + sorting optional | 5 intermediate arrays + O(W&sup2;) &rarr; single pass + O(1); sort O(N&nbsp;log&nbsp;N) skipped when not needed |
| **Wallet lookup in getTotal** | `walletsIds.includes()`: O(W) per transfer | `new Set(walletsIds).has()`: O(1) per transfer | Linear &rarr; constant per lookup |
@@ -60,7 +67,7 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
| **Category statistics** | `categoriesStat` eagerly computes both `grouped` and `ungrouped` on every change; `filter().at(0)` for biggest | Lazy `computed()` per variant, only accessed one executes; `.find()` stops at first match | Up to 2&times; fewer `computeCategoriesWithData` calls |
| **Vertical categories filter** | `verticalCategories.filter(c => c.value !== 0)` called twice in template (title + v-for): re-evaluated on every render | Cached in `visibleVerticalCategories` computed: filtered once, reused | 2 filter passes &rarr; 1 cached |
| **Number formatting** | `currency.js` library + `currencies.find()` O(N) called twice per format | Native `Intl.NumberFormat` cached in `Map` + `currencyMap.get()` O(1) | No library overhead; formatter created once per precision |
-| **Last created trn** | `Object.keys().sort().find()` &mdash; sorts all trns O(N&nbsp;log&nbsp;N) then searches | Single O(N) pass tracking running max date | 10K trns: ~130K ops &rarr; ~10K ops |
+| **Last created trn** | `Object.keys().sort().find()` - sorts all trns O(N&nbsp;log&nbsp;N) then searches | Single O(N) pass tracking running max date | 10K trns: ~130K ops &rarr; ~10K ops |
| **Category parent check** | `categoriesForBeParent` calls `Object.values(trns).some()` O(N) per root category: O(M&times;N) | Pre-built `usedCategoryIds` Set via `for...in` O(N) + `Set.has()` O(1) per check; no intermediate arrays | 200 categories &times; 10K trns: ~2M &rarr; ~10K ops |
| **Recent categories** | `Object.keys(trns).filter().sort()` O(N&nbsp;log&nbsp;N) + `acc.some(c => c.id)` O(K&sup2;) dedup + `includes()` O(W) per category | Single O(N) pass via `Map` tracking latest date + `entries().toSorted()` O(K&nbsp;log&nbsp;K) + `Set.has()` O(1) | 10K trns: ~130K + K&sup2; &rarr; ~10K + K&nbsp;log&nbsp;K ops |
| **Transactible categories** | `.reduce()` with `acc.includes()` O(M) + `childIds.filter(!acc.includes)` O(C&times;M): O(M&sup2;) | `Map<parentId, childIds[]>` built in O(M) + `Set` dedup O(1) per check | 200 categories: ~40K &rarr; ~200 ops |
@@ -70,9 +77,9 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
| **Group totals cache** | `getTotalOfTrnsIds()` called twice per group in template (income + expense): O(2G) calls | Pre-computed `groupTotals` Map + `paginatedTotal` computed: O(G) compute + O(1) lookups | 15 groups: ~30 &rarr; ~15 total computations per render |
| **Category grouping sort** | `categories.sort()` called inside `reduce` on every child push: O(K&sup2;&nbsp;log&nbsp;K) per parent | Sort once after grouping loop, only if `length > 1`: O(K&nbsp;log&nbsp;K) per parent | 5 children: ~50 &rarr; ~12 comparisons |
| **Category grouping totals** | `getTotalOfTrnsIds(cat.trnsIds).sum` called twice per child (for push value + parent sum) | Computed once into `catTotal`, reused: single call per child | 2&times; fewer `getTotal` calls per child category |
-| **Data sync** | Firebase full replacement on every update: O(N) | Delta sync: only changed records fetched &mdash; O(D) where D &laquo; N | Avoids reprocessing unchanged transactions |
+| **Data sync** | Firebase full replacement on every update: O(N) | Delta sync: only changed records fetched - O(D) where D &laquo; N | Avoids reprocessing unchanged transactions |
| **Interval generation** | `list.unshift(current)` in while loop: O(n) per call, O(n&sup2;) total | `list.push(current)` + `list.reverse()`: O(1) per call, O(n) total | Year/365 days: ~66K shifts &rarr; ~365 pushes + 1 reverse |
-| **Date duration keys** | Dynamic `{ [\`${period}s\`]: value }` &mdash; TS sees `Record<string, number>`, no type check against `Duration` | `toDuration(period, value)` returns typed `Duration` via exhaustive switch | Compile-time safety; new period variants cause errors, not silent fallback |
+| **Date duration keys** | Dynamic `{ [\`${period}s\`]: value }` - TS sees `Record<string, number>`, no type check against `Duration` | `toDuration(period, value)` returns typed `Duration` via exhaustive switch | Compile-time safety; new period variants cause errors, not silent fallback |
| **Date formatting** | Each format function called twice (`type: 'start'` + `type: 'end'`), concatenated; 3 IIFE switch blocks for period comparison | Each format function returns full string; `isSamePeriod(a, b, period)` replaces all 3 switches | ~40% fewer lines in `useGetDateRange`; no double calls |
| **Average computation** | `sum !== 0` checked 3 times + `Object.keys(items).length > 0` guard | Early `sum === 0` exit; `day` average always present (range &ge; 2 guaranteed) | Single check instead of 4 |
| **Favorite categories sort** | Inline sort duplicating parent-name + name logic (8 lines) | Reuses `compareCategoriesByParentAndName` utility (1 line) | DRY; single sort implementation to maintain |
@@ -84,11 +91,11 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
### Bundle and rendering
-| What | firebase | main |
+| What | firebase | v7 (Convex) |
|------|----------|------|
| **ECharts** | 9 components in main bundle (incl. PieChart, DataZoom, MarkPoint) | 7 components in lazy-loaded async chunk (unused removed) |
| **Theme plugin** | 81 lines with SSR inline scripts and regex replacements | 32 lines, SPA-only `appConfig` updates from localStorage |
-| **Persist** | `deepUnref()` on every `localforage.setItem()` &mdash; full recursive clone | Direct write, debounced 300ms, no cloning |
+| **Persist** | `deepUnref()` on every `localforage.setItem()` - full recursive clone | Direct write, debounced 300ms, no cloning |
| **Responsive layout** | `useWindowSize()` JS listener for sidebar | Pure CSS `sm:` / `md:` Tailwind breakpoints |
| **Container queries** | Media queries only | CSS container queries (`@xl/page:`, `@md/page:`) for layout-aware sizing |
| **Dependencies** | `currency.js` for number formatting | Native `Intl.NumberFormat` (no dependency) |
@@ -97,23 +104,25 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
## Security
-| What | firebase | main |
+| What | firebase | v7 (Convex) |
|------|----------|------|
-| **Calculator parser** | `new Function(expression)` &mdash; code injection risk, requires `unsafe-eval` CSP | Recursive descent parser &mdash; only `+`,`-`,`*`,`/` on numeric literals |
+| **Calculator parser** | `new Function(expression)` - code injection risk, requires `unsafe-eval` CSP | Recursive descent parser - only `+`,`-`,`*`,`/` on numeric literals |
| **Input validation** | Firebase rules (client can't verify) | Convex validators: string limits, numeric ranges, field checks |
| **Auth tokens** | Firebase-managed | Encrypted at rest (`encryptOAuthTokens: true`) |
| **Session lifetime** | Firebase default | 30 days, daily refresh |
| **Cascade deletes** | N/A (Firebase) | Paginated batches of 500 (Convex 16K write limit) |
| **Data integrity** | None enforced in code | Transfer &harr; `categoryId='transfer'`, type change normalization, name uniqueness |
-| **Redirect safety** | No validation | `getSafeRedirectPath()` &mdash; only relative paths starting with `/` (not `//`) |
+| **Redirect safety** | No validation | `getSafeRedirectPath()` - only relative paths starting with `/` (not `//`) |
## Auth
-| | firebase | main |
+_(Historical - describes the v7 Convex era. Current auth: Supabase Auth, email/password only. See [Architecture](/en/development/architecture).)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Provider** | Firebase Auth | Better Auth |
-| **Plugin** | `nuxt-vuefire` (auto-handles auth) | `plugins/convex.ts` &mdash; manual lifecycle |
-| **Token flow** | Firebase SDK internal | `setAuth(fetchToken)` &rarr; `authClient.convex.token()` &rarr; `authReadyPromise` |
+| **Plugin** | `nuxt-vuefire` (auto-handles auth) | `plugins/convex.ts` - manual lifecycle |
+| **Token flow** | Firebase SDK internal | `setAuth(fetchToken)` -> `authClient.convex.token()` -> `authReadyPromise` |
| **Offline** | Firebase SDK handles reconnect | Session watch ignores `error`/`isPending`, skips token fetch when offline, `online` event triggers fresh auth |
| **Auth state hint** | None | `finapp.localAuthUid` cookie (sync check, no network) |
| **Callback** | Firebase redirect | OTT flow + `ensureConvexAuth()` before SPA navigation |
@@ -122,47 +131,51 @@ The `vue-deepunref` dependency is removed. Store data uses `shallowRef`, so deep
## Offline Queue
-| | firebase | main |
+_(Historical - describes the v7 Convex era. Current offline: PowerSync handles sync automatically. See [Architecture](/en/development/architecture).)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Structure** | Ad-hoc helpers in `trns/helpers.ts` | Dedicated `components/offline/` directory |
| **Files** | Scattered localStorage keys | `helpers.ts`, `replay.ts`, `replayHelpers.ts`, `storageKeys.ts`, `types.ts` |
-| **Operations** | `saveTrnToAddLaterLocal()`, `removeTrnToDeleteLaterLocal()` | `pushSaveOp()`, `pushDeleteOp()` &rarr; generic for any entity |
+| **Operations** | `saveTrnToAddLaterLocal()`, `removeTrnToDeleteLaterLocal()` | `pushSaveOp()`, `pushDeleteOp()` -> generic for any entity |
| **Entity types** | String literals (`'wallets'`, `'trns'`) | `OfflineEntityType` const object for type-safe entity references |
| **Replay** | Manual on next load | `replayOfflineQueue()` with conflict detection, ID remapping |
-| **Per-entity replay** | N/A | `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps` &mdash; extracted testable functions |
-| **Op validation** | None | `validateOpData()` with Zod schemas &mdash; corrupted ops logged and removed |
+| **Per-entity replay** | N/A | `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps` - extracted testable functions |
+| **Op validation** | None | `validateOpData()` with Zod schemas - corrupted ops logged and removed |
| **Merge** | None | `mergeOfflineOps(serverData, entity)` applies pending ops on top of fresh server data |
## PWA
-| | firebase | main |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Strategy** | `injectManifest` (custom service worker via `SW` env var) | `generateSW` (auto-generated by Workbox) |
-| **Service worker** | Hand-written `sw.ts` | None &mdash; Workbox generates it |
+| **Service worker** | Hand-written `sw.ts` | None - Workbox generates it |
| **Precaching** | Manual configuration | Automatic for all build assets |
| **Icons** | Fetched from Iconify API at runtime | Bundled at build time via `clientBundle` |
## TypeScript
-| | firebase | main |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Strict mode** | Enabled, but unresolved errors | Zero TypeScript errors |
-| **Type casts** | `as any` used across codebase | Zero `as any` &mdash; replaced with type guards, `@vue-ignore`, narrow casts |
+| **Type casts** | `as any` used across codebase | Zero `as any` - replaced with type guards, `@vue-ignore`, narrow casts |
| **Transfer detection** | `transferCategoriesIds` computed array | `TrnType.Transfer` enum + discriminated union types |
| **Runtime validation** | None | Zod schemas for user settings, rates, stat config, date params |
-| **Date period functions** | `getStartOf(date, string)`, `getEndOf(date, string)` &mdash; `default` fallback to day | Typed as `Period`, exhaustive `switch` with `case 'day'` &mdash; new variants cause compile errors |
-| **Duration construction** | Dynamic `{ [\`${period}s\`]: value }` &mdash; TS sees `Record<string, number>` | `toDuration(period, value): Duration` &mdash; typed return via exhaustive switch |
-| **Stat type mapping** | `Record<string, TrnType[]>` with `??` fallback | `Record<SeriesSlugSelected \| StatTabSlug, TrnType[]>` &mdash; all keys covered, no fallback needed |
-| **Average key resolution** | `key as keyof TotalReturns` unsafe cast + `as number` | Typed `key: keyof TotalReturns` via explicit `'netIncome'` &rarr; `'sum'` mapping, no casts |
-| **Currency rate fallback** | `rates[code] \|\| 1`, `wallet?.currency \|\| 'USD'` &mdash; falsy `0`/`''` triggers fallback | `rates[code] ?? 1`, `wallet?.currency ?? 'USD'` &mdash; only `null`/`undefined` triggers fallback |
-| **Query param parsing** | `if (data.rangeOffset)` &mdash; falsy `0` skipped | `if (data.x !== undefined)` &mdash; zero values applied correctly |
-| **Total props** | `baseCurrencyCode?: string` loose type | `baseCurrencyCode?: CurrencyCode` &mdash; consistent with `getAmountInRate` |
-| **Category stat params** | `trnsItems: Record<TrnId, { categoryId?: string }>` inline type | `trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>>` &mdash; linked to source type |
-| **Sort null guard** | `sortCategoriesByAmount` checks `if (!a \|\| !b)` at runtime | Guard removed &mdash; TS already guarantees `CategoryWithData` parameters; explicit `: number` return type |
+| **Date period functions** | `getStartOf(date, string)`, `getEndOf(date, string)` - `default` fallback to day | Typed as `Period`, exhaustive `switch` with `case 'day'` - new variants cause compile errors |
+| **Duration construction** | Dynamic `{ [\`${period}s\`]: value }` - TS sees `Record<string, number>` | `toDuration(period, value): Duration` - typed return via exhaustive switch |
+| **Stat type mapping** | `Record<string, TrnType[]>` with `??` fallback | `Record<SeriesSlugSelected \| StatTabSlug, TrnType[]>` - all keys covered, no fallback needed |
+| **Average key resolution** | `key as keyof TotalReturns` unsafe cast + `as number` | Typed `key: keyof TotalReturns` via explicit `'netIncome'` -> `'sum'` mapping, no casts |
+| **Currency rate fallback** | `rates[code] \|\| 1`, `wallet?.currency \|\| 'USD'` - falsy `0`/`''` triggers fallback | `rates[code] ?? 1`, `wallet?.currency ?? 'USD'` - only `null`/`undefined` triggers fallback |
+| **Query param parsing** | `if (data.rangeOffset)` - falsy `0` skipped | `if (data.x !== undefined)` - zero values applied correctly |
+| **Total props** | `baseCurrencyCode?: string` loose type | `baseCurrencyCode?: CurrencyCode` - consistent with `getAmountInRate` |
+| **Category stat params** | `trnsItems: Record<TrnId, { categoryId?: string }>` inline type | `trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>>` - linked to source type |
+| **Sort null guard** | `sortCategoriesByAmount` checks `if (!a \|\| !b)` at runtime | Guard removed - TS already guarantees `CategoryWithData` parameters; explicit `: number` return type |
## Tests
-| | firebase | main |
+_(The v7 Convex test infrastructure had a dedicated `convex` vitest project running in edge-runtime. Current tests run in `unit` (node) and `store` (happy-dom) projects against PowerSync/Supabase mocks.)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Config** | No vitest config | 3 vitest projects: `unit` (node), `store` (happy-dom), `convex` (edge-runtime) |
| **Backend tests** | None | Full CRUD integration tests (wallets, categories, trns, sync hash) |
@@ -180,7 +193,7 @@ Business logic moved from Vue components into testable pure functions:
- **Wallets:** `filterWalletsByCurrency`, `filterWalletsByViewType`, `groupWalletsByProperty`, `computeWalletCounts`, `sumWalletAmounts`, `getCreditAvailable`
- **Categories:** `collectCategoriesByTrns`, `flattenCategoriesWithValues`, `groupCategoriesWithValues`
- **Offline:** `remapTrnIds`, `isTrnOrphaned`, `groupOpsByEntity`, `splitCategoryOps`, `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps`, `validateOpData`
-- **Demo:** simplified to read-only &mdash; removed per-entity CRUD methods (`addDemoCategory`, `deleteDemoWallet`, etc.), only `generateDemoData()` + `isDemo`
+- **Demo:** simplified to read-only - removed per-entity CRUD methods (`addDemoCategory`, `deleteDemoWallet`, etc.), only `generateDemoData()` + `isDemo`
### Component changes
@@ -190,25 +203,25 @@ Business logic moved from Vue components into testable pure functions:
### Component patterns
-- **Class merging:** `getStyles()` utility removed &mdash; replaced with `cn()` (clsx + tailwind-merge)
-- **Form inputs:** `value`/`updateValue` props &rarr; `v-model` / `defineModel`
+- **Class merging:** `getStyles()` utility removed - replaced with `cn()` (clsx + tailwind-merge)
+- **Form inputs:** `value`/`updateValue` props -> `v-model` / `defineModel`
### Composable decomposition
- **Wallets:** `useWalletContextMenu`, `useWalletDelete`, `useWalletsFilter`, `useWalletsGrouping`, `useWalletsCounts`
- **Categories:** `useCategoryContextMenu`
- **Statistics:** Symbol-based injection keys (`filterKey`, `statDateKey`, `statConfigKey`) for type-safe `provide`/`inject`
-- **Stat pages:** `useStatPage` composable &mdash; extracts duplicated stat infrastructure (filter, statConfig, statDate creation + provide, activeTab, storageKey, trnsIds, maxRange) from three page components (Dashboard, Category, Wallet) into a single reusable composable. Each page passes only its entity-specific filter logic via `getTrnsFilter` callback. Script section reduced by 24&ndash;53% across the three pages
+- **Stat pages:** `useStatPage` composable - extracts duplicated stat infrastructure (filter, statConfig, statDate creation + provide, activeTab, storageKey, trnsIds, maxRange) from three page components (Dashboard, Category, Wallet) into a single reusable composable. Each page passes only its entity-specific filter logic via `getTrnsFilter` callback. Script section reduced by 24&ndash;53% across the three pages
- **`useCategoryLongPress` composable:** extracted 59 lines of duplicated long-press logic from `Round2lines.vue`, `Line.vue`, and `Vertical.vue` into a shared composable. Handles long-press to create transactions from categories with proper date selection from chart intervals
- **`useStatDate` encapsulation:** navigation computed properties (`shouldShowNav`, `isAtEnd`, `isAtStart`, `isDayToday`, `shouldShowNavHome`) and direct `params.value` mutations moved from `Navigation.vue` and `chart/Wrap.vue` into `useStatDate` methods (`selectInterval()`, `resetInterval()`, `setIntervalsBy()`, `navigate()`). Navigation.vue reduced from ~54 lines of script to 5 lines
-- **Duplicate `stat/date/Nav.vue` removed:** identical copy of `date/Nav.vue` was deleted &mdash; only the canonical `DateNav` component remains
+- **Duplicate `stat/date/Nav.vue` removed:** identical copy of `date/Nav.vue` was deleted - only the canonical `DateNav` component remains
- **`UiNumberStepper` component:** extracted duplicated &plusmn;/input counter pattern from `ConfigModal.vue` into a reusable UI primitive with `v-model`, `min`, `max` props
- **Stat component self-containment:** `StatAverage` consolidated three conditional `Amount` blocks into one via computed props; `StatSumWrap` and `StatChartWrap` removed redundant prop-drilling in favor of inject; `StatItem` merged two modal blocks into one via state-machine pattern
- **Config caching:** `Section2.vue` and `Line.vue` cache `statConfig.config.value.catsList.*` reads into computed properties (`isItemsBg`, `isLines`, `isRoundIcon`, `isListGrouped`, etc.) for template readability
- **`Range.vue` simplified:** replaced manual `intervalsInRange` indexing with `statDate.selectedInterval`; extracted `isIntervalSelected` computed
-- **`useStatItem` cleanup:** extracted `baseTrnsIdsForSelection` computed to eliminate duplicated interval-selection logic; fixed unsafe `type.value as keyof TotalReturns` cast with `type.value ?? 'sum'` fallback; fixed chart average denominator using wrong data source (`intervalsData` &rarr; `intervalsDataWithFilteredCategories`)
-- **`useCategoriesExpanded` composable:** extracted 52-line expand/collapse logic from `DetailedSection.vue` (286&rarr;234 lines)
-- **Stat component rename:** `Section`/`Section2` &rarr; `RoundSection`/`DetailedSection` for clarity
+- **`useStatItem` cleanup:** extracted `baseTrnsIdsForSelection` computed to eliminate duplicated interval-selection logic; fixed unsafe `type.value as keyof TotalReturns` cast with `type.value ?? 'sum'` fallback; fixed chart average denominator using wrong data source (`intervalsData` -> `intervalsDataWithFilteredCategories`)
+- **`useCategoriesExpanded` composable:** extracted 52-line expand/collapse logic from `DetailedSection.vue` (286->234 lines)
+- **Stat component rename:** `Section`/`Section2` -> `RoundSection`/`DetailedSection` for clarity
- **`barUtils` extraction:** `computeBarStyle()` and `formatCompactAmount()` extracted from inline template logic into testable utilities
- **Wallet statistics consistency:** archived wallets fully excluded from all counts (total, type sums, withdrawal, available) via early `continue`; `available.isShow` requires both withdrawal and credit wallets; auto-reset filter to Total when currency switch produces empty results
- **Store sync consolidation:** `showErrorToast`/`showSuccessToast`/`showWarningToast` merged into generic `showToast(type, key, params?)`
@@ -216,7 +229,7 @@ Business logic moved from Vue components into testable pure functions:
### Semantic renaming
-| firebase | main |
+| firebase | v7 (Convex) |
|----------|------|
| `getTrnsIds` | `filterTrnsIds` |
| `getCategoriesWithData` | `computeCategoriesWithData` |
@@ -241,7 +254,7 @@ Business logic moved from Vue components into testable pure functions:
### Data model
-| | firebase | main |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Category children** | Denormalized `childIds` array | Computed dynamically from `parentId` |
| **Transfer detection** | `transferCategoriesIds` (computed from category data) | `TrnType.Transfer` enum value |
@@ -250,10 +263,10 @@ Business logic moved from Vue components into testable pure functions:
## UX Improvements
- **Haptic feedback** on transaction submit (mobile vibration)
-- **Accessibility:** `<div>` &rarr; `<button>` in interactive components, i18n `aria-label` on icon-only buttons
+- **Accessibility:** `<div>` -> `<button>` in interactive components, i18n `aria-label` on icon-only buttons
- **Calculator:** fixed infinite loop on zero result, proper `0.` decimal display, rounded division results
- **Form:** amount clears immediately after submit, popover closes before edit navigation
-- **Onboarding:** `Welcome` component replaced with `Onboarding` &mdash; improved layout, cookie-persisted state (`finapp.isOnboarded`)
+- **Onboarding:** `Welcome` component replaced with `Onboarding` - improved layout, cookie-persisted state (`finapp.isOnboarded`)
- **Currencies page:** two sections (Used / All) with global search, O(1) lookup via `currencyMap`
- **Wallet/category detail:** edit/delete actions moved to three-dot menu
- **Wallet statistics:** archived wallets fully excluded from all filter tabs; Available tab only shown when both withdrawal and credit wallets exist; filter auto-resets to Total on currency switch if current filter is empty
@@ -265,7 +278,7 @@ Business logic moved from Vue components into testable pure functions:
## i18n
-| | firebase | main |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Error messages** | Generic or none | Per-entity error keys (`categories.errors.*`, `wallets.errors.*`, `trns.errors.*`) |
| **Form labels** | Verbose (`Category name`, `Category color`) | Concise (`Name`, `Color`, `Icon`) |
@@ -292,31 +305,33 @@ Business logic moved from Vue components into testable pure functions:
- Emit during render in `SelectionCategoriesFast`
- Magic numbers replaced with `TrnType` enum (8 places)
- `ref<any>` replaced with proper types (4 files)
-- Error layout localized (hardcoded English &rarr; i18n keys)
-- Tailwind v4 CSS syntax: `[var(--name)]` &rarr; `(--name)` functional notation
+- Error layout localized (hardcoded English -> i18n keys)
+- Tailwind v4 CSS syntax: `[var(--name)]` -> `(--name)` functional notation
- Radius uses `??` (not `||`) so `0` is valid: `radius ?? 0.375`
-- CSS utility typo: `bottomSheetDrugClassesCustom` &rarr; `bottomSheetDragClassesCustom`
+- CSS utility typo: `bottomSheetDrugClassesCustom` -> `bottomSheetDragClassesCustom`
- ESLint: Convex-specific rules for `convex/`, layout `vue/no-multiple-template-root`
-- `createLogger(prefix)` &mdash; dev-only `log`, always-on `warn` and `error`, with `[prefix]` formatting across all modules
-- Hardcoded `'ru'` locale in chart formatters &rarr; dynamic locale from settings
+- `createLogger(prefix)` - dev-only `log`, always-on `warn` and `error`, with `[prefix]` formatting across all modules
+- Hardcoded `'ru'` locale in chart formatters -> dynamic locale from settings
- `Statistics.vue` empty group sections hidden with `v-show`
-- `Selector.vue` `onSelectRange(value: any)` &rarr; typed `{ end: unknown, start: unknown }`
+- `Selector.vue` `onSelectRange(value: any)` -> typed `{ end: unknown, start: unknown }`
- `setWalletViewType` type fixed from `WalletType | 'total'` to `WalletViewTypes | 'total'`
-- Version: v6.6.4 &rarr; v7.0.0-beta.10
+- Version: v6.6.4 -> v7.0.0-beta.10
- `useAmount.getAmountInBaseRate`: dead `noFormat` param removed, unnecessary `+` unary on number removed
-- `useFilter`: redundant `[...array.filter()]` and `[...string.split()]` spreads removed &mdash; both methods already return new arrays
-- `getUCalendarTimedDate`: `new Date(string)` parsed as UTC &rarr; `date.toDate(getLocalTimeZone())` for correct local timezone
-- `useGetDateRange`: `type: 'start' | 'end'` pattern removed &mdash; format functions return full strings directly, 3 IIFE switches replaced with `isSamePeriod` helper
-- `getIntervalsInRange`: `rangeOffset` made optional in `IntervalsInRangeProps` &mdash; not used by `getIntervalsInRange`, only by `calculateIntervalInRange`
-- `compareCategoriesByParentAndName`: `||` &rarr; `??` for empty string fallback (consistent nullish semantics)
-- `useCategoriesStore`: removed 5 unnecessary `?? {}` defensive checks &mdash; `items` is always initialized via `shallowRef`
+- `useFilter`: redundant `[...array.filter()]` and `[...string.split()]` spreads removed - both methods already return new arrays
+- `getUCalendarTimedDate`: `new Date(string)` parsed as UTC -> `date.toDate(getLocalTimeZone())` for correct local timezone
+- `useGetDateRange`: `type: 'start' | 'end'` pattern removed - format functions return full strings directly, 3 IIFE switches replaced with `isSamePeriod` helper
+- `getIntervalsInRange`: `rangeOffset` made optional in `IntervalsInRangeProps` - not used by `getIntervalsInRange`, only by `calculateIntervalInRange`
+- `compareCategoriesByParentAndName`: `||` -> `??` for empty string fallback (consistent nullish semantics)
+- `useCategoriesStore`: removed 5 unnecessary `?? {}` defensive checks - `items` is always initialized via `shallowRef`
- `useCategoryLongPress`: removed redundant `!` after optional chaining (`value?.start` already narrowed)
-- `useCategoriesExpanded`: `forEach` &rarr; `for...of`; `reduce` with `as` cast &rarr; `Object.fromEntries`
-- `sortCategoriesByAmount`: renamed `isP`/`isN` &rarr; `bothPositive`/`bothNegative` for readability; removed redundant `categories ??= []` (already initialized in grouping)
+- `useCategoriesExpanded`: `forEach` -> `for...of`; `reduce` with `as` cast -> `Object.fromEntries`
+- `sortCategoriesByAmount`: renamed `isP`/`isN` -> `bothPositive`/`bothNegative` for readability; removed redundant `categories ??= []` (already initialized in grouping)
### Dependencies
-| Removed | Added |
+_(Historical - describes what changed from firebase to v7 Convex. For current dependencies see the project `package.json`.)_
+
+| Removed (firebase era) | Added (Convex era) |
|---------|-------|
| `firebase` | `convex` |
| `nuxt-vuefire` | `@convex-dev/better-auth` |
@@ -326,3 +341,5 @@ Business logic moved from Vue components into testable pure functions:
| | `@vueuse/nuxt` |
| | `zod` |
| | `es-toolkit` |
+
+The Convex era deps (`convex`, `@convex-dev/better-auth`, `better-auth`, `convex-helpers`, `convex-test`) were subsequently removed when the backend migrated to Supabase + PowerSync. `@powersync/web` and `@supabase/supabase-js` were added. `zod`, `es-toolkit`, and `@vueuse/nuxt` remain.
diff --git a/docs/content/en/3.reference/08.loans-optimization.md b/docs/content/en/3.reference/08.loans-optimization.md
index 9006378b..6ba2fd98 100644
--- a/docs/content/en/3.reference/08.loans-optimization.md
+++ b/docs/content/en/3.reference/08.loans-optimization.md
@@ -1,20 +1,18 @@
---
title: Loans Optimization
-description: Future optimization plans for the loans feature.
+description: Historical document - Convex-era optimization plan for a loans feature that no longer exists.
navigation:
icon: i-lucide-timer
seo:
- title: Loans Optimization
- description: Future optimization plans for the loans feature in Finapp.
+ title: Loans Optimization (Historical)
+ description: Historical Convex-era optimization plan for the loans feature in Finapp. The described convex/loans.ts no longer exists in the current Supabase + PowerSync app.
---
-Future optimization plans for the loans feature.
+> **Historical document.** This page describes a planned optimization for `convex/loans.ts`, a file that existed in the Convex era of Finapp. The Convex backend has been replaced by Supabase Postgres + PowerSync. There is no loans table or feature in the current app - `convex/loans.ts` does not exist. The algorithmic discussion below is kept as a historical reference only.
-## markOverduePayments Cron Optimization
+## markOverduePayments Cron Optimization (Convex era)
-**Problem:** The daily cron `markOverduePayments` in `convex/loans.ts` scans ALL loans across ALL users with `ctx.db.query('loans').collect()`, then for each active loan queries all its payments. This is O(L*P) where L = total loans, P = average payments per loan.
-
-**Current state:** Works fine for small user counts (< 100 users). No functional issue.
+**Problem:** The daily cron `markOverduePayments` in `convex/loans.ts` scanned ALL loans across ALL users with `ctx.db.query('loans').collect()`, then for each active loan queried all its payments. This is O(L*P) where L = total loans, P = average payments per loan.
**When to optimize:** When the total number of active loans exceeds ~1000.
@@ -35,13 +33,9 @@ ctx.db
3. Batch-patch all matching payments to `'overdue'`
4. This reduces complexity from O(L*P) to O(overdue) - only touching payments that actually need updating
-**Schema change required:**
+**Schema change required (Convex era, no longer applicable):**
```ts
// In convex/schema.ts, add to loanPayments:
.index('by_status_date', ['status', 'date'])
```
-
-::callout{type="info"}
-Russian docs at `../docs/content/ru/3.technical/` should be updated separately when this optimization is implemented.
-::
diff --git a/docs/content/en/4.premium/03.ai-chat.md b/docs/content/en/4.premium/03.ai-chat.md
index eb2f9d13..3f493cf7 100644
--- a/docs/content/en/4.premium/03.ai-chat.md
+++ b/docs/content/en/4.premium/03.ai-chat.md
@@ -14,24 +14,24 @@ Finapp ships a local AI assistant powered by [Ollama](https://ollama.com) and [@
## Entry points
-- **FAB button** (`AiFab.vue`) — floating action button on all authenticated pages
+- **FAB button** (`AiFab.vue`) - floating action button on all authenticated pages
- **Keyboard shortcut** `Cmd/Ctrl+I` (see `shortcuts.ts`)
-- **Slide-over panel** — right side, `sm:max-w-md`
+- **Slide-over panel** - right side, `sm:max-w-md`
## Architecture
```
User input → AiChatPanel
├── useAiChat.send(text)
- │ ├── pruneContext(messages) — sliding window + tool result compression
+ │ ├── pruneContext(messages) - sliding window + tool result compression
│ ├── chat() via @tanstack/ai with Ollama adapter
│ ├── streams TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END / TEXT_MESSAGE_CONTENT
- │ ├── autoRetry — detects failed mutations + incomplete chains
- │ ├── client-side fallback — directly executes mutations if model stalls
- │ ├── toast notifications — visual feedback for mutations
- │ └── lastAction tracker — enables undo
- ├── AiToolCallsList.vue — renders rich cards per tool
- └── AiMessageContent.vue — markdown assistant text
+ │ ├── autoRetry - detects failed mutations + incomplete chains
+ │ ├── client-side fallback - directly executes mutations if model stalls
+ │ ├── toast notifications - visual feedback for mutations
+ │ └── lastAction tracker - enables undo
+ ├── AiToolCallsList.vue - renders rich cards per tool
+ └── AiMessageContent.vue - markdown assistant text
```
## Tool catalog
@@ -39,16 +39,16 @@ User input → AiChatPanel
All tools live in `app/components/ai/tools/` and are registered via `createAllTools()`.
### Transactions
-- `create_trn` — new expense or income
-- `create_adjustment` — set wallet balance to target value (delta is computed)
-- `create_transfer` — transfer between wallets (supports currency exchange)
-- `update_trn` — patch fields on existing transaction by id
-- `delete_trn` — delete by id
-- `duplicate_trn` — clone a transaction with current date
-- `bulk_delete_trns` — delete many by filter (safety cap via `maxDelete`)
-- `list_trns` — filter + aggregate
-- `search_trns` — full-text search in descriptions
-- `undo_last_action` — reverse last AI mutation
+- `create_trn` - new expense or income
+- `create_adjustment` - set wallet balance to target value (delta is computed)
+- `create_transfer` - transfer between wallets (supports currency exchange)
+- `update_trn` - patch fields on existing transaction by id
+- `delete_trn` - delete by id
+- `duplicate_trn` - clone a transaction with current date
+- `bulk_delete_trns` - delete many by filter (safety cap via `maxDelete`)
+- `list_trns` - filter + aggregate
+- `search_trns` - full-text search in descriptions
+- `undo_last_action` - reverse last AI mutation
### Wallets
- `create_wallet`, `update_wallet`, `delete_wallet`, `list_wallets`
@@ -60,13 +60,13 @@ All tools live in `app/components/ai/tools/` and are registered via `createAllTo
- `create_category`, `update_category`, `delete_category`, `list_categories`
### Analytics
-- `get_summary` — totals, income/expense, top N categories
-- `get_wallet_stats` — single-wallet income/expense/net
-- `compare_periods` — current vs previous period, delta and %
+- `get_summary` - totals, income/expense, top N categories
+- `get_wallet_stats` - single-wallet income/expense/net
+- `compare_periods` - current vs previous period, delta and %
### Settings
- `set_base_currency`, `set_locale`, `get_settings`
-- `set_theme` — primary/neutral color, border radius, black-as-primary
+- `set_theme` - primary/neutral color, border radius, black-as-primary
## System prompt
@@ -77,14 +77,14 @@ Built in `useSystemPrompt.ts`. Key rules:
- **Chain pattern:** `delete_trn` / `update_trn` / `duplicate_trn` require `list_trns` first to get a real id
- **FORBIDDEN:** inventing ids, asking user for ids, reusing past tool results
- **Mutations:** rules 12a-12i cover transfer, adjustment, settings, wallet management, ordering, undo
-- **DATE RULE:** omit `date` unless user explicitly said one — tools default to now
+- **DATE RULE:** omit `date` unless user explicitly said one - tools default to now
## Context pruning
`pruneContext.ts` implements a sliding window + tool result compression:
-- `maxContextTurns` (default 6) — only the last N user+assistant pairs go to the model
-- `compressToolsAfterTurns` (default 1) — older assistant messages keep tool_calls compressed to `[tool_name: summary]` strings
+- `maxContextTurns` (default 6) - only the last N user+assistant pairs go to the model
+- `compressToolsAfterTurns` (default 1) - older assistant messages keep tool_calls compressed to `[tool_name: summary]` strings
This prevents model "I already did X" hallucinations that appear in long sessions.
@@ -92,12 +92,12 @@ This prevents model "I already did X" hallucinations that appear in long session
`useAiChat.ts` implements two layers of robustness:
-1. **autoRetry** — if tool call failed (validation error or `ok: false`), send a retry hint with the real id from `list_trns`
-2. **executeFallback** — if model still stalls after retry on `duplicate_trn` / `delete_trn` / `undo_last_action`, the client directly executes the mutation and injects the result as a synthetic tool_call. This bypasses model reliability issues.
+1. **autoRetry** - if tool call failed (validation error or `ok: false`), send a retry hint with the real id from `list_trns`
+2. **executeFallback** - if model still stalls after retry on `duplicate_trn` / `delete_trn` / `undo_last_action`, the client directly executes the mutation and injects the result as a synthetic tool_call. This bypasses model reliability issues.
## Idle clear
-`idleMinutesBeforeClear` (default 30) — if the chat was idle for N minutes since last message, history is silently cleared on next `send()`. Prevents context pollution across sessions.
+`idleMinutesBeforeClear` (default 30) - if the chat was idle for N minutes since last message, history is silently cleared on next `send()`. Prevents context pollution across sessions.
## Model recommendations
@@ -121,11 +121,11 @@ Accessible via the settings popover in the chat header.
## Known limitations
- **Multi-turn `create_trn` is model-dependent.** On `gemma4:latest` end-to-end follow-up collection (e.g. user says "купил кофе", assistant asks for amount/wallet, assistant calls `create_trn` after answers) succeeds in roughly 70% of attempts. The model sometimes mis-maps the answer to the wrong parameter (e.g. puts "наличными" into `description` instead of `wallet`) or omits `type`. For reliable multi-turn, prefer `qwen3:8b` or provide all fields in one message.
-- **Chain tools (`duplicate_trn`, `delete_trn`, `update_trn`) can stall on `gemma4:latest` in long sessions** — the model sometimes replies in text asking for an id instead of chaining `list_trns` → mutation. This is mitigated by client-side fallback (`executeFallback` in `useAiChat.ts`) which directly executes the mutation and injects the result as a synthetic tool_call.
+- **Chain tools (`duplicate_trn`, `delete_trn`, `update_trn`) can stall on `gemma4:latest` in long sessions** - the model sometimes replies in text asking for an id instead of chaining `list_trns` → mutation. This is mitigated by client-side fallback (`executeFallback` in `useAiChat.ts`) which directly executes the mutation and injects the result as a synthetic tool_call.
- **"I already did that" hallucinations** can still appear if `maxContextTurns` is set too high. The default `compressToolsAfterTurns: 1` compresses old tool results to prevent this, but raising the window beyond 8-10 turns brings the risk back.
-- **Local network dependency.** If Ollama is not running at `baseUrl`, the chat is unusable. There is no remote fallback by design — all inference stays local.
+- **Local network dependency.** If Ollama is not running at `baseUrl`, the chat is unusable. There is no remote fallback by design - all inference stays local.
- **Validation errors from `@tanstack/ai`** are reported as `state: 'done'` (not `error`) with `{ error: "..." }` in the result. `autoRetry` handles this via the `isTcFailed` helper that inspects the result JSON.
-- **No bulk reorder of categories** — `useCategoriesStore` does not expose a `saveCategoriesOrder` helper, so the AI cannot reorder categories.
+- **No bulk reorder of categories** - `useCategoriesStore` does not expose a `saveCategoriesOrder` helper, so the AI cannot reorder categories.
## Adding a new tool
diff --git a/docs/content/en/index.md b/docs/content/en/index.md
index 5ad6c7b8..4e02f01a 100644
--- a/docs/content/en/index.md
+++ b/docs/content/en/index.md
@@ -11,7 +11,7 @@ Your money, your control
#description
Open-source personal finance app built with Vue and Nuxt.
-Track expenses, manage wallets, and analyze your spending — anywhere, anytime.
+Track expenses, manage wallets, and analyze your spending - anywhere, anytime.
#links
:::u-button
diff --git a/docs/content/ru/1.guide/01.introduction.md b/docs/content/ru/1.guide/01.introduction.md
index cc39aa97..904848b9 100644
--- a/docs/content/ru/1.guide/01.introduction.md
+++ b/docs/content/ru/1.guide/01.introduction.md
@@ -113,8 +113,9 @@ name: dashboard
- [Nuxt 4](https://nuxt.com) - мета-фреймворк для Vue
- [Nuxt UI](https://ui.nuxt.com) - библиотека компонентов
- [Tailwind CSS](https://tailwindcss.com) - утилитарные стили
-- [Convex](https://convex.dev) - бэкенд и база данных реального времени
-- [Better Auth](https://better-auth.com) - аутентификация
+- [Supabase](https://supabase.com) (Postgres) - бэкенд база данных
+- [PowerSync](https://www.powersync.com) - синхронизация offline-first
+- [Supabase Auth](https://supabase.com/docs/guides/auth) - аутентификация (email/пароль)
## Следующие шаги
diff --git a/docs/content/ru/2.development/01.installation.md b/docs/content/ru/2.development/01.installation.md
index 08c1dc96..11160049 100644
--- a/docs/content/ru/2.development/01.installation.md
+++ b/docs/content/ru/2.development/01.installation.md
@@ -1,17 +1,19 @@
---
title: Установка
-description: Начало работы с Финапкой.
+description: Начало работы с Финапкой - клонирование, настройка переменных окружения, запуск локального бэкенда и dev-сервера.
navigation:
icon: i-lucide-download
seo:
title: Установка
- description: Как установить и запустить Финапку локально.
+ description: Как установить и запустить Финапку локально с Supabase и PowerSync.
---
## Требования
-- [Node.js](https://nodejs.org) v24.12.0+
+- [Node.js](https://nodejs.org) v24.12.0 или выше
- [pnpm](https://pnpm.io) >= 10.28.2
+- [Supabase CLI](https://supabase.com/docs/guides/cli) (для локального Supabase)
+- [Docker](https://docs.docker.com/get-docker/) (для Supabase и PowerSync)
## Установка
@@ -29,78 +31,55 @@ cd finapp
pnpm install
```
-### Запустите dev-сервер
+### Настройте переменные окружения
-Два терминала — фронтенд и бэкенд:
+Скопируйте пример env-файла и заполните значения:
-```bash [Терминал 1 — Фронтенд]
-pnpm dev
+```bash [Terminal]
+cp app/.env.example app/.env
```
-```bash [Терминал 2 — Бэкенд]
-pnpm dev:convex
+```bash [app/.env]
+VITE_SUPABASE_URL=http://localhost:54321
+VITE_SUPABASE_ANON_KEY=<anon key из вывода supabase start>
+VITE_POWERSYNC_URL=http://localhost:8080
```
-Приложение доступно на [http://localhost:3050](http://localhost:3050).
-
-Playground дизайн-системы доступен на [http://localhost:3050/dev](http://localhost:3050/dev) в режиме разработки (скрыт в продакшене).
-::
-
-## Файлы окружения
-
-- `.env` — значения dev-деплоймента, читается Nuxt (по умолчанию `--dotenv`)
-- `.env.local` — создаётся автоматически `convex dev`, используется Convex CLI (в gitignore)
-- `.env.prod` — значения prod-деплоймента, используется `pnpm dev:prod`
+При локальной разработке `supabase start` выводит `API URL` (использовать как `VITE_SUPABASE_URL`) и `anon key` (использовать как `VITE_SUPABASE_ANON_KEY`). `VITE_POWERSYNC_URL` - это сервис PowerSync, запускаемый на следующем шаге.
-Все `.env*` файлы в gitignore, кроме `.env.example`.
+### Запустите локальный бэкенд
-## Настройка бэкенда
+Выполните три команды из директории `app/`. После первоначальной настройки достаточно просто запускать контейнеры при необходимости.
-Бэкенд — [Convex](https://convex.dev).
+**1. Запустите Supabase (Postgres + Auth на порту 54321):**
-1. Создайте проект на [convex.dev](https://convex.dev)
-2. Скопируйте `.env.example` в `.env`:
-
-```bash [.env]
-CONVEX_DEPLOYMENT=your_deployment
-VITE_CONVEX_URL=your_convex_url
-VITE_CONVEX_SITE_URL=your_convex_site_url
+```bash [Terminal - из app/]
+supabase start
```
-### Переменные Nuxt
-
-| Переменная | Описание |
-|------------|----------|
-| `CONVEX_DEPLOYMENT` | Идентификатор деплоймента для Convex CLI |
-| `VITE_CONVEX_URL` | URL деплоймента Convex (фронтенд Nuxt) |
-| `VITE_CONVEX_SITE_URL` | Site URL Convex (авторизация Nuxt) |
+**2. Примените настройки репликации PowerSync:**
-### Переменные Convex backend
+```bash [Terminal - из app/]
+docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersync_setup.sql
+```
-Устанавливаются через `npx convex env set`:
+Эта команда создаёт роль `powersync_role` с правами репликации и публикацию `powersync` для пяти таблиц Финапки.
-| Переменная | Описание |
-|------------|----------|
-| `BETTER_AUTH_SECRET` | Секретный ключ Better Auth (обязателен — без него все auth-эндпоинты, включая CORS preflight, будут падать) |
-| `APP_URL` | URL приложения для кросс-доменной авторизации и CORS/trustedOrigins |
-| `GOOGLE_CLIENT_ID` | Google OAuth client ID |
-| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret |
-| `OPENEXCHANGERATES_APP_ID` | API-ключ курсов валют |
+**3. Запустите сервис PowerSync (порт 8080):**
-### Первичная настройка Convex
+```bash [Terminal - из app/]
+docker compose -f powersync/docker-compose.yaml up -d
+```
-При подключении к новому dev-деплойменту Convex настройте его окружение:
+### Запустите dev-сервер
```bash [Terminal]
-npx convex env set BETTER_AUTH_SECRET <значение>
-npx convex env set APP_URL http://localhost:3050
-npx convex env set GOOGLE_CLIENT_ID <значение>
-npx convex env set GOOGLE_CLIENT_SECRET <значение>
-npx convex env set OPENEXCHANGERATES_APP_ID <значение>
+pnpm dev
```
-::callout{icon="i-lucide-alert-triangle" color="warning"}
-`BETTER_AUTH_SECRET` обязателен — без него все auth-эндпоинты (включая CORS preflight) будут падать с ошибкой `BetterAuthError`.
+Приложение доступно на [http://localhost:3050](http://localhost:3050).
+
+Playground дизайн-системы доступен на [http://localhost:3050/dev](http://localhost:3050/dev) в режиме разработки (скрыт в продакшене).
::
## Сборка
diff --git a/docs/content/ru/2.development/02.understand-anything.md b/docs/content/ru/2.development/02.understand-anything.md
index 091bddba..7a6a7c12 100644
--- a/docs/content/ru/2.development/02.understand-anything.md
+++ b/docs/content/ru/2.development/02.understand-anything.md
@@ -108,8 +108,8 @@ cd dist && vercel deploy --prod --yes
|------|----------|
| **Entry** | Точки входа приложения и Nuxt конфиг |
| **Config** | Конфиги сборки, ESLint, TypeScript |
-| **Backend** | Convex схема, мутации, запросы, HTTP обработчики |
-| **Auth** | Конфигурация Better Auth и middleware |
+| **Backend** | Схема Supabase Postgres + RLS + правила синхронизации PowerSync (`app/supabase/`, `app/powersync/`) |
+| **Auth** | Supabase Auth (email/пароль); двухуровневая защита маршрутов |
| **Store** | Pinia сторы (categories, wallets, trns, rates, settings) |
| **Composables** | Vue composables и утилиты |
| **Components** | Vue компоненты, сгруппированные по фичам |
diff --git a/docs/content/ru/2.development/03.offline.md b/docs/content/ru/2.development/03.offline.md
index 7d7c7163..a9a0b735 100644
--- a/docs/content/ru/2.development/03.offline.md
+++ b/docs/content/ru/2.development/03.offline.md
@@ -5,37 +5,37 @@ navigation:
icon: i-lucide-wifi-off
seo:
title: Офлайн и PWA
- description: Как Финапка работает офлайн как прогрессивное веб-приложение.
+ description: Как Финапка работает офлайн как прогрессивное веб-приложение на основе локальной синхронизации PowerSync.
---
## Установка PWA
-- **Десктоп** — значок установки в адресной строке
-- **Мобильные** — «Добавить на главный экран» из меню браузера
+Финапка - прогрессивное веб-приложение (PWA). Его можно установить на устройство для нативного опыта:
+
+- **Десктоп** - значок установки в адресной строке
+- **Мобильные** - «Добавить на главный экран» из меню браузера
Приложение открывается в автономном режиме (standalone) без интерфейса браузера.
## Офлайн
-Все данные хранятся локально. Транзакции, кошельки и категории можно создавать, редактировать и удалять без интернета.
+Финапка работает по принципу offline-first. Все данные лежат в локальной базе SQLite в браузере (на основе PowerSync, хранится в IndexedDB). Транзакции, кошельки и категории можно создавать, редактировать и удалять без интернета - чтение и запись всегда идут сначала в локальную базу, поэтому интерфейс не ждёт сети.
-### Очередь операций
+### Как синхронизируется запись
-Изменения офлайн записываются в локальную очередь:
+Любая запись сразу попадает в локальную SQLite и фиксируется во встроенной очереди отправки PowerSync. Пока вы офлайн, очередь просто ждёт.
-- Тип сущности (транзакция, кошелёк, категория)
-- Тип операции (создание, обновление, удаление)
-- Данные и временная метка
+При восстановлении связи PowerSync автоматически и по порядку отправляет очередь на сервер (Supabase). Здесь нет ручной очереди и нет временных клиентских ID, которые нужно переотображать - каждая строка несёт сгенерированный на клиенте UUID, одинаковый и на устройстве, и на сервере.
-Очередь оптимизируется — создание и последующее обновление одного элемента объединяются в одну операцию.
+Если сервер навсегда отклоняет запись (например нарушение row-level security или ограничения), это изменение отбрасывается, чтобы не блокировать очередь, и приложение показывает тост об ошибке синхронизации - чтобы вы знали, что локальная копия теперь опережает сервер.
-### Синхронизация при восстановлении связи
+### Как чтение остаётся актуальным
-Очередь обрабатывается автоматически. Операции отправляются на сервер по порядку, локальные ID заменяются серверными.
+Приложение подписано на локальную базу. Любое изменение - от вашей записи или от входящей синхронизации с другого устройства - перезапускает нужные запросы и обновляет интерфейс. Одна и та же подписка отвечает и за первичную загрузку, и за живые обновления, поэтому второе устройство видит ваши изменения вскоре после их синхронизации.
## Стратегия синхронизации
-- **Транзакции** — дельта-синхронизация. Загружаются только изменения с момента последней синхронизации по временной метке.
-- **Кошельки и категории** — полная синхронизация. Коллекции небольшие, загружаются целиком.
+PowerSync реплицирует строки каждого пользователя инкрементально: после первой полной синхронизации передаются только изменения (вставки, обновления и удаления) для таблиц, на которые вы подписаны. Курсы валют - общий поток только для чтения, доступный всем пользователям. Стратегию не нужно выбирать под тип данных - она инкрементальна для всего.
-Локальный кеш — `localforage`.
+Единственное исключение - демо-режим: у него нет бэкенда, и он сохраняет данные в `localforage`, чтобы перезагрузка работала без входа.
+</content>
diff --git a/docs/content/ru/2.development/04.migration.md b/docs/content/ru/2.development/04.migration.md
index b0d02b31..527b4dd7 100644
--- a/docs/content/ru/2.development/04.migration.md
+++ b/docs/content/ru/2.development/04.migration.md
@@ -1,20 +1,22 @@
---
-title: Миграция с Firebase
-description: Как перенести данные из Finapp v6 (Firebase) в Finapp v7 (Convex).
+title: История миграций данных
+description: Исторический обзор миграций бэкенда Финапки - Firebase -> Convex (v6 -> v7) и Convex -> Supabase+PowerSync.
navigation:
icon: i-lucide-database
seo:
- title: Миграция с Firebase
- description: Пошаговое руководство по миграции данных из Firebase Realtime Database в Convex.
+ title: История миграций данных
+ description: Историческая справка о миграциях бэкенда Финапки - из Firebase Realtime Database через Convex к Supabase Postgres с PowerSync.
---
-Finapp v6 использовал Firebase Realtime Database. Finapp v7 использует [Convex](https://convex.dev). Это руководство описывает миграцию данных пользователей.
+Финапка прошла через два крупных изменения бэкенда. На этой странице они описаны как исторический контекст.
-## Обзор
+## Firebase -> Convex (v6 -> v7)
-Скрипт миграции читает JSON-экспорт из Firebase, трансформирует данные под схему Convex и импортирует через внутренние мутации.
+В Финапке v6 использовалась Firebase Realtime Database. Финапка v7 заменила её на Convex (backend-as-code, WebSocket-синхронизация).
-### Что меняется
+Исходный код v6 хранится на ветке [`firebase`](https://github.com/ilkome/finapp/tree/firebase).
+
+### Что изменилось
| Сущность | Firebase (v6) | Convex (v7) |
|----------|---------------|-------------|
@@ -24,84 +26,24 @@ Finapp v6 использовал Firebase Realtime Database. Finapp v7 испо
| Настройки | `settings.lang` (`en`, `ru`) | `userSettings.locale` (`en`, `ru`) |
| Иконки | Формат `mdi mdi-xxx` | Формат `mdi:xxx` |
-## Требования
-
-- Задеплоенный Convex бекенд (dev и prod)
-- Созданный аккаунт пользователя на целевом деплойменте (нужно войти хотя бы раз, чтобы получить userId)
-- JSON-экспорт из Firebase
-
-## Экспорт данных из Firebase
-
-Экспортируйте данные из [Firebase Console](https://console.firebase.google.com):
-
-1. Откройте проект в Firebase
-2. Перейдите в Realtime Database
-3. Нажмите меню (три точки) на корневом узле пользователя
-4. Выберите "Export JSON"
-5. Сохраните файл как `data.json` в `utils/migrate/`
-
-Файл должен иметь такую структуру:
-
-```json [data.json]
-{
- "accounts": { ... },
- "categories": { ... },
- "settings": { "baseCurrency": "USD", "lang": "en" },
- "trns": { ... }
-}
-```
-
-## Найдите Convex userId
-
-Нужен Convex userId пользователя на каждом деплойменте. Найти его можно в [Convex Dashboard](https://dashboard.convex.dev) в таблице `users`.
-
-## Запуск миграции
-
-Скрипт удаляет существующие данные пользователя перед импортом.
-
-::callout{icon="i-lucide-alert-triangle" color="warning"}
-Скрипт удалит все существующие данные для указанного userId перед импортом. Убедитесь, что userId правильный.
-::
-
-```bash [Dev]
-node utils/migrate/firebase.js <userId>
-```
-
-```bash [Prod]
-node utils/migrate/firebase.js <userId> --prod
-```
-
-Скрипт выполнит:
+### Инструменты миграции (исторически - больше нет в репозитории)
-1. Удаление существующих данных для userId
-2. Импорт кошельков (из `accounts`) с возвратом маппинга ID
-3. Импорт категорий с исправлением иконок и ремаппингом parent/child
-4. Импорт транзакций батчами по 200, с ремаппингом всех ссылок на кошельки и категории
-5. Импорт настроек пользователя
+Миграция была разовой операцией. Скрипты, которые её выполняли (`utils/migrate/firebase.js`, `convex/migrate.ts`), удалены из репозитория как неактуальные. Запускать их не нужно.
-## Трансформации данных
+Скрипты читали JSON-экспорт из Firebase, трансформировали данные под схему Convex (ремаппинг ID, исправление формата иконок, нормализация настроек) и импортировали через внутренние мутации Convex батчами по 200.
-Скрипт применяет следующие трансформации при импорте:
+## Convex -> Supabase+PowerSync (текущий бэкенд)
-### Кошельки
-- Ключ `accounts` переименован в `wallets`
-- Отсутствующие поля получают значения по умолчанию: `isArchived: false`, `isExcludeInTotal: false`, `isWithdrawal: false`, `order: 0`
+Финапка v7+ (Convex) была мигрирована на **Supabase Postgres + PowerSync** (offline-first синхронизация) с **Supabase Auth (email/password)**.
-### Категории
-- Иконки: `mdi mdi-xxx` → `mdi:xxx`, пустые → `mdi:category-outline`
-- `parentId` перемаплен со старых строковых ID на новые Convex ID (`childIds` больше не хранится — вычисляется из `parentId`)
-- Отсутствующие поля получают значения по умолчанию: `showInLastUsed: false`, `showInQuickSelector: false`
+Это была разовая операция во время разработки, не повторяющийся пользовательский процесс:
-### Транзакции
-- `walletId`, `categoryId`, `expenseWalletId`, `incomeWalletId` перемаплены на новые Convex ID
-- Специальные значения `categoryId` сохранены как есть: `transfer`, `adjustment`
+1. Экспорт всех данных из деплоймента Convex командой `convex export --prod`.
+2. Трансформация экспорта Python-скриптом, который сохранял значения `_id` из Convex как `text`-идентификаторы в Postgres (конвертация UUID не требовалась - id остались стабильными) и переопределял значения `userId` на соответствующие Supabase Auth uid.
+3. Импорт через `psql` в экземпляр Supabase Postgres.
-### Настройки
-- `settings.lang` → `userSettings.locale` (значения остаются теми же: `en`, `ru`)
+В схеме Postgres нет FK-ограничений, поэтому порядок импорта не имеет значения. RLS-политики и правила синхронизации PowerSync обеспечивают изоляцию данных по пользователям.
-## Файлы
+## Текущий бэкенд
-| Файл | Описание |
-|------|----------|
-| `utils/migrate/firebase.js` | Node.js скрипт: читает JSON, трансформирует данные, вызывает мутации Convex |
-| `convex/migrate.ts` | Внутренние мутации Convex: `deleteUserData`, `insertWallets`, `insertCategories`, `insertTrnsBatch`, `insertUserSettings` |
+Текущий бэкенд - **Supabase Postgres + PowerSync**. Полное описание - в разделе [Архитектура](/ru/reference/architecture), настройка локальной среды - в разделе [Установка](/ru/development/installation).
diff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.md
index dbcb48be..4f3722c0 100644
--- a/docs/content/ru/2.development/05.deployment.md
+++ b/docs/content/ru/2.development/05.deployment.md
@@ -1,21 +1,21 @@
---
title: Деплой
-description: Деплой Finapp и документации на Vercel из монорепы.
+description: Деплой Finapp и документации на Vercel из монорепы с Supabase и PowerSync в качестве бэкенда.
navigation:
icon: i-lucide-rocket
seo:
title: Деплой
- description: Как задеплоить приложение и документацию Finapp на Vercel.
+ description: Как задеплоить приложение и документацию Finapp на Vercel с Supabase Postgres и PowerSync.
---
-Finapp — это монорепа на pnpm workspaces. Приложение и документация деплоятся из одного репозитория как два отдельных проекта в Vercel.
+Finapp - это монорепа на pnpm workspaces. Приложение и документация деплоятся из одного репозитория как два отдельных проекта в Vercel.
## Настройка Vercel
Создайте **два проекта** в Vercel, оба указывают на один GitHub-репозиторий.
::callout{icon="i-lucide-info" color="info"}
-**Где что настраивать: файл vs проект.** Большинство build-настроек живут в `vercel.json` каждого проекта (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory нельзя положить в `vercel.json`**, потому что Vercel должен знать его заранее, чтобы понять где искать файл. Ставится один раз в dashboard (Settings → General → Root Directory) или через API:
+**Где что настраивать: файл vs проект.** Большинство build-настроек живут в `vercel.json` каждого проекта (`framework`, `buildCommand`, `installCommand`, `outputDirectory`, `ignoreCommand`, `env`, `rewrites`). **Root Directory нельзя положить в `vercel.json`**, потому что Vercel должен знать его заранее, чтобы понять где искать файл. Ставится один раз в dashboard (Settings -> General -> Root Directory) или через API:
```bash
TOKEN=$(jq -r .token "$HOME/Library/Application Support/com.vercel.cli/auth.json")
@@ -37,12 +37,13 @@ curl -X PATCH \
| Output Directory | `.output/public` |
| Install Command | `pnpm install` |
-Добавьте переменные окружения:
+Добавьте переменные окружения, указывающие на ваш хостируемый проект Supabase и сервис PowerSync:
| Переменная | Значение |
|------------|----------|
-| `VITE_CONVEX_URL` | URL вашего Convex-деплоймента |
-| `VITE_CONVEX_SITE_URL` | Site URL вашего Convex-деплоймента |
+| `VITE_SUPABASE_URL` | URL вашего проекта Supabase |
+| `VITE_SUPABASE_ANON_KEY` | Публичный (anon) ключ Supabase |
+| `VITE_POWERSYNC_URL` | URL вашего сервиса PowerSync |
### Проект документации
@@ -55,7 +56,7 @@ curl -X PATCH \
## Ignored Build Step
-Чтобы избежать лишних билдов, настройте **Ignored Build Step** в каждом проекте Vercel (Settings → Git → Ignored Build Step):
+Чтобы избежать лишних билдов, настройте **Ignored Build Step** в каждом проекте Vercel (Settings -> Git -> Ignored Build Step):
::code-group
```bash [App]
@@ -69,6 +70,15 @@ git diff --quiet HEAD^ HEAD -- docs
Так приложение не будет передеплоиваться при изменениях только в документации, и наоборот.
+## Бэкенд: Supabase + PowerSync
+
+Nuxt SPA статически хостится на Vercel. Бэкенд-сервисы отдельные:
+
+- **Supabase** - хостируемый проект Supabase (облачный или self-hosted) предоставляет Postgres, Auth и путь записи через PostgREST/supabase-js.
+- **PowerSync** - сервис PowerSync (self-hosted через Docker или хостируемый вариант) обеспечивает offline-first синхронизацию, реплицируя данные из Supabase Postgres через логическую репликацию.
+
+Установите три `VITE_*` переменные в Vercel, указывающие на продакшен-проект Supabase и экземпляр PowerSync. Описание переменных - в разделе [Установка](/ru/development/installation#переменные-окружения).
+
## Premium (Finapp Premium)
Finapp Premium живёт в отдельном репозитории ([finapp-premium](https://github.com/ilkome/finapp-premium)) и расширяет базовое приложение как **Nuxt layer**.
@@ -83,13 +93,13 @@ Finapp Premium живёт в отдельном репозитории ([finapp-
| Output Directory | `.output/public` |
| Install Command | `pnpm install` |
-На Vercel не нужно задавать `FINAPP_BASE_PATH`. Путь по умолчанию — `./base/app`, то есть checked-out базовый субмодуль.
+На Vercel не нужно задавать `FINAPP_BASE_PATH`. Путь по умолчанию - `./base/app`, то есть checked-out базовый субмодуль.
### Как это работает
- `nuxt.config.ts` использует переменную `FINAPP_BASE_PATH` для определения пути к базовому слою
-- По умолчанию (CI/Vercel): `./base/app` — поддиректория `app/` внутри Git-субмодуля `base`
-- `base/` — Git-субмодуль, указывающий на ветку `convex` репозитория `ilkome/finapp`
+- По умолчанию (CI/Vercel): `./base/app` - поддиректория `app/` внутри Git-субмодуля `base`
+- `base/` - Git-субмодуль, указывающий на ветку `main` репозитория `ilkome/finapp`
- `npx nuxt prepare base/app` генерирует `base/app/.nuxt/tsconfig.json`, который нужен Vite для резолва TypeScript config из submodule layer
- Локально: установите `FINAPP_BASE_PATH=../mono/app` в `.env` для работы с локальной монорепой и hot reload
@@ -107,10 +117,10 @@ FINAPP_BASE_PATH=../mono/app
### Git-субмодуль
-Субмодуль должен указывать на ветку `convex` репозитория `ilkome/finapp`:
+Субмодуль должен указывать на ветку `main` репозитория `ilkome/finapp`:
```bash [Terminal]
-git submodule add -b convex https://github.com/ilkome/finapp.git base
+git submodule add -b main https://github.com/ilkome/finapp.git base
```
После свежего клонирования:
@@ -118,15 +128,3 @@ git submodule add -b convex https://github.com/ilkome/finapp.git base
```bash [Terminal]
git submodule update --init
```
-
-## Бэкенд Convex
-
-Convex деплоится отдельно от Vercel. Используйте дашборд Convex или CLI:
-
-```bash [Terminal]
-npx convex deploy
-```
-
-::callout{icon="i-lucide-info" color="info"}
-Убедитесь, что все необходимые переменные окружения установлены в продакшен-деплойменте Convex. Полный список — в разделе [Установка](/development/installation#convex-backend-env-vars).
-::
diff --git a/docs/content/ru/3.reference/01.architecture.md b/docs/content/ru/3.reference/01.architecture.md
index 1d86f26d..0b2a8ef2 100644
--- a/docs/content/ru/3.reference/01.architecture.md
+++ b/docs/content/ru/3.reference/01.architecture.md
@@ -1,11 +1,11 @@
---
title: Архитектура
-description: Инициализация, структура проекта, паттерн хранилищ, авторизация.
+description: Инициализация, структура проекта, паттерн хранилищ, авторизация - Supabase + PowerSync.
navigation:
icon: i-lucide-boxes
seo:
title: Архитектура
- description: Архитектура Финапки: инициализация приложения, паттерн хранилищ, клиент Convex, auth guard, офлайн-режим и ключевые файлы проекта.
+ description: Архитектура Финапки: инициализация приложения, паттерн хранилищ, Supabase Auth, офлайн-first через PowerSync и настройка PWA.
---
## Инициализация приложения
@@ -15,119 +15,105 @@ seo:
├── Плагины
│ ├── theme.ts (enforce: 'post')
│ │ └── Чтение темы из localStorage → обновление appConfig
-│ └── convex.ts
-│ └── Создание WebSocket-клиента → настройка авторизации
+│ └── powersync.client.ts
+│ ├── navigator.storage.persist() - защита IndexedDB от вытеснения
+│ ├── setUploadErrorHandler → showErrorToast('sync.errors.uploadRejected')
+│ └── watch uid (immediate)
+│ ├── uid есть → setAuthCookie(uid) + connectPowerSync(...)
+│ └── uid нет → clearAuthCookie() + disconnectPowerSync()
├── app.vue
│ ├── useHead() - CSS-переменные темы (tagPriority: -2)
│ ├── useGuard() - логика редиректа авторизации
│ └── рендер layout + page
└── useInitApp (на авторизованной странице)
- ├── loadDataFromCache() - параллельное чтение из localforage (6 элементов)
- ├── loadDataFromDB()
- │ ├── await waitForConvexAuth() - ожидание аутентификации WebSocket
- │ ├── параллельная инициализация хранилищ (5 хранилищ)
- │ │ ├── initCurrencies()
- │ │ ├── initUserSettings()
- │ │ ├── initWallets()
- │ │ ├── initCategories()
- │ │ └── initTrns() - дельта или полная синхронизация
- │ └── replayOfflineQueue() - воспроизведение ожидающих офлайн-операций
+ └── хранилища гидрируются автоматически через подписки watchTable
+ ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)
+ ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)
+ ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)
+ ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)
+ └── useTrnsStore - watchTable('SELECT * FROM trns', ...)
```
+Каждый `watchTable` срабатывает немедленно с текущими локальными строками SQLite и повторно при каждом изменении (локальная запись или входящая синхронизация). Отдельного шага «инициализация + подписка» нет.
+
## Структура проекта
```
-app/ # Nuxt: компоненты, composables, страницы, плагины
-convex/ # Бэкенд: схема, queries, mutations, auth, Telegram-бот
-services/ # Клиентская инфраструктура (фабрика Convex-клиента, конвертеры API)
-utils/ # Чистые хелперы (id, logger, типы)
-utils/migrate/ # Скрипты миграции Firebase → Convex (data.json в gitignore)
-i18n/locales/ # en-US.js, ru-RU.js
+app/ # @finapp/app - Nuxt, конфиг Supabase, конфиг PowerSync
+ app/ # Nuxt-корень (компоненты, composables, middleware, страницы, плагины)
+ services/powersync/ # Клиентский слой данных: схема, db-синглтон, коннектор, трансформации, мутации
+ supabase/ # Конфиг Supabase: миграции, RLS-политики, powersync_setup.sql
+ powersync/ # Self-hosted PowerSync: docker-compose, config/
+docs/ # @finapp/docs - сайт документации
+i18n/locales/ # en-US.js, ru-RU.js
```
Неочевидные соглашения:
-- `convex/_generated/` создаётся Convex CLI - не редактировать.
-- `services/convex/` вынесен из `convex/` намеренно: `convex/` - это деплоящийся бэкенд, `services/` - только фронтенд-прослойка (фабрика клиента, конвертеры doc → map).
-- Каждая фича в `app/components/<feature>/` содержит свой Pinia store, форму, список и типы - отдельной папки `stores/` нет.
+- `services/powersync/` - клиентский слой данных: SQLite-схема (`AppSchema.ts`), синглтон `PowerSyncDatabase` (`db.ts`), коннектор загрузки (`connector.ts`), конвертеры строк/элементов (`transforms.ts`) и хелперы записи (`mutations.ts`).
+- Каждая фича в `app/app/components/<feature>/` содержит свой Pinia-стор, форму, список и типы - отдельной папки `stores/` нет.
+- `supabase/migrations/` содержит все изменения схемы Postgres. Никогда не редактировать вручную - использовать `supabase migration new`.
## Паттерн хранилища
-Все Pinia-хранилища (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`) следуют одному паттерну:
+Все Pinia-хранилища (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`, `useUserStore`, `useCurrenciesStore`) следуют одному паттерну:
```
-items: shallowRef # реактивное состояние (shallow для производительности)
-init() # запрос из Convex → mergeOfflineOps → set
-set(data) # items.value = data + debouncedPersist (300мс)
-save({ id, values }) # оптимистичный UI → pushSaveOp → fire mutation
-delete(id) # оптимистичный UI → pushDeleteOp → fire mutation
+items: shallowRef<Map|null> # реактивное состояние (shallow для производительности)
+подписка watchTable # срабатывает при инициализации + каждой записи или синхронизации
+save({ id, values }) # оптимистичная запись → upsertRow → откат при ошибке
+delete(id) # оптимистичная запись → deleteRow → откат при ошибке
```
-### Поток данных (save)
+### Поток данных (запись)
```
действие пользователя
→ save({ id, values })
- → isExisting = !isLocalId(id) && id in items
- → оптимистично: set({ ...items, [id]: values })
- → pushSaveOp({ entity, id, isDemo, isExisting, values })
- → fire mutation (без await)
- → .then(): removeOfflineOp + переназначение frontend ID
- → .catch(): показать toast с ошибкой
+ → prev = снимок текущих items
+ → оптимистично: items.value = new Map(...items, [id, values])
+ → await upsertRow(table, id, row)
+ → успех: watchTable срабатывает → хранилище обновляется из SQLite
+ → ошибка: items.value = prev + showErrorToast
```
-### Поток данных (init)
+Откат при ошибке записи обрабатывает ошибки локального SQLite. Отказ на стороне сервера (RLS, ограничение) обрабатывается отдельно обработчиком ошибок загрузки коннектора (показывает toast `sync.errors.uploadRejected`).
+
+### Поток данных (watchTable)
```
-init()
- → запрос из Convex (query)
- → конвертация в map (удаление _id, _creationTime, userId)
- → mergeOfflineOps(data, entity)
- → чтение ожидающих операций из очереди
- → применение create/update операций поверх серверных данных
- → удаление устаревших frontend ID
- → set(data)
+watchTable('SELECT * FROM trns', [], onRows, throttleMs)
+ → срабатывает немедленно с текущими локальными строками
+ → срабатывает снова при каждом изменении таблицы (локальная запись ИЛИ входящая синхронизация PowerSync)
+ → onRows: rows → трансформация через rowToTrn() → items.value = new Map(...)
```
-## Доступ к клиенту Convex
-
-| Composable | Возвращает | Назначение |
-|------------|-----------|------------|
-| `useConvexClient()` | `ConvexClient` | Синглтон WebSocket-клиента |
-| `useConvexClientWithApi()` | `{ api, client }` | Клиент + автогенерируемый объект `api` для типизированных запросов/мутаций |
+`useTrnsStore` использует `reconcileTrns(prev, rows)` внутри `onRows`: возвращает тот же `prev`-ref, если ничего не изменилось (подавляет эхо от собственной оптимистичной записи хранилища), и переиспользует неизменённые объекты строк по `updatedAt`, так что `rowToTrn()` выполняется только для изменённых строк.
-Хранилища используют императивный `client.query()` и `client.mutation()`, так как управляют собственным кешированием и офлайн-слиянием.
+### Каскадное удаление
-**Поток авторизации (клиент - `plugins/convex.ts`):**
-1. При инициализации плагина: если `hasAuthCookie()` && онлайн → вызов `client.setAuth(fetchToken)` для параллельного получения токена с разрешением сессии
-2. `fetchToken` использует `authClient.convex.token()` (Better Auth `convexClient()` плагин) - `crossDomainClient` автоматически пробрасывает cookie через `localStorage['better-auth_cookie']`
-3. `authReadyPromise` разрешается после первого получения токена (успех или ошибка) - `loadDataFromDB()` ожидает это перед запросами к Convex
-4. Watch сессии действует только на определённые результаты (пользователь найден → `setAuth()`, пользователь отсутствует без ошибки → `clearAuth()`). Сетевые ошибки и `isPending` игнорируются для предотвращения выхода при офлайне
-5. Событие `online`: пересоздаёт `authReadyPromise` и вызывает `setAuth()` для нового токена
-6. `ensureConvexAuth()`: вызывается из `/auth/callback` для установки авторизации ДО SPA-навигации на dashboard
+`deleteWallet` и `deleteCategory` также удаляют транзакции сущности из локальной SQLite перед возвратом (иначе подписка `watchTable` на `trns` вернёт их в UI после удаления родителя). Откат при ошибке восстанавливает и саму сущность, и её транзакции.
-## Система Frontend ID
+### Демо-режим
-Новые сущности получают временные ID с префиксом `local_` (например, `local_a1b2c3`). `isLocalId(id)` проверяет `id.startsWith('local_')` для их различения. См. [обоснование](/ru/development/tech-decisions#система-frontend-id).
+Демо-режим полностью обходит PowerSync. Хранилища проверяют `isDemo` и пропускают все вызовы PowerSync. Вместо этого используются данные в памяти + localforage. Демо-данные (1000 транзакций, 18 категорий, 6 кошельков) генерируются в `useDemo.ts`. Управляется cookie `finapp.isDemo`.
-Frontend ID переназначаются на Convex ID в `handleMutationResult()` после успешных мутаций создания. Хранилище заменяет `items[frontendId]` на `items[convexId]`.
+## Авторизация
-## Защита авторизации
+### Supabase Auth
-### Слои авторизации
-
-Авторизация использует два слоя:
+`app/app/composables/useSupabase.ts` предоставляет:
+- Синглтон-клиент `supabase-js` (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: false`).
+- Composable `useSupabaseAuth()` с реактивными `session`, `uid`, `user`, `isAuthReady`, а также `signInWithPassword` / `signUp` / `signOut`.
+- Сессия сохраняется в localStorage и автоматически обновляется. `onAuthStateChange` поддерживает модульный реактивный ref `session` в актуальном состоянии.
-1. **Route middleware** (`auth.global.ts`): проверяет cookie `finapp.localAuthUid` и решает, разрешить навигацию или редиректить на `/login`. При отсутствии сети пропускает сетевые запросы, доверяя кешированному cookie.
-2. **Клиентская защита** (`useGuard()` в `app.vue`): асинхронно следит за сессией Better Auth и обрабатывает истечение сессии после начальной загрузки. При неожиданной потере сессии (не через sign-out) cookie `finapp.localAuthUid` очищается.
+Метод авторизации: **только email/password** (OAuth в MVP не предусмотрен).
-### OTT-авторизация
+### Защита авторизации
-Google OAuth использует одноразовый токен (OTT) для кросс-доменной авторизации:
+Авторизация использует два слоя:
-1. Google OAuth перенаправляет обратно с параметром `?ott=...`
-2. Глобальный middleware перехватывает любой маршрут с `ott` в запросе и перенаправляет на `/auth/callback`
-3. Страница callback верифицирует OTT с бэкендом Convex Better Auth
-4. При успехе: устанавливает cookie авторизации, вызывает `ensureConvexAuth()` для немедленного старта авторизации Convex, затем навигация через `navigateTo()` на исходный URL
+1. **Route middleware** (`app/app/middleware/auth.global.ts`): синхронная проверка cookie `finapp.localAuthUid` (`hasAuthCookie()`), без сетевых запросов, работает офлайн. Перенаправляет на `/login` (сохраняя `?redirect=`) при отсутствии; перенаправляет `/login` → `/dashboard` при наличии cookie. Демо-режим обходит эту проверку.
+2. **Плагин PowerSync** (`app/app/plugins/powersync.client.ts`): следит за Supabase `uid`. Устанавливает cookie `finapp.localAuthUid` при разрешении сессии; очищает при выходе. Это единственное место, где записывается cookie.
### Защита от редиректов
@@ -140,52 +126,46 @@ Google OAuth использует одноразовый токен (OTT) для
- Не авторизован + не на `/login` → редирект на `/login`
- Флаг `isSigningOut` предотвращает цикл редиректов при выходе
-## Офлайн / Онлайн
-
-Приложение сохраняет состояние авторизации и данные при офлайне:
+## Защита локальной БД от чужого пользователя
-- **Cookie авторизации сохраняется офлайн:** Watch сессии игнорирует сетевые ошибки (`s.error`) - только определённые ответы «нет пользователя» очищают cookie. Предотвращает выход при офлайне или нестабильном соединении.
-- **Получение токена пропускается офлайн:** `fetchToken` проверяет `!navigator.onLine` перед HTTP-запросами - избегает шумных ошибок в консоли.
-- **Переподключение:** Слушатель события `online` пересоздаёт `authReadyPromise` и вызывает `setAuth()`, чтобы `loadDataFromDB()` (который ожидает `waitForConvexAuth()`) получил свежий токен.
-- **Route middleware:** `auth.global.ts` проверяет `hasAuthCookie()` синхронно - без сетевых запросов, работает офлайн.
-- **PWA:** Service worker прекеширует все ассеты сборки + `NavigationRoute` отдаёт SPA-оболочку для всех навигаций.
+`connectPowerSync(client, powerSyncUrl, userId)` проверяет сохранённый маркер владельца (`finapp.psDbOwnerUid` в localStorage). Если локальная SQLite принадлежит другому пользователю, база данных **стирается перед подключением** (fail-closed). Это предотвращает утечку данных при входе другой учётной записи на том же устройстве.
## Поток выхода
```
signOut()
→ isSigningOut = true (предотвращение цикла редиректов)
- → очистка данных хранилищ (trns, categories, wallets, user)
- → очистка cookie авторизации
- → очистка localforage
- → authClient.signOut()
- → удаление ключей better-auth из localStorage
+ → supabase.auth.signOut()
+ → disconnectPowerSync() - disconnectAndClear() стирает локальную SQLite + очищает маркер владельца
+ → clearAuthCookie()
→ window.location.href = '/login' (жёсткая навигация, уничтожение всего JS-состояния)
```
-Жёсткая навигация вместо Vue Router - см. [обоснование](/ru/development/tech-decisions#жёсткая-навигация-при-выходе).
+Жёсткая навигация вместо Vue Router - см. [Технические решения](/ru/development/tech-decisions).
+
+## Курсы валют
-## Демо режим
+- **Источник:** OpenExchangeRates API (бесплатный тариф), заполняется на стороне сервера
+- **Хранение:** таблица `rates` в Postgres; глобальный поток PowerSync синхронизирует все строки каждому авторизованному пользователю
+- **Фронтенд:** `useCurrenciesStore` подписывается через `watchTable('SELECT * FROM rates', ...)`
+- **Использование:** `getAmountInRate()` конвертирует суммы в базовую валюту для статистики
-Демо режим работает без авторизации. Управляется cookie `finapp.isDemo`.
+## PWA
-- **Данные:** 1000 случайных транзакций, 18 категорий, 6 кошельков - генерируются в `useDemo.ts`
-- **Хранение:** только localStorage/localforage, без запросов к Convex
-- **Изоляция хранилищ:** все методы мутации (`saveTrn`, `saveWallet` и т.д.) проверяют `isDemo` и пропускают мутации Convex + офлайн-очередь
-- **Выход:** очистка локальных данных, без вызова `authClient.signOut()`
+- Стратегия: `generateSW` из `@vite-pwa/nuxt` (без кастомного service worker)
+- Прекеширование: все ассеты сборки включая `wasm`-файлы; `maximumFileSizeToCacheInBytes: 3 МБ` - WASM-файлы wa-sqlite прекешируются для офлайн-запуска
+- `navigateFallback: '/'` отдаёт SPA-оболочку для всех навигаций (офлайн-поддержка)
+- Runtime-кеширование: Google Fonts, иконки Iconify (CacheFirst)
+- Start URL: `/dashboard`
+- Манифест: `display: 'standalone'`
-## Курсы валют
+## Логирование
-- **Источник:** OpenExchangeRates API (бесплатный тариф)
-- **Расписание:** ежедневный cron в 6:00 UTC (`convex/crons.ts`)
-- **Хранение:** таблица `rates` с индексом `by_date` (одна запись в день)
-- **Фронтенд:** `useCurrenciesStore` получает последние курсы, запускает обновление если пусто
-- **Fallback:** Если в базе нет курсов (новый деплоймент), курсы должны быть загружены через ежедневный cron или вручную через `npx convex run`
-- **Использование:** `getAmountInRate()` конвертирует суммы в основную валюту для статистики
+`createLogger(prefix)` (`app/utils/logger.ts`) - логирование только для разработки. В продакшене работает только `.error()`. Все операции хранилищ и авторизации инструментированы с префиксами (`[wallets]`, `[trns]`, `[auth/middleware]` и т.д.). Проверяйте консоль браузера при `pnpm dev`.
## Управление модальными окнами
-Модальные окна используют локальные `ref` и паттерн `v-if` + `@close` emit. Видимость меню - модульный `ref` в `useMenuData.ts` (общий для всех вызовов). Остальные модалки (например, сортировка кошельков) используют локальные `ref` компонента. Глобального реестра модалок нет - они размонтируются автоматически при размонтировании родительских компонентов (например, при выходе хранилища сбрасываются в `null` → условие layout становится false → модалки исчезают).
+Модальные окна используют локальные `ref` и паттерн `v-if` + `@close` emit. Видимость меню - модульный `ref` в `useMenuData.ts` (общий для всех вызовов). Глобального реестра модалок нет - они размонтируются автоматически при размонтировании родительских компонентов (например, при выходе хранилища сбрасываются в `null` → условие layout становится false → модалки исчезают).
## Персистентность сайдбара
@@ -195,58 +175,34 @@ signOut()
Мобильная форма транзакции использует кастомный компонент `BottomSheet` с `useBottomSheetDrag` - ручная реализация drag-поддержки touch и mouse. Функции: настраиваемый порог начала закрытия, определение направления, затухание оверлея, учёт скролла (игнорирует drag при прокрутке контента), исключение sort-хэндлов.
-## Логирование
-
-`createLogger(prefix)` (`app/utils/logger.ts`) - логирование только для разработки. В продакшене работает только `.error()`. Все операции хранилищ и авторизации инструментированы с префиксами (`[wallets]`, `[trns]`, `[auth/middleware]` и т.д.). Проверяйте консоль браузера при `pnpm dev`.
-
-## PWA
-
-- Стратегия: `generateSW` из `@vite-pwa/nuxt` (без кастомного service worker)
-- Прекеширование: все ассеты сборки кешируются автоматически
-- `navigateFallback: '/'` отдаёт SPA-оболочку для всех навигаций (офлайн-поддержка)
-- Runtime-кеширование: Google Fonts, иконки Iconify (CacheFirst)
-- Start URL: `/dashboard`
-- Манифест: `display: 'standalone'`
-
-## Инструменты миграции
-
-Бэкенд Convex включает внутренние мутации для миграции данных, вызываемые через `npx convex run`:
-
-| Функция | Назначение |
-|---------|-----------|
-| `migrate:deleteUserData` | Удаление всех данных пользователя |
-| `migrate:insertWallets` | Массовый импорт кошельков с ремаппингом ID |
-| `migrate:insertCategories` | Массовый импорт категорий с ремаппингом parentId |
-| `migrate:insertTrnsBatch` | Массовый импорт транзакций |
-| `migrate:insertUserSettings` | Импорт настроек пользователя |
-
-Скрипт миграции: `utils/migrate/firebase.js` - читает JSON-экспорт Firebase, трансформирует данные и вызывает мутации выше. Подробнее: [Миграция с Firebase](/ru/development/migration).
-
## Краткая справка по ключевым файлам
| Что | Где |
|-----|-----|
-| Точка входа | `app/app.vue` |
-| Логика темы | `app/plugins/theme.ts`, `app/app.vue` |
-| Настройка авторизации | `app/plugins/convex.ts`, `app/composables/useAuth.ts` |
-| Cookie авторизации | `app/composables/useAuthCookie.ts` |
-| Защита авторизации | `app/middleware/auth.global.ts`, `app/components/user/useGuard.ts` |
-| Синхронизация хранилищ | `app/composables/useStoreSync.ts` |
-| Офлайн-очередь | `app/components/offline/helpers.ts` |
-| Воспроизведение офлайн | `app/components/offline/replay.ts` |
-| Расчёт статистики | `app/components/amount/getTotal.ts` |
-| Схема Convex | `convex/schema.ts` |
-| Frontend ID | `app/utils/convexId.ts`, `utils/generateId.ts` |
-| Утилиты дат | `app/components/date/utils.ts` |
-| Логирование | `app/utils/logger.ts` |
+| Точка входа | `app/app/app.vue` |
+| Логика темы | `app/app/plugins/theme.ts`, `app/app/app.vue` |
+| Плагин PowerSync | `app/app/plugins/powersync.client.ts` |
+| Supabase-клиент + авторизация | `app/app/composables/useSupabase.ts` |
+| Cookie авторизации | `app/app/composables/useAuthCookie.ts` |
+| Защита авторизации (middleware) | `app/app/middleware/auth.global.ts` |
+| Логика защиты (app.vue) | `app/app/components/user/useGuard.ts` |
+| Утилиты синхронизации хранилищ | `app/app/composables/useStoreSync.ts` |
+| Синглтон PowerSync db | `app/services/powersync/db.ts` |
+| SQLite-схема | `app/services/powersync/AppSchema.ts` |
+| Коннектор загрузки | `app/services/powersync/connector.ts` |
+| Трансформации строк/элементов | `app/services/powersync/transforms.ts` |
+| Хелперы записи | `app/services/powersync/mutations.ts` |
+| Подавление эха | `app/app/components/trns/reconcile.ts` |
+| Расчёт статистики | `app/app/components/amount/getTotal.ts` |
| Защита редиректов | `app/utils/redirect.ts` |
-| Состояние меню | `app/components/layout/useMenuData.ts` |
-| Bottom sheet drag | `app/components/bottomSheet/useBottomSheetDrag.ts` |
-| Инструменты миграции | `convex/migrate.ts`, `utils/migrate/firebase.js` |
-| Telegram-бот | `convex/telegram/bot.ts`, `convex/telegram/link.ts` |
-| UI настроек Telegram | `app/components/telegram/SettingsCard.vue` |
+| Утилиты дат | `app/app/components/date/utils.ts` |
+| Логирование | `app/utils/logger.ts` |
+| Состояние меню | `app/app/components/layout/useMenuData.ts` |
+| Bottom sheet drag | `app/app/components/bottomSheet/useBottomSheetDrag.ts` |
+| Миграции Supabase | `app/supabase/migrations/` |
+| Правила синхронизации PowerSync | `app/powersync/config/sync-config.yaml` |
## Следующие шаги
-- [Синхронизация](/ru/development/sync) - механизм дельта-синхронизации транзакций
-- [Офлайн-очередь](/ru/development/offline-queue) - офлайн-очередь и система Frontend ID
+- [Синхронизация](/ru/development/sync) - как PowerSync синхронизирует данные между сервером и локальной SQLite
+- [Офлайн-first](/ru/development/offline-queue) - офлайн-записи, очередь загрузки и обработка ошибок
diff --git a/docs/content/ru/3.reference/02.transaction-types.md b/docs/content/ru/3.reference/02.transaction-types.md
index 7989796e..e2e5d0fe 100644
--- a/docs/content/ru/3.reference/02.transaction-types.md
+++ b/docs/content/ru/3.reference/02.transaction-types.md
@@ -88,13 +88,13 @@ const isAdjustment = trn.categoryId === 'adjustment'
## Поведение при смене типа
-При смене типа транзакции через `trns.update` бэкенд Convex нормализует данные:
+При смене типа транзакции нормализация происходит на клиенте - в `trnToRow` (`services/powersync/transforms.ts`) при записи. Никакого серверного бэкенда для этого нет:
-- **→ Перевод**: устанавливает `categoryId` в `'transfer'`, очищает поля одного кошелька (`walletId`, `amount`)
-- **→ Расход/Доход**: очищает поля перевода (`expenseWalletId`, `incomeWalletId`, `expenseAmount`, `incomeAmount`)
+- **→ Перевод**: `trnToRow` устанавливает `categoryId` в `'transfer'` и записывает `expenseWalletId`/`incomeWalletId`/`expenseAmount`/`incomeAmount`; поля одного кошелька (`walletId`, `amount`) записываются как `null`
+- **→ Расход/Доход**: `trnToRow` записывает `walletId`/`amount`; поля перевода (`expenseWalletId`, `incomeWalletId`, `expenseAmount`, `incomeAmount`) записываются как `null`
- **→ Корректировка**: дополнительная очистка не требуется - корректировка использует обычные поля Расхода/Дохода с `categoryId: 'adjustment'`
-Это предотвращает осиротевшие записи в индексах и гарантирует хранение только полей, относящихся к текущему типу.
+Это гарантирует, что только поля, относящиеся к текущему типу, имеют ненулевые значения в локальной SQLite-строке и на сервере.
## Статистика
diff --git a/docs/content/ru/3.reference/03.sync.md b/docs/content/ru/3.reference/03.sync.md
index abfcc98a..d10b1abf 100644
--- a/docs/content/ru/3.reference/03.sync.md
+++ b/docs/content/ru/3.reference/03.sync.md
@@ -1,89 +1,115 @@
---
title: Синхронизация
-description: Дельта-синхронизация транзакций - обнаружение удалений, производительность.
+description: Как PowerSync синхронизирует локальную SQLite с Supabase Postgres.
navigation:
icon: i-lucide-refresh-cw
seo:
title: Синхронизация
- description: Как работает дельта-синхронизация транзакций в Финапке: механизм, обнаружение удалений по хешу, взаимодействие с офлайн-очередью и ключевые файлы.
+ description: Как работает синхронизация данных в Финапке через PowerSync - локальная SQLite как источник истины, потоки синхронизации, очередь загрузки, объединение изменений и подавление эха.
---
-Транзакции используют инкрементальную (дельта) синхронизацию, чтобы не загружать все данные при каждом запуске. Вызывается из `initTrns()` при [инициализации приложения](/ru/development/architecture#инициализация-приложения).
+PowerSync - это слой синхронизации между клиентом (локальная SQLite через wa-sqlite / IndexedDB) и сервером (Supabase Postgres). Локальная SQLite является единственным источником истины для UI - хранилища читают только из SQLite, никогда напрямую из сети.
## Как это работает
-1. Чтение `syncMeta` из LocalForage
-2. **Нет syncMeta или кеша** → `fullSync()`: загрузка всего через пагинированный `trns.list`, сохранение syncMeta
-3. **Есть syncMeta + кеш** → `deltaSync()`: загрузка только изменений через пагинированный `trns.delta` + `trns.idsHash` (параллельно)
-4. При ошибке дельта или несовпадении хеша → откат на `fullSync()`
-5. Оба пути заканчиваются `mergeOfflineOps()` + `setTrns()`
+```
+Supabase Postgres (сервер)
+ ↕ логическая репликация (powersync_role, публикация powersync)
+Сервис PowerSync (self-hosted, :8080)
+ ↕ WebSocket sync stream (Sync Streams издание 3, per-user + глобальный)
+Локальная SQLite (клиент, IDBBatchAtomicVFS / IndexedDB)
+ ↕ подписки watchTable
+Pinia-хранилища (UI)
+```
-## Запросы Convex
+При подключении PowerSync воспроизводит серверное состояние в локальную SQLite. После этого каждое серверное изменение передаётся по открытому WebSocket. Локальные записи идут в SQLite немедленно (оптимистично) и ставятся в очередь на загрузку.
-| Запрос | Аргументы | Возвращает | Индекс |
-|--------|-----------|------------|--------|
-| `trns.list` | `paginationOpts` | Пагинированные транзакции (`PaginationResult`) | `by_user_date` |
-| `trns.delta` | `paginationOpts`, `since: number` | Пагинированные транзакции с `updatedAt > since` (`PaginationResult`) | `by_user_updatedAt` |
-| `trns.idsHash` | - | XOR-хеш всех ID транзакций (строка) | `by_user` |
+## Потоки синхронизации
-## Метаданные синхронизации
+Правила синхронизации определены в `app/powersync/config/sync-config.yaml` с использованием **Sync Streams издания 3**.
-Хранятся в LocalForage под ключом `finapp.trns.syncMeta`:
+**Поток на пользователя (`user_data`, auto_subscribe):**
+```sql
+SELECT * FROM categories WHERE "userId" = auth.user_id()
+SELECT * FROM wallets WHERE "userId" = auth.user_id()
+SELECT * FROM trns WHERE "userId" = auth.user_id()
+SELECT * FROM user_settings WHERE "userId" = auth.user_id()
+```
-```typescript
-type TrnsSyncMeta = {
- lastSyncedAt: number // timestamp последней успешной синхронизации
- idsHash: string // XOR-хеш всех ID транзакций при последней синхронизации
-}
+**Глобальный поток (`rates`):**
+```sql
+SELECT * FROM rates
```
-## Обнаружение удалений
+`auth.user_id()` разрешается в UUID пользователя Supabase из проверенного JWT. Сервис PowerSync проверяет JWT Supabase (ES256) через JWKS-endpoint, поэтому дополнительная логика токенов на клиенте не требуется.
+
+## watchTable - паттерн единственной подписки
+
+`watchTable(sql, params, onRows, throttleMs?)` в `app/services/powersync/db.ts`:
+
+- Выполняет SQL-запрос немедленно и вызывает `onRows` с текущими локальными строками.
+- Подписывается на события изменения таблицы. При изменении любой строки в таблице (локальная запись или входящая синхронизация) вызывает `onRows` со свежими строками.
+- `throttleMs` объединяет быстрые всплески изменений (trailing edge). По умолчанию: 30мс. Транзакции используют 120мс для обработки большого потока строк при начальной синхронизации без лишних перерисовок UI.
+- Возвращает `AbortController` - вызов `.abort()` отменяет подписку (хранилища делают это при разрушении).
+
+Этот единственный механизм заменяет разделение на «инициализацию + подписку на реалтайм». Отдельного шага «загрузить из кеша, затем подписаться» не существует.
+
+## Подавление эха (транзакции)
+
+Когда хранилище делает оптимистичную запись, а затем `watchTable` срабатывает для этой же записи, UI мог бы мерцать. `useTrnsStore` избегает этого с помощью `reconcileTrns(prev, rows)` (`app/app/components/trns/reconcile.ts`):
+
+- Сравнивает входящие строки с предыдущим состоянием по `updatedAt`.
+- Если ничего не изменилось - возвращает тот же `prev`-ref (Vue не видит изменений, перерисовки нет).
+- Для изменённых строк запускает `rowToTrn()` только для дельты - неизменённые объекты строк переиспользуются.
+
+## Очередь загрузки
+
+Локальные записи автоматически ставятся в очередь PowerSync. `SupabaseConnector.uploadData()` (`app/services/powersync/connector.ts`) опустошает очередь:
+
+| Операция PowerSync | Вызов Supabase |
+|-------------------|----------------|
+| `PUT` | `supabase.from(table).upsert(row)` |
+| `PATCH` | `supabase.from(table).update(data).eq('id', id)` |
+| `DELETE` | `supabase.from(table).delete().eq('id', id)` |
-Поскольку Convex использует жёсткое удаление (без поля `deletedAt`), удаления обнаруживаются сравнением хешей:
+Коннектор работает от имени авторизованного пользователя Supabase, поэтому RLS-политики применяются при каждой загрузке. Это слой безопасности пути записи - путь чтения использует `powersync_role` (BYPASSRLS) для репликации, разграничение по пользователям обеспечивается правилами синхронизации.
-1. `deltaSync()` применяет дельта-изменения к кешированным данным
-2. Вычисляет локальный XOR-хеш из всех не-локальных ID в результирующих данных
-3. Сравнивает с `trns.idsHash()` с сервера
-4. **Хеши совпадают** → удалений нет, синхронизация завершена
-5. **Хеши не совпадают** → обнаружены удаления или пропущенные изменения → откат на `fullSync()`
+## Фатальные и повторяемые ошибки загрузки
-Этот подход прост и надёжен. Удаления редки (1-2 в месяц), поэтому разовый `fullSync()` при несовпадении хешей - приемлемый компромисс.
+| Класс ошибки | Коды Postgres | Поведение |
+|-------------|---------------|-----------|
+| Фатальные (данные / ограничение / RLS) | `22xxx`, `23xxx`, `42501` | Транзакция **отбрасывается** - очередь разблокируется; `setUploadErrorHandler` показывает toast `sync.errors.uploadRejected` |
+| Повторяемые (сеть, таймаут) | всё остальное | Ошибка **пробрасывается** - PowerSync повторяет попытку с backoff |
-## Триггеры полной синхронизации
+Отбрасывание фатальной операции означает тихое расхождение локальной SQLite и сервера для этой строки. Пользователь получает уведомление через toast и может исправить данные вручную.
-Полная синхронизация запускается когда:
-- Первый запуск приложения (нет syncMeta в LocalForage)
-- Кеш LocalForage очищен
-- Дельта-синхронизация не удалась (сетевая ошибка, повреждённые данные)
-- Несовпадение хешей после применения дельта (обнаружены удаления)
+## Обработка удалений
-## Взаимодействие с офлайн-очередью
+PowerSync синхронизирует жёсткие удаления нативно - когда строка удаляется на сервере, сервис PowerSync передаёт событие удаления клиенту и SQLite удаляет строку. Никакого сравнения хешей или полного обновления не требуется.
-Дельта-синхронизация полностью совместима с [офлайн-очередью](/ru/development/offline-queue):
-- `mergeOfflineOps()` запускается после полной и дельта-синхронизации
-- `cleanupFrontendIds()` удаляет устаревшие frontend ID из объединённых данных, которые больше не присутствуют в ожидающих операциях (уже синхронизированы в предыдущей сессии, но остались в кеше)
-- Транзакции, созданные офлайн (frontend ID), не затрагиваются обнаружением удалений (сравниваются только Convex ID)
-- Воспроизведение офлайн-очереди происходит после завершения `initTrns()`
+**Каскадные удаления (на клиенте):** `deleteWallet` и `deleteCategory` также удаляют транзакции сущности из локальной SQLite до возврата. Без этого подписка `watchTable` на `trns` вернула бы осиротевшие строки в UI после удаления родительской сущности.
-## Производительность
+## Первая синхронизация
-| Метрика | Полная синхронизация (10К транзакций) | Дельта-синхронизация (10 изменений) |
-|---------|--------------------------------------|-------------------------------------|
-| Сеть | ~2 МБ (пагинированно) | ~2 КБ (дельта) + хеш |
-| Парсинг | 10К объектов | 10 объектов |
-| Сокращение | - | ~99% сети и парсинга |
+`waitForFirstSync(timeoutMs=10000)` (`app/services/powersync/db.ts`) разрешается после полной передачи начального серверного состояния в локальную SQLite (или по таймауту). `useInitApp` ожидает этого перед показом основного UI, гарантируя, что пользователь не увидит пустое приложение после входа.
## Ключевые файлы
| Файл | Роль |
|------|------|
-| `convex/trns.ts` | Запросы `list`, `delta`, `idsHash` |
-| `convex/schema.ts` | Индекс `by_user_updatedAt` |
-| `app/components/trns/useTrnsStore.ts` | `fullSync()`, `deltaSync()`, `initTrns()`, `fetchAllPages()` |
-| `app/composables/useStoreSync.ts` | `mergeOfflineOps()`, `cleanupFrontendIds()` |
-| `app/components/offline/storageKeys.ts` | Ключ хранения `trnsSyncMeta` |
+| `app/services/powersync/db.ts` | Синглтон `PowerSyncDatabase`, `connectPowerSync`, `watchTable`, `waitForFirstSync` |
+| `app/services/powersync/connector.ts` | `SupabaseConnector` - `fetchCredentials` + `uploadData` |
+| `app/services/powersync/AppSchema.ts` | SQLite-схема клиента |
+| `app/services/powersync/transforms.ts` | `rowToTrn`, `rowToWallet`, `rowToCategory`, `rowToRates`, `trnToRow` и др. |
+| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow`, `upsertRows` |
+| `app/app/components/trns/useTrnsStore.ts` | Подписка `watchTable` + подавление эха `reconcileTrns` |
+| `app/app/components/trns/reconcile.ts` | `reconcileTrns` - дедупликация и переиспользование неизменённых объектов строк |
+| `app/app/plugins/powersync.client.ts` | Плагин подключения/отключения PowerSync при смене состояния авторизации |
+| `app/powersync/config/sync-config.yaml` | Правила Sync Streams (per-user + глобальные rates) |
+| `app/powersync/config/service.yaml` | Конфиг сервиса PowerSync (репликация, JWT, порт 8080) |
+| `app/supabase/powersync_setup.sql` | `powersync_role` + публикация `powersync` |
## Следующие шаги
-- [Офлайн-очередь](/ru/development/offline-queue) - взаимодействие офлайн-операций с синхронизацией
+- [Офлайн-first](/ru/development/offline-queue) - офлайн-записи, очередь загрузки и обработка фатальных ошибок
- [Архитектура](/ru/development/architecture) - инициализация приложения и паттерн хранилищ
diff --git a/docs/content/ru/3.reference/04.offline-queue.md b/docs/content/ru/3.reference/04.offline-queue.md
index 6aebe20a..b1b58501 100644
--- a/docs/content/ru/3.reference/04.offline-queue.md
+++ b/docs/content/ru/3.reference/04.offline-queue.md
@@ -1,204 +1,84 @@
---
-title: Офлайн-очередь
-description: Архитектура очереди, правила свёртки, сценарии синхронизации.
+title: Офлайн-first
+description: Как PowerSync обеспечивает офлайн-записи, очередь загрузки и вывод ошибок.
navigation:
icon: i-lucide-list-ordered
seo:
- title: Офлайн-очередь
- description: Офлайн-очередь Финапки хранит операции локально и синхронизирует при подключении. Правила свёртки, система frontend-ID и сценарии обработки ошибок.
+ title: Офлайн-first
+ description: Финапка работает офлайн-first через PowerSync - локальная SQLite хранит все данные, записи оптимистичны и ставятся в очередь локально, фатальные ошибки загрузки отбрасываются и выводятся через toast.
---
-Единая упорядоченная офлайн-очередь со свёрткой операций. Все ожидающие операции (создание/обновление/удаление) для кошельков, категорий и транзакций хранятся в одном упорядоченном массиве в localforage под ключом `finapp.offline.queue`.
+Финапка работает в режиме офлайн-first через PowerSync. Локальная SQLite является единственным источником истины. Все операции чтения берутся из SQLite; все записи сначала идут в SQLite и ставятся в очередь для загрузки в Supabase Postgres.
-## Архитектура
+## Как это работает
-### Ключевые файлы
-
-| Файл | Описание |
-|------|----------|
-| `app/components/offline/types.ts` | Типы: `OfflineOp`, `EntityType` |
-| `app/components/offline/helpers.ts` | API очереди: push, remove, get, clear |
-| `app/components/offline/replay.ts` | Воспроизведение очереди при перезапуске |
-| `app/components/offline/storageKeys.ts` | Ключи LocalForage для кешей сущностей |
-
-### Правила свёртки
-
-При добавлении новой операции очередь находит последнюю операцию с тем же `entity + id` и выполняет свёртку:
-
-| Существующая | Новая | Результат |
-|-------------|-------|-----------|
-| create | update | create (объединённые данные) |
-| create | delete | удаление обеих (не достигли сервера) |
-| update | update | update (объединённые данные) |
-| update | delete | замена на delete |
-| delete | * | игнорирование новой (delete - терминальная) |
-| - | * | добавление как есть |
-
-### Сериализация
-
-`pushOfflineOp` использует цепочку промисов для сериализации параллельных записей - `await` не требуется в местах вызова.
+```
+действие пользователя (создание/обновление/удаление)
+ → оптимистично: items.value обновляется в хранилище немедленно
+ → upsertRow / deleteRow записывает в локальную SQLite (синхронно)
+ → успех: watchTable срабатывает → хранилище обновляется из SQLite
+ → ошибка: восстанавливается prev-снимок + showErrorToast (ошибка локальной записи)
+ → PowerSync ставит операцию в очередь на загрузку
+ → онлайн: коннектор опустошает очередь → upsert/update/delete в Supabase
+ → офлайн: очередь сохраняется в SQLite; опустошается при переподключении
+```
-### Каскадное удаление на бэкенде
+Ручного управления очередью нет, правил свёртки нет, системы frontend-local ID нет. Очередью загрузки управляет PowerSync.
-`wallets.remove` и `categories.remove` на бэкенде Convex каскадно удаляют все связанные транзакции. Фронтенд НЕ добавляет отдельные операции удаления транзакций при удалении кошелька или категории - в очередь попадает только удаление родительской сущности. `removeTrnsFromStore()` обрабатывает оптимистичную очистку UI без мутаций.
+## Офлайн-записи
-## Система Frontend ID
+При отсутствии соединения:
+- Чтение продолжает работать - все данные уже в локальной SQLite.
+- Записи идут в локальную SQLite немедленно (оптимистично). Пользователь видит изменение сразу.
+- Операция загрузки добавляется во внутреннюю очередь PowerSync.
+- При переподключении PowerSync автоматически опустошает очередь.
-Новые сущности нуждаются в ID до ответа сервера. Фронтенд генерирует временные ID, которые затем переназначаются на реальные Convex ID.
+Никаких действий пользователя для запуска синхронизации после переподключения не требуется.
-### Генерация
+## Обработка ошибок загрузки
-`generateId()` (`utils/generateId.ts`) создаёт ID с префиксом `local_` + 6 случайных base-36 символов. Пример: `local_a1b2c3`.
+`SupabaseConnector.uploadData()` разделяет фатальные ошибки и повторяемые:
-### Отличие от Convex ID
+### Фатальные ошибки (отбрасываются)
-`isLocalId(id)` (`app/utils/convexId.ts`) проверяет `id.startsWith('local_')`. Любой ID с префиксом `local_` - frontend ID.
+Классы ошибок Postgres `22xxx` (исключение данных), `23xxx` (нарушение ограничения целостности) и `42501` (RLS - недостаточно прав) считаются фатальными. Неудавшаяся операция **отбрасывается**, чтобы не блокировать остальную очередь. Плагин выводит ошибку через `showErrorToast('sync.errors.uploadRejected')`.
-Эта проверка используется по всей кодовой базе:
-- Хранилища: определение создания vs обновления (`!isLocalId(id) && id in items`)
-- Дельта-синхронизация: исключение локальных ID из обнаружения удалений
-- Пакетное удаление: фильтрация локальных ID для серверной мутации
-- Воспроизведение: пропуск операций удаления для локальных ID (нечего удалять на сервере)
+Отброшенная операция означает тихое расхождение локальной SQLite и сервера для этой строки. Пользователь получает уведомление через toast и может исправить данные вручную (например, снова отредактировать и сохранить запись).
-### Переназначение ID
+### Повторяемые ошибки
-После успешной мутации создания сервер возвращает новый Convex ID. `handleMutationResult()` (`app/composables/useStoreSync.ts`) заменяет ключ frontend ID в карте хранилища:
+Сетевые ошибки, таймауты и все остальные не-фатальные ошибки вызывают **пробрасывание** ошибки. PowerSync перехватывает его и повторяет попытку с backoff при восстановлении соединения.
-```
-items[frontendId] → items[convexId] (те же данные, новый ключ)
-```
+## Каскадные удаления
-Переназначенное хранилище немедленно сохраняется в localforage.
+`deleteWallet` и `deleteCategory` также удаляют транзакции сущности из локальной SQLite до возврата. Это необходимо, поскольку иначе подписка `watchTable` на `trns` вернула бы осиротевшие строки в хранилище после удаления родительской сущности из SQLite. Откат при ошибке локальной записи восстанавливает и саму сущность, и её транзакции.
-### Очистка устаревших ID
+Сервер не накладывает ограничений внешних ключей (порядок загрузки PowerSync не гарантирован), поэтому ссылочная целостность обеспечивается логикой приложения.
-`cleanupFrontendIds()` (`app/utils/convexId.ts`) запускается в `mergeOfflineOps()` при каждой инициализации. Удаляет локальные ID из кешированных данных, которых больше нет в ожидающей офлайн-очереди - это ID из предыдущей сессии, которые были либо успешно переназначены, либо брошены.
+## Оптимистичный откат
-### Где создаются Frontend ID
-
-| Сущность | Файл | Код |
-|----------|------|-----|
-| Транзакция | `app/components/trnForm/useTrnsFormStore.ts` | `id: values.trnId ?? generateId()` |
-| Категория | `app/components/categories/Form.vue` | `editCategoryId = props.categoryId ?? generateId()` |
-| Кошелёк | `app/components/wallets/Form.vue` | `editWalletId = props.walletId ?? generateId()` |
-
-### Крайние случаи
-
-**Параллельные создания:** Каждое переназначение независимо - деструктуризация извлекает конкретный frontend ID и пересобирает объект. Конфликтов между параллельными мутациями создания нет.
-
-**Краш до переназначения:** Если приложение падает после успешной мутации, но до выполнения `.then()`, `cleanupFrontendIds()` следующей сессии удалит устаревший frontend ID из кеша, а сущность существует на сервере с Convex ID.
-
-## Сценарии
-
-### Создание
-
-#### Онлайн
-1. Пользователь создаёт сущность (кошелёк/категорию/транзакцию)
-2. Хранилище генерирует frontend ID (например, `local_abc123`)
-3. Оптимистичный UI: сущность появляется в хранилище немедленно
-4. `pushOfflineOp({ type: 'create', ... })` сохраняет в очередь
-5. Мутация Convex запускается (fire-and-forget)
-6. `.then()`: удаление операции из очереди, переназначение frontend ID на Convex ID в хранилище
-
-#### Офлайн
-1. Шаги 1-4 такие же, как онлайн
-2. Мутация не удаётся (сетевая ошибка) - `.catch()` показывает toast
-3. Операция остаётся в очереди
-4. Сущность видна в UI с frontend ID
-
-#### Перезапуск после офлайн-создания
-1. `initTrns` получает серверные данные (полная синхронизация при первой загрузке, [дельта-синхронизация](/ru/development/sync) при последующих); `initWallets/initCategories` получают полные данные
-2. Ожидающие операции из очереди объединяются поверх (записи с frontend ID добавляются в хранилище)
-3. `replayOfflineQueue()` запускается:
- - Frontend ID + create/update → отправка в метод хранилища → мутация запускается → `.then()` переназначает ID
- - Frontend ID + delete → пропускается (нечего удалять на сервере)
-4. Сущность получает настоящий Convex ID
-
-### Обновление
-
-#### Онлайн
-1. Пользователь редактирует сущность
-2. `isExisting = !isLocalId(id) && id in items` → `true`
-3. Оптимистичный UI: хранилище обновляется немедленно
-4. `pushOfflineOp({ type: 'update', ... })` - свёртка с существующими операциями
-5. Мутация Convex `update` запускается
-6. `.then()`: удаление операции из очереди
-
-#### Офлайн
-1. Шаги 1-4 такие же, как онлайн
-2. Мутация не удаётся - операция остаётся в очереди
-3. Несколько редактирований сворачиваются: update + update → один update с объединёнными данными
-
-#### Перезапуск после офлайн-обновления
-1. Инициализация получает серверные данные - старую версию (через [дельта-синхронизацию](/ru/development/sync) или полную синхронизацию)
-2. Ожидающее обновление объединяется поверх → UI показывает последнюю версию
-3. Воспроизведение отправляет update → мутация запускается → синхронизировано
-
-### Удаление
-
-#### Онлайн
-1. Пользователь удаляет сущность
-2. Оптимистичный UI: удаление из хранилища немедленно
-3. Для кошельков/категорий: `removeTrnsFromStore()` удаляет дочерние транзакции из UI
-4. `pushOfflineOp({ type: 'delete', ... })` - свёртка с существующими операциями
-5. Мутация Convex `remove` запускается (каскадное удаление транзакций на бэкенде)
-6. `.then()`: удаление операции из очереди
-
-#### Офлайн
-1. Шаги 1-4 такие же, как онлайн
-2. Мутация не удаётся - операция остаётся в очереди
-3. Свёртка: если сущность была создана офлайн и затем удалена → обе операции удаляются (не достигли сервера)
-
-#### Перезапуск после офлайн-удаления
-1. Инициализация получает серверные данные - сущность всё ещё существует на сервере (через [дельта-синхронизацию](/ru/development/sync) или полную синхронизацию)
-2. Ожидающее удаление убирает сущность из объединённых данных
-3. Воспроизведение отправляет delete → мутация запускается → синхронизировано
-
-### Крайние случаи
-
-#### Создание + редактирование офлайн, затем перезапуск
-1. Создание: `pushOfflineOp({ type: 'create', data: v1 })`
-2. Редактирование: свёртка до `create` с объединёнными данными (v1 + v2)
-3. Перезапуск: одна операция create воспроизводится → сервер получает финальную версию
-
-#### Создание + удаление офлайн, затем перезапуск
-1. Создание: `pushOfflineOp({ type: 'create', ... })`
-2. Удаление: свёртка → обе операции удаляются из очереди
-3. Перезапуск: нечего воспроизводить, сущность никогда не существовала на сервере
-
-#### Удаление кошелька/категории с транзакциями офлайн
-1. `pushOfflineOp({ type: 'delete', entity: 'wallets', id })` - только удаление кошелька в очереди
-2. `removeTrnsFromStore(trnsIds)` - оптимистичная очистка UI, без операций очереди для транзакций
-3. Перезапуск: удаление кошелька воспроизводится → бэкенд каскадно удаляет транзакции
-
-#### Осиротевшие транзакции при воспроизведении
-1. Транзакция создана офлайн со ссылкой на кошелёк/категорию
-2. Этот кошелёк/категория удалён (тоже офлайн или с другого устройства)
-3. Воспроизведение обнаруживает сироту: кошелёк/категория больше нет в хранилище
-4. Операция сиротской транзакции удаляется из очереди, пользователю показывается toast
-
-#### Параллельные вызовы pushOfflineOp
-Сериализация цепочкой промисов гарантирует, что записи не перезаписывают друг друга:
-```typescript
-let writeChain = Promise.resolve()
-export function pushOfflineOp(op) {
- writeChain = writeChain.then(() => impl(op), () => impl(op))
- return writeChain
-}
-```
+Каждая запись в хранилище сохраняет снимок `prev = items.value` до мутации. Если локальная запись в SQLite выбрасывает исключение, восстанавливается `items.value = prev` и показывается toast. Это покрывает ошибки локальной записи (например, ограничение SQLite, нехватка места). Ошибки отказа на сервере (RLS, ограничение) обрабатываются отдельно обработчиком ошибок загрузки.
-#### Флаг isReplaying
-Во время воспроизведения методы хранилищ пропускают `pushOfflineOp`, чтобы не добавлять в очередь операции, которые уже воспроизводятся. Флаг устанавливается перед циклом воспроизведения и сбрасывается в `finally`.
+## Без ручной офлайн-очереди
-## Известные ограничения
+Написанная вручную офлайн-очередь (`components/offline/helpers.ts`, `replay.ts`, `replayHelpers.ts`, `types.ts`) и система ID с префиксом `local_` были удалены. PowerSync предоставляет очередь загрузки нативно. Нет `replay()`, нет `mergeOfflineOps()`, нет `cleanupFrontendIds()`, нет переназначения ID.
-### Порядок кошельков не сохраняется в offline queue
+Клиентские ID - это обычные UUID (генерируются на клиенте). Они стабильны и не требуют переназначения после загрузки.
-`saveWalletsOrder` использует fire-and-forget без offline queue. Если пользователь изменит порядок кошельков в offline и закроет приложение до успешной мутации - порядок будет потерян при следующей загрузке (сервер вернёт старый порядок, pending операции для merge нет).
+## Ключевые файлы
-Это сделано осознанно - сортировка кошельков выполняется редко, а добавление в очередь потребовало бы специального `id: 'order'`, отдельной логики merge в `initWallets` и дополнительной ветки в replay. Эта сложность не оправдана.
+| Файл | Роль |
+|------|------|
+| `app/services/powersync/connector.ts` | `SupabaseConnector.uploadData()` - опустошение очереди, разделение фатальных/повторяемых ошибок |
+| `app/services/powersync/mutations.ts` | `upsertRow`, `deleteRow` - запись в локальную SQLite |
+| `app/services/powersync/db.ts` | `watchTable` - подписка на изменения SQLite |
+| `app/app/plugins/powersync.client.ts` | Регистрирует обработчик ошибок загрузки (toast) |
+| `app/app/components/trns/useTrnsStore.ts` | Оптимистичная запись + откат, каскадное удаление trns |
+| `app/app/components/wallets/useWalletsStore.ts` | Оптимистичная запись + откат + каскадное удаление trns |
+| `app/app/components/categories/useCategoriesStore.ts` | Оптимистичная запись + откат + каскадное удаление trns |
+| `app/app/composables/useStoreSync.ts` | `showErrorToast`, `showSuccessToast`, demo-only `createDebouncedPersist` |
## Следующие шаги
-- [Синхронизация](/ru/development/sync) - дельта-синхронизация и обнаружение удалений по хешу
-- [Тех. решения](/ru/development/tech-decisions) - обоснование fire-and-forget мутаций
+- [Синхронизация](/ru/development/sync) - потоки синхронизации PowerSync, очередь загрузки и обработка удалений
+- [Архитектура](/ru/development/architecture) - инициализация приложения и паттерн хранилищ
diff --git a/docs/content/ru/3.reference/05.tech-decisions.md b/docs/content/ru/3.reference/05.tech-decisions.md
index 7c3fae73..8e4a2d17 100644
--- a/docs/content/ru/3.reference/05.tech-decisions.md
+++ b/docs/content/ru/3.reference/05.tech-decisions.md
@@ -5,60 +5,80 @@ navigation:
icon: i-lucide-lightbulb
seo:
title: Технические решения
- description: Осознанные технические решения в Финапке и их обоснование: синхронизация, оптимистичный UI, система фронтенд-ID, арифметический парсер и каскадное удаление.
+ description: Осознанные технические решения в Финапке и их обоснование - PowerSync offline-first, оптимистичный UI, клиентские UUID, жёсткая навигация при выходе, арифметический парсер и каскадное удаление.
---
Осознанные технические решения и их обоснование.
-## `trns.list` / `trns.delta` - пагинация Convex
+## PowerSync offline-first (локальная SQLite как источник правды)
-`convex/trns.ts` использует встроенный API `.paginate()` Convex. Фронтенд-хелпер `fetchAllPages()` проходит по всем страницам для сбора полного результата.
+Приложение использует PowerSync для репликации Supabase Postgres в локальную WASM SQLite базу данных на клиенте. Сторы читают данные исключительно из этой локальной SQLite через `watchTable('SELECT * FROM ...', [], cb)`.
-**Почему пагинация вместо JSON.stringify:**
-Ранее запросы использовали `JSON.stringify` для обхода лимита Convex в 8 192 элемента массива. Пагинация - стандартный подход Convex: без накладных расходов на сериализацию, с правильной типизацией, нативная обработка больших наборов данных без обходных путей.
+**Почему локальная SQLite как источник правды:**
+Это делает приложение полностью функциональным без подключения к сети. Чтение мгновенно (без round-trip). Одна подписка `watchTable` срабатывает сразу с текущими локальными строками И при каждом изменении - будь то локальная запись или входящая серверная синхронизация. Этот единственный механизм заменяет прежнее разделение между начальной загрузкой и realtime-подпиской.
-## Инкрементальная синхронизация (дельта)
+**Почему PowerSync вместо кастомной офлайн-очереди:**
+В прошлом использовалась написанная вручную офлайн-очередь (`components/offline/replay*`) с XOR-хеш обнаружением удалений, ремапингом локальных ID и пагинированным дельта-запросом. PowerSync делает всё это автоматически: поддерживает локальную CRUD-очередь, сливает её в Supabase через `uploadData` коннектора, согласует серверные изменения через logical replication. Никакого кода очереди, никакой логики несовпадения хешей, никакого ремапинга ID.
-`initTrns()` использует инкрементальную синхронизацию вместо полной загрузки при каждом запуске. Подробнее: [Инкрементальная синхронизация](/ru/development/sync).
+**Почему IDBBatchAtomicVFS (бэкенд IndexedDB) вместо OPFS:**
+OPFS (Origin Private File System) быстрее, но требует `SharedArrayBuffer`, который требует заголовков cross-origin isolation (COOP/COEP). Эти заголовки ломают Google Fonts, Iconify CDN и другие сторонние ресурсы. `IDBBatchAtomicVFS` (на основе IndexedDB) не требует cross-origin isolation и работает в стандартном деплое.
-**Почему не реактивные запросы Convex:**
-Convex поддерживает подписки в реальном времени, но они требуют постоянного WebSocket-соединения и отправляют полный результат запроса при любом изменении. Для 10К+ транзакций это неэффективно. Дельта-синхронизация загружает только изменённые записи.
+## Оптимистичные записи с откатом
-**Почему несовпадение хешей → fullSync вместо запроса ids:**
-Ранее обнаружение удалений использовало отдельный запрос `trns.ids` для загрузки всех ID и поиска удалённых. Этот запрос был сломан при 8 000+ транзакциях (упирался в лимит 8 192 элемента массива). Новый подход: после применения дельта вычислить локальный XOR-хеш и сравнить с серверным. При несовпадении - откат на `fullSync()`. Удаления редки (1-2 в месяц), поэтому разовая полная синхронизация - приемлемый компромисс, проще и надёжнее поддержки пагинированного запроса ID.
+Методы сторов немедленно обновляют `items` (оптимистично), затем вызывают `upsertRow`/`deleteRow` для записи в локальную SQLite. Если локальная запись падает, оптимистичное изменение откатывается путём восстановления снимка `prev`, и показывается тост с ошибкой.
-**Почему не soft-delete:**
-Soft-delete (поле `deletedAt`) потребовал бы миграции всех существующих данных, модификации всех запросов для фильтрации удалённых записей и периодической очистки. Обнаружение на основе хешей проще и не требует изменений схемы.
+**Почему оптимистично, а не с ожиданием:**
+Ожидание записи в SQLite блокировало бы UI, даже несмотря на то что это локальная внутрипроцессная операция. Оптимистичные обновления дают мгновенную обратную связь. Путь отката обрабатывает редкий случай, когда сама локальная запись завершается ошибкой (например, конфликт транзакции).
-**Почему дельта-синхронизация только для транзакций:**
-Категории и кошельки - маленькие наборы данных (десятки-сотни записей). Полная синхронизация достаточно быстра. Транзакции - единственная сущность, которая растёт до тысяч записей.
+**Замечание об отклонении сервером:** серверные ошибки (нарушения RLS Postgres, исключения данных) выводятся отдельно - через обработчик upload-error в `uploadData` коннектора, а не через catch локальной записи.
-## Оптимистичный UI с fire-and-forget мутациями
+## `shallowRef` для элементов сторов
-Методы хранилища обновляют UI немедленно, затем запускают мутации Convex без ожидания. [Офлайн-очередь](/ru/development/offline-queue) фиксирует каждую операцию, поэтому ничего не теряется даже при ошибке мутации.
+Все Pinia-сторы используют `shallowRef<Map | null>` вместо `ref` для коллекции элементов. Методы сторов создают новые ссылки на объекты при каждой мутации для запуска реактивности.
-**Почему fire-and-forget:**
-Ожидание мутаций блокировало бы UI и делало приложение медленным. Оптимистичные обновления дают мгновенную обратную связь. Механизм офлайн-очереди + воспроизведения обеспечивает итоговую согласованность.
+**Почему:**
+`ref` глубоко отслеживал бы каждое вложенное свойство потенциально тысяч объектов транзакций/кошельков/категорий. `shallowRef` отслеживает только ссылку верхнего уровня. Явный паттерн «создать новый объект» при записи - осознанный компромисс: чуть более многословные сторы, значительно меньшие накладные расходы реактивности.
+
+## Клиентские UUID (без префикса `local_`, без ремапинга)
+
+Каждая новая сущность получает UUID, сгенерированный на клиенте (`crypto.randomUUID()` или аналог) до локальной записи. Этот UUID является постоянным ID - нет временного префикса `local_` и нет ремапинга после подтверждения от сервера.
+
+**Почему не `local_` ID:**
+В прошлом использовался временный префикс `local_abc123`, который потом переназначался на серверный ID после успешной мутации. Это требовало отслеживания ожидающих ремапов ID во всех сторах и каскадных обновлений (например, транзакции, ссылающиеся на новый кошелёк). С PowerSync клиент владеет ID навсегда: схема Supabase использует `text` PK с `default gen_random_uuid()::text`, поэтому любой UUID, сгенерированный клиентом, принимается как есть. Нет ремапинга, нет каскадной сложности.
+
+**Почему нет FK-ограничений в Postgres:**
+Порядок загрузки PowerSync не гарантирован. Транзакция, ссылающаяся на кошелёк, может быть загружена раньше самого кошелька. FK-ограничения отклонили бы валидные данные. Ссылочная целостность обеспечивается логикой приложения.
+
+## SQLite views требуют INSERT/UPDATE, а не upsert
-**Почему `shallowRef` для элементов хранилища:**
-Все Pinia-хранилища используют `shallowRef` вместо `ref` для карты элементов. Это позволяет избежать глубокого отслеживания реактивности на потенциально тысячах объектов, значительно улучшая производительность. Методы хранилища создают новые ссылки на объекты при мутации для запуска реактивности.
+Клиентские таблицы PowerSync - это SQLite views с INSTEAD OF триггерами. Они принимают обычные `INSERT` и `UPDATE`, но НЕ поддерживают `INSERT ... ON CONFLICT` (синтаксис upsert).
-## Система Frontend ID
+**Как `upsertRow` это решает:**
+Выполняет проверку существования, затем либо `INSERT` (новая строка), либо `UPDATE` (существующая), обёрнутые в `writeTransaction` для атомарности. Вызывающий всегда владеет ID, поэтому INSERT/UPDATE однозначны.
-Новые сущности получают временные ID с префиксом `local_` (например, `local_a1b2c3`). После успешного создания на сервере ID переназначается на Convex ID. Полный жизненный цикл: [Офлайн-очередь - Система Frontend ID](/ru/development/offline-queue#система-frontend-id).
+## Троттлинг `reconcileTrns` и подавление изменений
-**Почему префикс `local_`:**
-Явный префикс делает намерение понятным в коде - `isLocalId(id)` проверяет `id.startsWith('local_')`. Нет зависимости от внутреннего формата Convex ID.
+`useTrnsStore` использует 120ms окно троттлинга для своего `watchTable` (против 30ms по умолчанию для других таблиц). Также используется `reconcileTrns` для подавления «эха» собственной оптимистичной записи.
-**Почему не UUID:**
-Короткий случайный суффикс достаточен для однопользовательского приложения. UUID длиннее и сложнее читать в логах.
+**Почему большее окно троттлинга:**
+Транзакции - самая большая таблица. Во время начальной синхронизации PowerSync генерирует много быстрых событий изменения строк. 120ms trailing coalesce сворачивает всплеск в один перезапрос, снижая нагрузку на CPU.
+
+**Почему `reconcileTrns`:**
+После оптимистичной записи watch снова срабатывает с теми же данными (эхо записи). `reconcileTrns` обнаруживает, что ничего не изменилось (сравнивая по `updatedAt`), и возвращает тот же `prev` ref без изменений, подавляя лишний цикл реактивности. Также переиспользует неизменённые объекты строк, так что `rowToTrn` выполняется только для дельты.
+
+## Очистка перед подключением другого пользователя (fail-closed)
+
+`connectPowerSync` проверяет хранящийся `finapp.psDbOwnerUid` (localStorage). Если локальная SQLite принадлежит другому пользователю, вызывается `disconnectAndClear()` перед подключением - сначала очищается локальная база данных.
+
+**Почему fail-closed:**
+Если сама очистка завершается ошибкой, маркер владельца сохраняется. Следующая сессия другого пользователя всё равно попытается очиститься перед чтением данных. Это предотвращает утечку данных пользователя A к пользователю B на общем устройстве.
## Жёсткая навигация при выходе
Выход из системы использует `window.location.href = '/login'` вместо навигации Vue Router.
**Почему:**
-Жёсткая навигация уничтожает всё JavaScript-состояние - Pinia-хранилища, WebSocket-соединения, реактивные наблюдатели, кешированные данные. Это предотвращает утечку устаревшего состояния авторизации в следующую сессию. `navigateTo()` Vue Router сохранил бы всё состояние в памяти.
+Жёсткая навигация уничтожает всё JavaScript-состояние - Pinia-сторы, WebSocket-соединения, реактивные наблюдатели, кешированные данные. Это предотвращает утечку устаревшего состояния авторизации в следующую сессию. `navigateTo()` Vue Router сохранил бы всё состояние в памяти.
## Безопасный арифметический парсер в калькуляторе
@@ -67,12 +87,12 @@ Soft-delete (поле `deletedAt`) потребовал бы миграции в
**Почему:**
`new Function(expression)` - вектор инъекции кода: вредоносная строка может выполнить произвольный JavaScript. Также требует `unsafe-eval` в Content-Security-Policy. Кастомный парсер поддерживает только `+`, `-`, `*`, `/` над числовыми литералами, отклоняя всё остальное.
-## Каскадное удаление в Convex
+## Каскадное удаление в сторах
-Convex не имеет ограничений внешних ключей, поэтому каскадное удаление выполняется вручную - `wallets.remove` и `categories.remove` удаляют все связанные транзакции в одной мутации. Фронтенд отправляет только удаление родительской сущности в [офлайн-очередь](/ru/development/offline-queue#каскадное-удаление-на-бэкенде).
+Postgres не имеет FK-ограничений (см. выше). При вызове `deleteWallet`/`deleteCategory` стор также удаляет транзакции сущности из локальной SQLite (иначе подписка watch снова добавила бы их на следующем такте). При откате восстанавливаются и сущность, и её транзакции.
-**Почему пагинированными батчами (500 элементов):**
-Convex ограничивает количество записанных документов за транзакцию до 16 000. Кошелёк с тысячами транзакций может превысить этот лимит в одной мутации. Каскадное удаление теперь пагинируется: получить батч из 500 ID транзакций, удалить их, повторить пока не останется ни одной, затем удалить родительскую сущность.
+**Почему не полагаться на серверный каскад:**
+Серверного каскада нет (нет FK-ограничений). Клиент должен очищать локально, чтобы локальное SQLite-представление оставалось консистентным с предполагаемым состоянием.
## Вычисляемые дочерние категории вместо денормализованных `childIds`
@@ -83,7 +103,7 @@ Convex ограничивает количество записанных док
## Ограничение вложенности категорий до 2 уровней
-Категории поддерживают только родитель → дочерний, без более глубокой вложенности.
+Категории поддерживают только родитель - дочерний, без более глубокой вложенности.
**Почему:**
Более глубокая вложенность усложняет UI (разбивка статистики, выбор категорий, хлебные крошки) без практической пользы для учёта личных финансов. Два уровня покрывают 99% случаев использования (например, Еда > Продукты).
@@ -93,21 +113,10 @@ Convex ограничивает количество записанных док
Стили темы используют `tagPriority: -2` в `useHead()`, а скрипты плагинов используют `tagPriority: -1`.
**Почему:**
-Это гарантирует применение CSS-переменных темы до первой отрисовки. Цепочка приоритетов: `useHead` стили (-2) → скрипты плагинов (-1) → `@layer theme` (всегда проигрывает non-layered). Non-layered CSS в `theme.css` переопределил бы `useHead()` порядком в документе, поэтому `--ui-radius` и `--ui-primary` не должны устанавливаться там.
-
-## Лимиты Convex
-
-Справка ([документация](https://docs.convex.dev/production/state/limits)):
-- Возвращаемое значение функции: 16 МиБ
-- Чтение данных за транзакцию: 16 МиБ
-- Просканированных документов за запрос: 32 000
-- Размер документа: 1 МиБ
-- Элементов массива в документе: 8 192
-- Записанных документов за транзакцию: 16 000
-- Время выполнения запроса: 1 сек (пользовательский код, исключая операции БД)
+Это гарантирует применение CSS-переменных темы до первой отрисовки. Цепочка приоритетов: `useHead` стили (-2) - скрипты плагинов (-1) - `@layer theme` (всегда проигрывает non-layered). Non-layered CSS в `theme.css` переопределил бы `useHead()` порядком в документе, поэтому `--ui-radius` и `--ui-primary` не должны устанавливаться там.
## Следующие шаги
- [Дата-утилиты](/ru/development/date-utilities) - типобезопасная работа с периодами, интервалы, форматирование
-- [Стратегия валидации](/ru/development/validation-strategy) - двойная валидация с Zod и Convex
+- [Стратегия валидации](/ru/development/validation-strategy) - клиентская валидация с Zod
- [Архитектура](/ru/development/architecture) - как решения влияют на структуру проекта
diff --git a/docs/content/ru/3.reference/06.validation-strategy.md b/docs/content/ru/3.reference/06.validation-strategy.md
index d27d6109..ae853bbf 100644
--- a/docs/content/ru/3.reference/06.validation-strategy.md
+++ b/docs/content/ru/3.reference/06.validation-strategy.md
@@ -1,102 +1,60 @@
---
title: Валидация
-description: Двойная валидация и планы на будущее.
+description: Клиентская валидация и компромиссы.
navigation:
icon: i-lucide-shield-check
seo:
title: Стратегия валидации
- description: Двойная валидация в Финапке: Zod на клиенте и нативная валидация Convex на сервере. Почему константы продублированы и когда стоит пересмотреть подход.
+ description: В Финапке используется только клиентская валидация с Zod v4. Где живут схемы, что каждая из них проверяет и что обеспечивает сервер.
---
-## Текущий подход: двойная валидация
+## Текущий подход: только клиентская валидация
-В проекте две независимые системы валидации:
+Валидация выполняется **только на клиенте**. Серверных валидаторов бизнес-правил нет. Сервер (Supabase Postgres) обеспечивает только типы колонок, ограничения NOT NULL, политики RLS для владельца строк и правила синхронизации по пользователям.
| Слой | Фреймворк | Назначение |
|------|-----------|------------|
-| **Клиент** (браузер) | Zod v4 | UX форм - дефолты, трим, мгновенные ошибки |
-| **Сервер** (Convex) | `convex/values` (`v.*`) | Целостность данных - типизированные ID-ссылки, проверка владельца |
+| **Клиент** (браузер) | Zod v4 | UX форм - дефолты, трим, мгновенные ошибки; проверка формата данных на рантайме |
+| **Сервер** (Supabase Postgres) | Типы колонок + RLS | Типы колонок, NOT NULL, владелец строки (политика RLS) |
### Где живёт валидация
-| Сущность | Convex-валидаторы | Zod-схемы |
-|----------|-------------------|-----------|
-| Кошельки | `convex/wallets.ts`, `convex/schema.ts` | `app/components/wallets/types.ts` |
-| Категории | `convex/categories.ts`, `convex/schema.ts` | `app/components/categories/types.ts` |
-| Транзакции | `convex/trns.ts`, `convex/schema.ts` | `app/components/trns/types.ts` |
-| Настройки | `convex/userSettings.ts` | - (нет клиентской схемы) |
-| Курсы валют | `convex/rates.ts` | - (нет клиентской схемы) |
-| Конфиг статистики | - | `app/components/stat/useStatConfig.ts` |
-| Параметры дат | - | `app/components/date/useStatDate.ts` |
+| Сущность / применение | Zod-схема |
+|----------------------|-----------|
+| Форма транзакции | `app/app/components/trns/types.ts` (`trnItemSchema`, `transactionSchema`) + `app/app/components/trnForm/utils/validate.ts` |
+| Конфиг статистики | `app/app/components/stat/useStatConfig.ts` (`ConfigSchema`) |
+| Дата / query-параметры | `app/app/components/date/statDateParams.ts` (`queryParamsSchema`) |
+| Настройки пользователя | `app/app/components/user/types.ts` (`userSettingsSchema`) |
+| Формат курсов валют | `app/app/components/currencies/types.ts` (`ratesSchema`) |
+| Локаль | `app/app/components/locale/types.ts` (`localeSchema`) |
-### Что валидирует каждая сторона
+### Что проверяет каждая сторона
-**Zod (только клиент):**
-- `.trim().min(1)` на имени/иконке - не пропускает пустые после трима
+**Zod (клиент):**
+- `.trim().min(1)` - не пропускает пустые строки после трима
- `.positive()` на суммах
- `.default()` для начальных значений форм
-- `.transform()` для парсинга query-параметров (строка → число)
+- `.transform()` для парсинга query-параметров (строка в число / булево)
+- Discriminated union для типа транзакции (`trnItemSchema` = `transactionSchema | transferSchema`)
+- Проверка одинаковых кошельков перевода: `incomeWalletId !== expenseWalletId`
-**Convex (только сервер):**
-- `v.id('wallets')`, `v.id('categories')` - типизированные ссылки на записи
-- Проверка владельца сущности (`userId`)
-- Защита от циклических ссылок в категориях
-- Уникальность имени категории в рамках родителя
-- Ограничение вложенности категорий (2 уровня)
-- Проверка что кошельки трансфера различаются
-- Лимиты длины строк: name (100), description (500), icon (50), color (50), currency (10)
-- Числовые диапазоны: amount (макс. 1 трлн), creditLimit (макс. 1 млрд), date (2000–2099)
-- Контроль `categoryId`: для Transfer обязателен `'transfer'`, для не-Transfer запрещён `'transfer'`
+**Supabase Postgres (сервер):**
+- Типы колонок: `text`, `numeric`, `integer`, `boolean`, `jsonb`
+- `NOT NULL` на обязательных колонках
+- RLS: каждая пользовательская таблица имеет `(select auth.uid())::text = "userId"` - строки других пользователей невидимы, запись отклоняется
+- Таблица `rates` доступна только для чтения аутентифицированным пользователям (без записи с клиента)
+- Триггер автоматически создаёт `user_settings` при регистрации (начальная инициализация на сервере не нужна)
-**Обе стороны (дублирование ~40%):**
-- Наличие / опциональность полей
-- Базовые проверки типов (string, number, boolean)
-- Валидация union / literal (TrnType, WalletType)
+**Серверных валидаторов бизнес-правил нет** (нет серверных ограничений длины строк, диапазонов чисел, кросс-полевой валидации). Эти правила живут только в Zod-схемах на клиенте.
-### Почему константы дублируются
+### Компромисс
-Enum `TrnType` и массив `walletTypes` определены независимо на каждой стороне:
-- `convex/validators.ts` - для сервера (импортирует `v` из `convex/values`)
-- `app/components/trns/types.ts` / `app/components/wallets/types.ts` - для клиента
+Целенаправленный клиент, обходящий форму, может записать произвольные данные в локальную SQLite, которые PowerSync загрузит в Supabase. Postgres примет их, если они проходят типы колонок и RLS. Это осознанный компромисс для однопользовательского приложения личных финансов - дублирование каждого бизнес-правила в виде Postgres-ограничений или политик RLS не оправдано по трудозатратам.
-Импорт из директории `convex/` в браузерный код тянет серверные модули (`_generated/server`, auth) и вызывает предупреждение «Convex functions should not be imported in the browser». Подробнее в [технических решениях](/ru/development/tech-decisions).
-
-## Рассмотренные альтернативы
-
-### fluent-convex + общие Zod-схемы
-
-[fluent-convex](https://github.com/mikecann/fluent-convex) (v0.x) - fluent API для Convex-функций с Zod-плагином, который автоматически конвертирует Zod-схемы в Convex-валидаторы.
-
-**Что бы дало:** одна Zod-схема, используемая и на клиенте, и на сервере.
-
-**Отклонено, потому что:**
-- Библиотека экспериментальная (v0.x, один автор, 90 звёзд)
-- `v.id('wallets')` не имеет аналога в Zod - теряются типизированные ID-ссылки
-- `schema.ts` (определение таблиц) всё равно остаётся на `v.*`
-- Дополнительная зависимость: `convex-helpers` как peer dep
-
-### Общие Zod-схемы с ручной конвертацией через convex-helpers
-
-Определить Zod-схемы в директории `shared/`. Клиент использует напрямую. Сервер конвертирует через `convex-helpers/server/zod`.
-
-**Что бы дало:** единый источник правды без зависимости от fluent-convex.
-
-**Отклонено, потому что:**
-- Та же проблема с `v.id()` - нет Zod-эквивалента
-- Нужно настраивать tsconfig Convex для импорта из-за пределов `convex/`
-- Бойлерплейт для ручной конвертации Zod → Convex
-- Минимальная выгода для 3 стабильных сущностей с ~15 полями каждая
-
-## Решение
-
-Оставить двойную валидацию. Дублирование невелико (~15 полей × 3 сущности), схемы меняются редко, и каждая сторона решает свою задачу:
-- **Zod** = UX (дефолты, трансформации, мгновенная обратная связь)
-- **Convex** = целостность (ID-ссылки, владелец, бизнес-правила)
-
-### Когда пересмотреть
-
-- Поддержка `v.id()` в `convex-helpers/server/zod`
-- Выход fluent-convex v1.0 со стабильным API
+Если в будущем потребуется более строгая проверка, варианты:
+- Postgres `CHECK` ограничения для диапазонов и длин
+- Supabase Edge Function как прокси загрузки с серверной Zod-валидацией
+- Оценка, покрывает ли встроенная валидация Supabase (pg_jsonschema, check constraints) критические правила
## Следующие шаги
diff --git a/docs/content/ru/3.reference/07.convex-migration.md b/docs/content/ru/3.reference/07.convex-migration.md
index dea9261e..61fea312 100644
--- a/docs/content/ru/3.reference/07.convex-migration.md
+++ b/docs/content/ru/3.reference/07.convex-migration.md
@@ -1,18 +1,25 @@
---
title: На Convex
-description: Что изменилось между v6 (Firebase) и v7 (Convex).
+description: Что изменилось между v6 (Firebase) и v7 (Convex). Convex впоследствии заменён Supabase + PowerSync.
navigation:
icon: i-lucide-hamburger
seo:
title: Миграция на Convex - что изменилось
- description: Подробное сравнение Finapp v6 (Firebase) и v7 (Convex): изменения бэкенда, производительность, безопасность, тесты, рефакторинг и архитектура.
+ description: Подробное сравнение Finapp v6 (Firebase) и v7 (Convex) - изменения бэкенда, производительность, безопасность, тесты, рефакторинг и архитектура. Историческая справка.
---
-Сравнение конечного состояния приложения на `main` (v6, Firebase) и `convex` (v7, Convex).
+> **Три эпохи.** Финапка прошла через три поколения бэкенда:
+> - **v6** - Firebase Realtime Database + Firebase Auth
+> - **v7** - Convex (backend-as-code) + Better Auth (описано в этом документе)
+> - **текущий** - Supabase Postgres + PowerSync (offline-first) + Supabase Auth
+>
+> Этот документ - историческое сравнение миграции с Firebase на Convex. Улучшения на уровне приложения (производительность, рефакторинг, UX, TypeScript, i18n), описанные здесь, по-прежнему актуальны и присутствуют в текущей кодовой базе. Разделы бэкенда, авторизации, офлайн-очереди и зависимостей отражают состояние v7 Convex; см. [Архитектуру](/ru/development/architecture) для текущей архитектуры Supabase + PowerSync.
+
+Сравнение конечного состояния приложения на `firebase`-ветке (v6, Firebase) и в эпоху Convex (v7).
## Бэкенд
-| | main (Firebase) | convex |
+| | firebase (Firebase) | v7 (Convex) |
|---|---|---|
| **База данных** | Firebase Realtime Database | Convex (backend-as-code) |
| **Авторизация** | Firebase Auth через `nuxt-vuefire` | Better Auth + `@convex-dev/better-auth` |
@@ -22,27 +29,27 @@ seo:
| **Курсы валют** | Клиентский запрос | Серверный крон (ежедневно в 6:00 UTC) + таблица `rates` |
| **Настройки пользователя** | Только localStorage | Convex-таблица `userSettings` (baseCurrency, locale) с офлайн-очередью |
| **Индексы схемы** | N/A | Составные индексы: `by_user_date`, `by_user_wallet`, `by_user_category` для эффективных запросов |
-| **Миграция** | N/A | `utils/migrate/firebase.js` &mdash; CLI для импорта JSON-экспортов Firebase в Convex |
-| **Удаление аккаунта** | N/A | `deleteUserDataFull()` &mdash; пагинированная очистка таблиц приложения + авторизации |
+| **Миграция** | N/A | `utils/migrate/firebase.js` - CLI для импорта JSON-экспортов Firebase в Convex |
+| **Удаление аккаунта** | N/A | `deleteUserDataFull()` - пагинированная очистка таблиц приложения + авторизации |
-### Что даёт Convex
+### Что давал Convex
-- **Типизированные мутации** &mdash; полный TypeScript на обеих сторонах, автогенерация API-типов
-- **Серверная валидация** &mdash; лимиты длины строк, диапазоны чисел, непустота полей, бизнес-правила (см. [Стратегия валидации](/ru/development/validation-strategy))
+- **Типизированные мутации** - полный TypeScript на обеих сторонах, автогенерация API-типов
+- **Серверная валидация** - лимиты длины строк, диапазоны чисел, непустота полей, бизнес-правила
- **Один WebSocket** для всех операций (запросы, мутации, авторизация)
- **Пагинация** через `.paginate()` API для больших наборов данных (транзакции)
-- **Дельта-синхронизация** &mdash; после начальной загрузки запрашиваются только изменённые записи (см. [Синхронизация](/ru/development/sync))
+- **Дельта-синхронизация** - после начальной загрузки запрашиваются только изменённые записи
## Паттерн сторов
-| | main | convex |
+| | firebase | v7 (Convex) |
|---|---|---|
-| **Источник данных** | Firebase listener &rarr; `setTrns()` | Convex query &rarr; `mergeOfflineOps()` &rarr; `set()` |
+| **Источник данных** | Firebase listener -> `setTrns()` | Convex query -> `mergeOfflineOps()` -> `set()` |
| **Persist** | `deepUnref()` + немедленный `localforage.setItem()` | Debounced 300ms `localforage.setItem()` (без глубокого клонирования) |
| **Офлайн-операции** | Ручные хелперы в `trns/helpers.ts`, произвольные ключи localStorage | Явная очередь: `pushSaveOp()`, `pushDeleteOp()`, `replay()` |
-| **Система ID** | Firebase push ID | Префикс `local_` &rarr; замена на Convex ID после мутации |
-| **Оптимистичный UI** | Частичный (fire-and-forget) | Полный: обновить UI &rarr; push op &rarr; fire mutation &rarr; remap ID при успехе |
-| **Верификация синхронизации** | Нет | XOR-хеш (`fnv1a`) ID транзакций; сравнение хешей клиент &harr; сервер при каждой синхронизации |
+| **Система ID** | Firebase push ID | Префикс `local_` -> замена на Convex ID после мутации |
+| **Оптимистичный UI** | Частичный (fire-and-forget) | Полный: обновить UI -> push op -> fire mutation -> remap ID при успехе |
+| **Верификация синхронизации** | Нет | XOR-хеш (`fnv1a`) ID транзакций; сравнение хешей клиент - сервер при каждой синхронизации |
Зависимость `vue-deepunref` удалена. Данные сторов используют `shallowRef`, поэтому глубокое клонирование при каждом persist было лишним.
@@ -50,9 +57,9 @@ seo:
### Алгоритмические улучшения
-| Что | main | convex | Эффект |
-|-----|------|--------|--------|
-| **Итоги кошельков** | `getWalletTotal(id)` вызывается для каждого кошелька в `reduce` &mdash; каждый вызов фильтрует все транзакции: O(W&times;N) | `getWalletsTotals()` один проход, распределение через `Map`: O(N), затем O(1) для каждого кошелька | 5 кошельков &times; 10K трн: ~50K &rarr; ~10K операций |
+| Что | firebase | v7 (Convex) | Эффект |
+|-----|----------|------|--------|
+| **Итоги кошельков** | `getWalletTotal(id)` вызывается для каждого кошелька в `reduce` - каждый вызов фильтрует все транзакции: O(W&times;N) | `getWalletsTotals()` один проход, распределение через `Map`: O(N), затем O(1) для каждого кошелька | 5 кошельков &times; 10K трн: ~50K &rarr; ~10K операций |
| **Разбивка по интервалам** | Инлайн в `Item.vue`: `intervalsInRange.reduce()` фильтрует все транзакции на каждый интервал: O(N&times;I) | Извлечено в `bucketTrnsByIntervals()`: один проход + бинарный поиск: O(N&nbsp;log&nbsp;I) | Год/365 дней/5K трн: 1.8M &rarr; ~43K сравнений |
| **Фильтрация транзакций** | 6 последовательных `.filter()` через `reduce` + `walletsIds.some(w => includes(w))` O(W&sup2;) + сортировка всегда O(N&nbsp;log&nbsp;N) | Один `.filter()` с ранним выходом + `Set.has()` O(1) + сортировка опциональна | 5 промежуточных массивов + O(W&sup2;) &rarr; один проход + O(1); сортировка O(N&nbsp;log&nbsp;N) пропускается когда не нужна |
| **Поиск кошелька в getTotal** | `walletsIds.includes()`: O(W) на каждый перевод | `new Set(walletsIds).has()`: O(1) на каждый перевод | Линейный &rarr; константный на каждый вызов |
@@ -60,7 +67,7 @@ seo:
| **Статистика категорий** | `categoriesStat` жадно вычисляет и `grouped`, и `ungrouped` на каждое изменение; `filter().at(0)` для наибольшей | Ленивый `computed()` на каждый вариант, выполняется только при обращении; `.find()` останавливается на первом совпадении | До 2&times; меньше вызовов `computeCategoriesWithData` |
| **Фильтр вертикальных категорий** | `verticalCategories.filter(c => c.value !== 0)` вызывается дважды в шаблоне (заголовок + v-for): пересчитывается на каждый рендер | Кеширован в `visibleVerticalCategories` computed: фильтрация один раз, переиспользование | 2 прохода фильтра &rarr; 1 кешированный |
| **Форматирование чисел** | Библиотека `currency.js` + `currencies.find()` O(N) дважды на вызов | Нативный `Intl.NumberFormat` с кешем в `Map` + `currencyMap.get()` O(1) | Нет зависимости; форматтер создаётся один раз на precision |
-| **Последняя транзакция** | `Object.keys().sort().find()` &mdash; сортирует все транзакции O(N&nbsp;log&nbsp;N) затем ищет | Один проход O(N), отслеживая максимальную дату | 10K трн: ~130K ops &rarr; ~10K ops |
+| **Последняя транзакция** | `Object.keys().sort().find()` - сортирует все транзакции O(N&nbsp;log&nbsp;N) затем ищет | Один проход O(N), отслеживая максимальную дату | 10K трн: ~130K ops &rarr; ~10K ops |
| **Проверка родителя категории** | `categoriesForBeParent` вызывает `Object.values(trns).some()` O(N) на каждую корневую категорию: O(M&times;N) | Предготовленный `usedCategoryIds` Set через `for...in` O(N) + `Set.has()` O(1) на проверку; без промежуточных массивов | 200 категорий &times; 10K трн: ~2M &rarr; ~10K ops |
| **Недавние категории** | `Object.keys(trns).filter().sort()` O(N&nbsp;log&nbsp;N) + `acc.some(c => c.id)` O(K&sup2;) дедупликация + `includes()` O(W) на категорию | Один проход O(N) через `Map` с последней датой + `entries().toSorted()` O(K&nbsp;log&nbsp;K) + `Set.has()` O(1) | 10K трн: ~130K + K&sup2; &rarr; ~10K + K&nbsp;log&nbsp;K ops |
| **Транзактируемые категории** | `.reduce()` с `acc.includes()` O(M) + `childIds.filter(!acc.includes)` O(C&times;M): O(M&sup2;) | `Map<parentId, childIds[]>` за O(M) + `Set` дедупликация O(1) на проверку | 200 категорий: ~40K &rarr; ~200 ops |
@@ -70,9 +77,9 @@ seo:
| **Кеш итогов групп** | `getTotalOfTrnsIds()` вызывается дважды на группу в шаблоне (доход + расход): O(2G) вызовов | Предвычисленная `groupTotals` Map + `paginatedTotal` computed: O(G) вычислений + O(1) обращения | 15 групп: ~30 &rarr; ~15 вычислений итогов на рендер |
| **Сортировка при группировке** | `categories.sort()` вызывается внутри `reduce` на каждый `.push()` дочерней категории: O(K&sup2;&nbsp;log&nbsp;K) на родителя | Сортировка один раз после цикла, только если `length > 1`: O(K&nbsp;log&nbsp;K) на родителя | 5 детей: ~50 &rarr; ~12 сравнений |
| **Итоги при группировке** | `getTotalOfTrnsIds(cat.trnsIds).sum` вызывается дважды на дочернюю категорию (для значения + суммы родителя) | Вычисляется один раз в `catTotal`, переиспользуется: один вызов на дочернюю | 2&times; меньше вызовов `getTotal` на дочернюю категорию |
-| **Синхронизация данных** | Firebase: полная замена данных на каждое обновление: O(N) | Дельта-синхронизация: запрашиваются только изменённые записи &mdash; O(D) где D &laquo; N | Не обрабатывает неизменённые транзакции |
+| **Синхронизация данных** | Firebase: полная замена данных на каждое обновление: O(N) | Дельта-синхронизация: запрашиваются только изменённые записи - O(D) где D &laquo; N | Не обрабатывает неизменённые транзакции |
| **Генерация интервалов** | `list.unshift(current)` в цикле while: O(n) на вызов, O(n&sup2;) всего | `list.push(current)` + `list.reverse()`: O(1) на вызов, O(n) всего | Год/365 дней: ~66K сдвигов &rarr; ~365 push + 1 reverse |
-| **Ключи Duration** | Динамический `{ [\`${period}s\`]: value }` &mdash; TS видит `Record<string, number>`, нет проверки типа `Duration` | `toDuration(period, value)` возвращает типизированный `Duration` через exhaustive switch | Безопасность на этапе компиляции; новые варианты периодов вызывают ошибки, а не молчаливый fallback |
+| **Ключи Duration** | Динамический `{ [\`${period}s\`]: value }` - TS видит `Record<string, number>`, нет проверки типа `Duration` | `toDuration(period, value)` возвращает типизированный `Duration` через exhaustive switch | Безопасность на этапе компиляции; новые варианты периодов вызывают ошибки, а не молчаливый fallback |
| **Форматирование дат** | Каждая format-функция вызывается дважды (`type: 'start'` + `type: 'end'`), результаты конкатенируются; 3 IIFE switch-блока для сравнения периодов | Каждая format-функция возвращает полную строку; `isSamePeriod(a, b, period)` заменяет все 3 switch-блока | ~40% меньше строк в `useGetDateRange`; без двойных вызовов |
| **Вычисление средних** | `sum !== 0` проверяется 3 раза + `Object.keys(items).length > 0` гард | Ранний выход при `sum === 0`; среднее за день всегда присутствует (диапазон &ge; 2 гарантирован) | 1 проверка вместо 4 |
| **Сортировка избранных категорий** | Инлайн-сортировка дублирует логику parent-name + name (8 строк) | Переиспользует утилиту `compareCategoriesByParentAndName` (1 строка) | DRY; одна реализация сортировки |
@@ -84,11 +91,11 @@ seo:
### Бандл и рендеринг
-| Что | main | convex |
-|-----|------|--------|
+| Что | firebase | v7 (Convex) |
+|-----|----------|------|
| **ECharts** | 9 компонентов в основном бандле (вкл. PieChart, DataZoom, MarkPoint) | 7 компонентов в lazy-загружаемом async-чанке (неиспользуемые удалены) |
| **Плагин темы** | 81 строка с SSR инлайн-скриптами и regex-заменами | 32 строки, SPA-only обновление `appConfig` из localStorage |
-| **Persist** | `deepUnref()` на каждый `localforage.setItem()` &mdash; полное рекурсивное клонирование | Прямая запись, debounce 300ms, без клонирования |
+| **Persist** | `deepUnref()` на каждый `localforage.setItem()` - полное рекурсивное клонирование | Прямая запись, debounce 300ms, без клонирования |
| **Адаптивная вёрстка** | JS-слушатель `useWindowSize()` для sidebar | CSS `sm:` / `md:` Tailwind брейкпоинты |
| **Container queries** | Только media queries | CSS container queries (`@xl/page:`, `@md/page:`) для адаптивных размеров относительно контейнера |
| **Зависимости** | `currency.js` для форматирования чисел | Нативный `Intl.NumberFormat` (без зависимости) |
@@ -97,23 +104,25 @@ seo:
## Безопасность
-| Что | main | convex |
-|-----|------|--------|
-| **Парсер калькулятора** | `new Function(expression)` &mdash; риск инъекции кода, требует `unsafe-eval` CSP | Рекурсивный парсер &mdash; только `+`,`-`,`*`,`/` над числами |
+| Что | firebase | v7 (Convex) |
+|-----|----------|------|
+| **Парсер калькулятора** | `new Function(expression)` - риск инъекции кода, требует `unsafe-eval` CSP | Рекурсивный парсер - только `+`,`-`,`*`,`/` над числами |
| **Валидация ввода** | Firebase rules (клиент не может проверить) | Convex-валидаторы: лимиты строк, диапазоны чисел, проверки полей |
| **Токены авторизации** | Управляются Firebase | Шифруются at rest (`encryptOAuthTokens: true`) |
| **Время жизни сессии** | По умолчанию Firebase | 30 дней, ежедневное обновление |
| **Каскадные удаления** | N/A (Firebase) | Пагинированные батчи по 500 (лимит Convex 16K записей) |
-| **Целостность данных** | Не проверяется в коде | Transfer &harr; `categoryId='transfer'`, нормализация при смене типа, уникальность имён |
-| **Защита редиректов** | Без валидации | `getSafeRedirectPath()` &mdash; только относительные пути, начинающиеся с `/` (не `//`) |
+| **Целостность данных** | Не проверяется в коде | Transfer - `categoryId='transfer'`, нормализация при смене типа, уникальность имён |
+| **Защита редиректов** | Без валидации | `getSafeRedirectPath()` - только относительные пути, начинающиеся с `/` (не `//`) |
## Авторизация
-| | main | convex |
+_(Историческая справка - описывает эпоху v7 Convex. Текущая авторизация: Supabase Auth, только email/password. См. [Архитектуру](/ru/development/architecture).)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Провайдер** | Firebase Auth | Better Auth |
-| **Плагин** | `nuxt-vuefire` (авто-управление авторизацией) | `plugins/convex.ts` &mdash; ручной жизненный цикл |
-| **Поток токенов** | Внутри Firebase SDK | `setAuth(fetchToken)` &rarr; `authClient.convex.token()` &rarr; `authReadyPromise` |
+| **Плагин** | `nuxt-vuefire` (авто-управление авторизацией) | `plugins/convex.ts` - ручной жизненный цикл |
+| **Поток токенов** | Внутри Firebase SDK | `setAuth(fetchToken)` -> `authClient.convex.token()` -> `authReadyPromise` |
| **Офлайн** | Firebase SDK управляет реконнектом | Watch сессии игнорирует `error`/`isPending`, пропускает запрос токена офлайн, событие `online` запускает fresh auth |
| **Подсказка состояния** | Нет | Кука `finapp.localAuthUid` (синхронная проверка, без сети) |
| **Callback** | Firebase redirect | OTT-поток + `ensureConvexAuth()` перед SPA-навигацией |
@@ -122,47 +131,51 @@ seo:
## Офлайн-очередь
-| | main | convex |
+_(Историческая справка - описывает эпоху v7 Convex. Текущий офлайн: PowerSync управляет синхронизацией автоматически. См. [Архитектуру](/ru/development/architecture).)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Структура** | Хелперы в `trns/helpers.ts` | Выделенная директория `components/offline/` |
| **Файлы** | Разрозненные ключи localStorage | `helpers.ts`, `replay.ts`, `replayHelpers.ts`, `storageKeys.ts`, `types.ts` |
-| **Операции** | `saveTrnToAddLaterLocal()`, `removeTrnToDeleteLaterLocal()` | `pushSaveOp()`, `pushDeleteOp()` &rarr; универсальные для любой сущности |
+| **Операции** | `saveTrnToAddLaterLocal()`, `removeTrnToDeleteLaterLocal()` | `pushSaveOp()`, `pushDeleteOp()` -> универсальные для любой сущности |
| **Типы сущностей** | Строковые литералы (`'wallets'`, `'trns'`) | Константный объект `OfflineEntityType` для типобезопасных ссылок |
| **Реплей** | Ручной при следующей загрузке | `replayOfflineQueue()` с обнаружением конфликтов и ремапом ID |
-| **Поэнтитный реплей** | N/A | `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps` &mdash; извлечённые тестируемые функции |
-| **Валидация операций** | Нет | `validateOpData()` с Zod-схемами &mdash; повреждённые операции логируются и удаляются |
+| **Поэнтитный реплей** | N/A | `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps` - извлечённые тестируемые функции |
+| **Валидация операций** | Нет | `validateOpData()` с Zod-схемами - повреждённые операции логируются и удаляются |
| **Мерж** | Нет | `mergeOfflineOps(serverData, entity)` применяет ожидающие операции поверх свежих серверных данных |
## PWA
-| | main | convex |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Стратегия** | `injectManifest` (кастомный SW через env var `SW`) | `generateSW` (автогенерация Workbox) |
-| **Service worker** | Рукописный `sw.ts` | Нет &mdash; Workbox генерирует автоматически |
+| **Service worker** | Рукописный `sw.ts` | Нет - Workbox генерирует автоматически |
| **Прекеширование** | Ручная конфигурация | Автоматическое для всех ассетов сборки |
| **Иконки** | Загрузка с Iconify API в рантайме | Включены в бандл на этапе сборки через `clientBundle` |
## TypeScript
-| | main | convex |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Strict mode** | Включён, но есть неразрешённые ошибки | Ноль ошибок TypeScript |
-| **Касты типов** | `as any` по кодовой базе | Ноль `as any` &mdash; type guards, `@vue-ignore`, узкие касты |
+| **Касты типов** | `as any` по кодовой базе | Ноль `as any` - type guards, `@vue-ignore`, узкие касты |
| **Определение переводов** | `transferCategoriesIds` (computed из данных категорий) | `TrnType.Transfer` enum + discriminated union типы |
| **Валидация на рантайме** | Нет | Zod-схемы для настроек, курсов, конфига статистики, параметров дат |
-| **Функции дат** | `getStartOf(date, string)`, `getEndOf(date, string)` &mdash; `default` fallback на day | Типизированы как `Period`, exhaustive `switch` с `case 'day'` &mdash; новые варианты вызывают ошибку компиляции |
-| **Конструкция Duration** | Динамический `{ [\`${period}s\`]: value }` &mdash; TS видит `Record<string, number>` | `toDuration(period, value): Duration` &mdash; типизированный возврат через exhaustive switch |
-| **Маппинг типов статистики** | `Record<string, TrnType[]>` с `??` fallback | `Record<SeriesSlugSelected \| StatTabSlug, TrnType[]>` &mdash; все ключи покрыты, fallback не нужен |
-| **Ключ средних** | `key as keyof TotalReturns` небезопасный каст + `as number` | Типизированный `key: keyof TotalReturns` через явный маппинг `'netIncome'` &rarr; `'sum'`, без кастов |
-| **Fallback курсов** | `rates[code] \|\| 1`, `wallet?.currency \|\| 'USD'` &mdash; falsy `0`/`''` триггерит fallback | `rates[code] ?? 1`, `wallet?.currency ?? 'USD'` &mdash; только `null`/`undefined` триггерит fallback |
-| **Парсинг query-параметров** | `if (data.rangeOffset)` &mdash; falsy `0` пропускается | `if (data.x !== undefined)` &mdash; нулевые значения применяются корректно |
-| **Пропсы total** | `baseCurrencyCode?: string` нестрогий тип | `baseCurrencyCode?: CurrencyCode` &mdash; согласованно с `getAmountInRate` |
-| **Параметры стат. категорий** | `trnsItems: Record<TrnId, { categoryId?: string }>` инлайн-тип | `trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>>` &mdash; привязан к исходному типу |
-| **Null guard в сортировке** | `sortCategoriesByAmount` проверяет `if (!a \|\| !b)` в рантайме | Гард удален &mdash; TS уже гарантирует параметры `CategoryWithData`; явный возвращаемый тип `: number` |
+| **Функции дат** | `getStartOf(date, string)`, `getEndOf(date, string)` - `default` fallback на day | Типизированы как `Period`, exhaustive `switch` с `case 'day'` - новые варианты вызывают ошибку компиляции |
+| **Конструкция Duration** | Динамический `{ [\`${period}s\`]: value }` - TS видит `Record<string, number>` | `toDuration(period, value): Duration` - типизированный возврат через exhaustive switch |
+| **Маппинг типов статистики** | `Record<string, TrnType[]>` с `??` fallback | `Record<SeriesSlugSelected \| StatTabSlug, TrnType[]>` - все ключи покрыты, fallback не нужен |
+| **Ключ средних** | `key as keyof TotalReturns` небезопасный каст + `as number` | Типизированный `key: keyof TotalReturns` через явный маппинг `'netIncome'` -> `'sum'`, без кастов |
+| **Fallback курсов** | `rates[code] \|\| 1`, `wallet?.currency \|\| 'USD'` - falsy `0`/`''` триггерит fallback | `rates[code] ?? 1`, `wallet?.currency ?? 'USD'` - только `null`/`undefined` триггерит fallback |
+| **Парсинг query-параметров** | `if (data.rangeOffset)` - falsy `0` пропускается | `if (data.x !== undefined)` - нулевые значения применяются корректно |
+| **Пропсы total** | `baseCurrencyCode?: string` нестрогий тип | `baseCurrencyCode?: CurrencyCode` - согласованно с `getAmountInRate` |
+| **Параметры стат. категорий** | `trnsItems: Record<TrnId, { categoryId?: string }>` инлайн-тип | `trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>>` - привязан к исходному типу |
+| **Null guard в сортировке** | `sortCategoriesByAmount` проверяет `if (!a \|\| !b)` в рантайме | Гард удален - TS уже гарантирует параметры `CategoryWithData`; явный возвращаемый тип `: number` |
## Тесты
-| | main | convex |
+_(В v7 Convex была отдельная vitest-конфигурация `convex`, работавшая в edge-runtime. Текущие тесты выполняются в проектах `unit` (node) и `store` (happy-dom) с моками PowerSync/Supabase.)_
+
+| | firebase | v7 (Convex) |
|---|---|---|
| **Конфиг** | Нет vitest config | 3 проекта vitest: `unit` (node), `store` (happy-dom), `convex` (edge-runtime) |
| **Тесты бэкенда** | Нет | Полные CRUD интеграционные тесты (кошельки, категории, транзакции, хеш синхронизации) |
@@ -180,7 +193,7 @@ seo:
- **Кошельки:** `filterWalletsByCurrency`, `filterWalletsByViewType`, `groupWalletsByProperty`, `computeWalletCounts`, `sumWalletAmounts`, `getCreditAvailable`
- **Категории:** `collectCategoriesByTrns`, `flattenCategoriesWithValues`, `groupCategoriesWithValues`
- **Офлайн:** `remapTrnIds`, `isTrnOrphaned`, `groupOpsByEntity`, `splitCategoryOps`, `replayWalletOps`, `replayCategoryOps`, `replayTrnOps`, `replaySettingsOps`, `validateOpData`
-- **Демо:** упрощён до read-only &mdash; удалены CRUD-методы (`addDemoCategory`, `deleteDemoWallet` и др.), только `generateDemoData()` + `isDemo`
+- **Демо:** упрощён до read-only - удалены CRUD-методы (`addDemoCategory`, `deleteDemoWallet` и др.), только `generateDemoData()` + `isDemo`
### Изменения компонентов
@@ -190,25 +203,25 @@ seo:
### Паттерны компонентов
-- **Мерж классов:** утилита `getStyles()` удалена &mdash; заменена на `cn()` (clsx + tailwind-merge)
-- **Инпуты форм:** пропы `value`/`updateValue` &rarr; `v-model` / `defineModel`
+- **Мерж классов:** утилита `getStyles()` удалена - заменена на `cn()` (clsx + tailwind-merge)
+- **Инпуты форм:** пропы `value`/`updateValue` -> `v-model` / `defineModel`
### Декомпозиция composables
- **Кошельки:** `useWalletContextMenu`, `useWalletDelete`, `useWalletsFilter`, `useWalletsGrouping`, `useWalletsCounts`
- **Категории:** `useCategoryContextMenu`
- **Статистика:** Symbol-based injection keys (`filterKey`, `statDateKey`, `statConfigKey`) для типобезопасного `provide`/`inject`
-- **Страницы статистики:** composable `useStatPage` &mdash; дублированная инфраструктура статистики (создание и provide filter, statConfig, statDate, а также activeTab, storageKey, trnsIds, maxRange) извлечена из трёх компонентов-страниц (Dashboard, Category, Wallet) в один переиспользуемый composable. Каждая страница передаёт только свою entity-specific логику фильтрации через коллбэк `getTrnsFilter`. Скрипт-секция сокращена на 24&ndash;53% на трёх страницах
-- **Composable `useCategoryLongPress`:** извлечён дублированный код long-press (59 строк &times; 3 файла) из `Round2lines.vue`, `Line.vue` и `Vertical.vue` в общий composable. Обрабатывает долгое нажатие для создания транзакции из категории с корректным выбором даты из интервалов графика
+- **Страницы статистики:** composable `useStatPage` - дублированная инфраструктура статистики (создание и provide filter, statConfig, statDate, а также activeTab, storageKey, trnsIds, maxRange) извлечена из трёх компонентов-страниц (Dashboard, Category, Wallet) в один переиспользуемый composable. Каждая страница передаёт только свою entity-specific логику фильтрации через коллбэк `getTrnsFilter`. Скрипт-секция сокращена на 24&ndash;53% на трёх страницах
+- **Composable `useCategoryLongPress`:** извлечён дублированный код long-press (59 строк x 3 файла) из `Round2lines.vue`, `Line.vue` и `Vertical.vue` в общий composable. Обрабатывает долгое нажатие для создания транзакции из категории с корректным выбором даты из интервалов графика
- **Инкапсуляция `useStatDate`:** навигационные computed-свойства (`shouldShowNav`, `isAtEnd`, `isAtStart`, `isDayToday`, `shouldShowNavHome`) и прямые мутации `params.value` перенесены из `Navigation.vue` и `chart/Wrap.vue` в методы `useStatDate` (`selectInterval()`, `resetInterval()`, `setIntervalsBy()`, `navigate()`). Скрипт Navigation.vue сокращён с ~54 строк до 5
-- **Удалён дубликат `stat/date/Nav.vue`:** удалена идентичная копия `date/Nav.vue` &mdash; остался только канонический компонент `DateNav`
+- **Удалён дубликат `stat/date/Nav.vue`:** удалена идентичная копия `date/Nav.vue` - остался только канонический компонент `DateNav`
- **Компонент `UiNumberStepper`:** извлечён дублированный паттерн &plusmn;/input из `ConfigModal.vue` в переиспользуемый UI-примитив с `v-model`, `min`, `max` пропами
-- **Автономность stat-компонентов:** `StatAverage` &mdash; три условных блока `Amount` консолидированы в один через computed; `StatSumWrap` и `StatChartWrap` &mdash; убран избыточный проброс пропов в пользу inject; `StatItem` &mdash; два модальных блока объединены в один через state-machine паттерн
+- **Автономность stat-компонентов:** `StatAverage` - три условных блока `Amount` консолидированы в один через computed; `StatSumWrap` и `StatChartWrap` - убран избыточный проброс пропов в пользу inject; `StatItem` - два модальных блока объединены в один через state-machine паттерн
- **Кэширование конфигов:** `Section2.vue` и `Line.vue` кэшируют чтения `statConfig.config.value.catsList.*` в computed-свойства (`isItemsBg`, `isLines`, `isRoundIcon`, `isListGrouped` и др.) для читаемости шаблонов
- **Упрощение `Range.vue`:** ручное индексирование `intervalsInRange` заменено на `statDate.selectedInterval`; извлечён computed `isIntervalSelected`
-- **Очистка `useStatItem`:** извлечён computed `baseTrnsIdsForSelection` для устранения дублирования логики выбора интервала; исправлен небезопасный каст `type.value as keyof TotalReturns` на `type.value ?? 'sum'`; исправлен знаменатель среднего в графике &mdash; использовался неверный источник данных (`intervalsData` &rarr; `intervalsDataWithFilteredCategories`)
-- **Composable `useCategoriesExpanded`:** извлечена логика expand/collapse (52 строки) из `DetailedSection.vue` (286&rarr;234 строк)
-- **Переименование stat-компонентов:** `Section`/`Section2` &rarr; `RoundSection`/`DetailedSection` для ясности
+- **Очистка `useStatItem`:** извлечён computed `baseTrnsIdsForSelection` для устранения дублирования логики выбора интервала; исправлен небезопасный каст `type.value as keyof TotalReturns` на `type.value ?? 'sum'`; исправлен знаменатель среднего в графике - использовался неверный источник данных (`intervalsData` -> `intervalsDataWithFilteredCategories`)
+- **Composable `useCategoriesExpanded`:** извлечена логика expand/collapse (52 строки) из `DetailedSection.vue` (286->234 строк)
+- **Переименование stat-компонентов:** `Section`/`Section2` -> `RoundSection`/`DetailedSection` для ясности
- **Извлечение `barUtils`:** `computeBarStyle()` и `formatCompactAmount()` извлечены из инлайн-шаблонов в тестируемые утилиты
- **Консистентность статистики кошельков:** архивные кошельки полностью исключены из всех подсчётов (итого, суммы по типам, снятие, доступно) через ранний `continue`; `available.isShow` требует наличия и withdrawal, и credit кошельков; авто-сброс фильтра на «Итого» при переключении валюты, если текущий фильтр пуст
- **Консолидация store sync:** `showErrorToast`/`showSuccessToast`/`showWarningToast` объединены в `showToast(type, key, params?)`
@@ -216,8 +229,8 @@ seo:
### Семантическое переименование
-| main | convex |
-|------|--------|
+| firebase | v7 (Convex) |
+|----------|------|
| `getTrnsIds` | `filterTrnsIds` |
| `getCategoriesWithData` | `computeCategoriesWithData` |
| `getTotalOfTrnsIds` | `computeTotalForTrnsIds` |
@@ -241,7 +254,7 @@ seo:
### Модель данных
-| | main | convex |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Дочерние категории** | Денормализованный массив `childIds` | Вычисляются динамически из `parentId` |
| **Определение переводов** | `transferCategoriesIds` (computed из данных категорий) | Значение enum `TrnType.Transfer` |
@@ -250,10 +263,10 @@ seo:
## UX-улучшения
- **Тактильная вибрация** при создании транзакции (вибрация на мобильных)
-- **Доступность:** `<div>` &rarr; `<button>` в интерактивных компонентах, i18n `aria-label` на кнопках-иконках
+- **Доступность:** `<div>` -> `<button>` в интерактивных компонентах, i18n `aria-label` на кнопках-иконках
- **Калькулятор:** исправлен бесконечный цикл при нулевом результате, корректный показ `0.`, округление деления
- **Форма:** сумма сбрасывается сразу после submit, popover закрывается перед навигацией
-- **Онбординг:** компонент `Welcome` заменён на `Onboarding` &mdash; улучшённый дизайн, состояние в куке (`finapp.isOnboarded`)
+- **Онбординг:** компонент `Welcome` заменён на `Onboarding` - улучшённый дизайн, состояние в куке (`finapp.isOnboarded`)
- **Страница валют:** два раздела (Используемые / Все) с глобальным поиском, O(1) поиск через `currencyMap`
- **Детали кошелька/категории:** действия редактирования/удаления перенесены в меню с тремя точками
- **Статистика кошельков:** архивные кошельки полностью исключены из всех вкладок-фильтров; вкладка «Доступно» показывается только при наличии и withdrawal, и кредитных кошельков; авто-сброс фильтра на «Итого» при переключении валюты, если фильтр пуст
@@ -265,7 +278,7 @@ seo:
## i18n
-| | main | convex |
+| | firebase | v7 (Convex) |
|---|---|---|
| **Сообщения об ошибках** | Общие или отсутствуют | Ключи ошибок по сущностям (`categories.errors.*`, `wallets.errors.*`, `trns.errors.*`) |
| **Лейблы форм** | Многословные (`Category name`, `Category color`) | Краткие (`Name`, `Color`, `Icon`) |
@@ -275,7 +288,7 @@ seo:
## Качество кода
-### Удалено из main
+### Удалено из firebase
- Зависимости `vue-deepunref`, `firebase`, `nuxt-vuefire`
- Старые page-specific wallet composables
@@ -292,31 +305,33 @@ seo:
- Emit во время рендера в `SelectionCategoriesFast`
- Магические числа заменены на `TrnType` enum (8 мест)
- `ref<any>` заменены на корректные типы (4 файла)
-- Layout ошибок локализован (хардкод на английском &rarr; i18n-ключи)
-- CSS-синтаксис Tailwind v4: `[var(--name)]` &rarr; `(--name)` функциональная нотация
+- Layout ошибок локализован (хардкод на английском -> i18n-ключи)
+- CSS-синтаксис Tailwind v4: `[var(--name)]` -> `(--name)` функциональная нотация
- Radius использует `??` (не `||`), чтобы `0` был валидным: `radius ?? 0.375`
-- Опечатка CSS-утилиты: `bottomSheetDrugClassesCustom` &rarr; `bottomSheetDragClassesCustom`
+- Опечатка CSS-утилиты: `bottomSheetDrugClassesCustom` -> `bottomSheetDragClassesCustom`
- ESLint: правила для `convex/`, layout `vue/no-multiple-template-root`
-- `createLogger(prefix)` &mdash; dev-only `log`, always-on `warn` и `error`, с `[prefix]` форматированием во всех модулях
-- Захардкоженная локаль `'ru'` в форматтерах графиков &rarr; динамическая локаль из настроек
+- `createLogger(prefix)` - dev-only `log`, always-on `warn` и `error`, с `[prefix]` форматированием во всех модулях
+- Захардкоженная локаль `'ru'` в форматтерах графиков -> динамическая локаль из настроек
- `Statistics.vue` пустые секции групп скрыты через `v-show`
-- `Selector.vue` `onSelectRange(value: any)` &rarr; типизированный `{ end: unknown, start: unknown }`
+- `Selector.vue` `onSelectRange(value: any)` -> типизированный `{ end: unknown, start: unknown }`
- Тип `setWalletViewType` исправлен с `WalletType | 'total'` на `WalletViewTypes | 'total'`
-- Версия: v6.6.4 &rarr; v7.0.0-beta.10
+- Версия: v6.6.4 -> v7.0.0-beta.10
- `useAmount.getAmountInBaseRate`: удалён мёртвый параметр `noFormat`, убран лишний унарный `+` над числом
-- `useFilter`: убраны избыточные `[...array.filter()]` и `[...string.split()]` &mdash; оба метода уже возвращают новые массивы
-- `getUCalendarTimedDate`: `new Date(string)` парсился как UTC &rarr; `date.toDate(getLocalTimeZone())` для корректной локальной таймзоны
-- `useGetDateRange`: паттерн `type: 'start' | 'end'` удалён &mdash; format-функции возвращают полную строку напрямую, 3 IIFE-switch заменены на `isSamePeriod`
-- `getIntervalsInRange`: `rangeOffset` сделан опциональным в `IntervalsInRangeProps` &mdash; не используется в `getIntervalsInRange`, только в `calculateIntervalInRange`
-- `compareCategoriesByParentAndName`: `||` &rarr; `??` для fallback пустой строки (консистентная nullish-семантика)
-- `useCategoriesStore`: убраны 5 лишних `?? {}` defensive-проверок &mdash; `items` всегда инициализирован через `shallowRef`
+- `useFilter`: убраны избыточные `[...array.filter()]` и `[...string.split()]` - оба метода уже возвращают новые массивы
+- `getUCalendarTimedDate`: `new Date(string)` парсился как UTC -> `date.toDate(getLocalTimeZone())` для корректной локальной таймзоны
+- `useGetDateRange`: паттерн `type: 'start' | 'end'` удалён - format-функции возвращают полную строку напрямую, 3 IIFE-switch заменены на `isSamePeriod`
+- `getIntervalsInRange`: `rangeOffset` сделан опциональным в `IntervalsInRangeProps` - не используется в `getIntervalsInRange`, только в `calculateIntervalInRange`
+- `compareCategoriesByParentAndName`: `||` -> `??` для fallback пустой строки (консистентная nullish-семантика)
+- `useCategoriesStore`: убраны 5 лишних `?? {}` defensive-проверок - `items` всегда инициализирован через `shallowRef`
- `useCategoryLongPress`: убран избыточный `!` после optional chaining (`value?.start` уже сужает тип)
-- `useCategoriesExpanded`: `forEach` &rarr; `for...of`; `reduce` с `as` кастом &rarr; `Object.fromEntries`
+- `useCategoriesExpanded`: `forEach` -> `for...of`; `reduce` с `as` кастом -> `Object.fromEntries`
- `sortCategoriesByAmount`: `isP`/`isN` переименованы в `bothPositive`/`bothNegative` для читаемости; убран избыточный `categories ??= []` (уже инициализирован при группировке)
### Зависимости
-| Удалены | Добавлены |
+_(Историческая справка - описывает изменения от firebase к v7 Convex. Текущие зависимости - в `package.json` проекта.)_
+
+| Удалены (эпоха firebase) | Добавлены (эпоха Convex) |
|---------|-----------|
| `firebase` | `convex` |
| `nuxt-vuefire` | `@convex-dev/better-auth` |
@@ -326,3 +341,5 @@ seo:
| | `@vueuse/nuxt` |
| | `zod` |
| | `es-toolkit` |
+
+Зависимости эпохи Convex (`convex`, `@convex-dev/better-auth`, `better-auth`, `convex-helpers`, `convex-test`) впоследствии удалены при миграции бэкенда на Supabase + PowerSync. Добавлены `@powersync/web` и `@supabase/supabase-js`. `zod`, `es-toolkit` и `@vueuse/nuxt` остались.
diff --git a/docs/content/ru/4.premium/01.overview.md b/docs/content/ru/4.premium/01.overview.md
index 27c9fe78..321a8de0 100644
--- a/docs/content/ru/4.premium/01.overview.md
+++ b/docs/content/ru/4.premium/01.overview.md
@@ -17,11 +17,11 @@ Finapp Premium - это расширение базового приложени
## Как это работает
-Premium - это [Nuxt Layer](https://nuxt.com/docs/getting-started/layers), который располагается поверх базового приложения. Он добавляет новые компоненты и страницы, не дублируя общий код. Базовое приложение подключено как Git-субмодуль, указывающий на ветку `convex`.
+Premium - это [Nuxt Layer](https://nuxt.com/docs/getting-started/layers), который располагается поверх базового приложения. Он добавляет новые компоненты и страницы, не дублируя общий код. Базовое приложение подключено как Git-субмодуль, указывающий на ветку `main`.
```
finapp-premium/
-├── base/ # Git субмодуль → ilkome/finapp (ветка convex)
+├── base/ # Git субмодуль → ilkome/finapp (ветка main)
├── app/ # Компоненты и страницы только для Premium
└── nuxt.config.ts # Расширяет базовый слой через FINAPP_BASE_PATH
```
diff --git a/docs/content/ru/4.premium/03.ai-chat.md b/docs/content/ru/4.premium/03.ai-chat.md
index 1b37cdfd..c0ec9748 100644
--- a/docs/content/ru/4.premium/03.ai-chat.md
+++ b/docs/content/ru/4.premium/03.ai-chat.md
@@ -14,7 +14,7 @@ seo:
## Точки входа
-- **FAB-кнопка** (`AiFab.vue`) — плавающая кнопка на всех авторизованных страницах
+- **FAB-кнопка** (`AiFab.vue`) - плавающая кнопка на всех авторизованных страницах
- **Горячая клавиша** `Cmd/Ctrl+I` (см. `shortcuts.ts`)
- **Slide-over панель** справа, `sm:max-w-md`
@@ -23,15 +23,15 @@ seo:
```
User input → AiChatPanel
├── useAiChat.send(text)
- │ ├── pruneContext(messages) — скользящее окно + сжатие старых tool results
+ │ ├── pruneContext(messages) - скользящее окно + сжатие старых tool results
│ ├── chat() через @tanstack/ai + адаптер Ollama
│ ├── стрим TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END / TEXT_MESSAGE_CONTENT
- │ ├── autoRetry — детект неудачных мутаций + незавершённых chain
- │ ├── client-side fallback — клиент напрямую исполняет мутации если модель тупит
- │ ├── toast — визуальный фидбек для мутаций
- │ └── lastAction tracker — для undo
- ├── AiToolCallsList.vue — rich cards для каждого tool
- └── AiMessageContent.vue — markdown-текст ассистента
+ │ ├── autoRetry - детект неудачных мутаций + незавершённых chain
+ │ ├── client-side fallback - клиент напрямую исполняет мутации если модель тупит
+ │ ├── toast - визуальный фидбек для мутаций
+ │ └── lastAction tracker - для undo
+ ├── AiToolCallsList.vue - rich cards для каждого tool
+ └── AiMessageContent.vue - markdown-текст ассистента
```
## Каталог tools
@@ -61,17 +61,17 @@ User input → AiChatPanel
В `useSystemPrompt.ts`. Ключевые правила:
- **Tool-first:** любой фактический вопрос о кошельках/категориях/транзакциях ВСЕГДА через tool, не из памяти
-- **Multi-turn:** если не хватает полей — задать ОДИН уточняющий вопрос; на следующем turn смержить данные
+- **Multi-turn:** если не хватает полей - задать ОДИН уточняющий вопрос; на следующем turn смержить данные
- **Chain-паттерн:** `delete_trn`/`update_trn`/`duplicate_trn` требуют сначала `list_trns` для получения id
- **FORBIDDEN:** выдумывать id, просить у пользователя id, переиспользовать старые tool results
- **DATE RULE:** не передавать `date` если пользователь не сказал явно
## Сжатие контекста
-`pruneContext.ts` — скользящее окно + сжатие tool results:
+`pruneContext.ts` - скользящее окно + сжатие tool results:
-- `maxContextTurns` (default 6) — в модель идут только последние N пар user+assistant
-- `compressToolsAfterTurns` (default 1) — старые tool_calls сжимаются в строку `[tool_name: summary]`
+- `maxContextTurns` (default 6) - в модель идут только последние N пар user+assistant
+- `compressToolsAfterTurns` (default 1) - старые tool_calls сжимаются в строку `[tool_name: summary]`
Это убирает "я уже сделал X" галлюцинации в длинных сессиях.
@@ -79,12 +79,12 @@ User input → AiChatPanel
`useAiChat.ts`:
-1. **autoRetry** — если tool вернул error / `ok: false`, отправить retry с реальным id из `list_trns`
-2. **executeFallback** — если модель всё равно тупит на chain'ах, клиент САМ выполняет мутацию и инжектирует результат как синтетический tool_call
+1. **autoRetry** - если tool вернул error / `ok: false`, отправить retry с реальным id из `list_trns`
+2. **executeFallback** - если модель всё равно тупит на chain'ах, клиент САМ выполняет мутацию и инжектирует результат как синтетический tool_call
## Auto-clear при простое
-`idleMinutesBeforeClear` (default 30) — если чат был неактивен N минут, история очищается на следующем `send()`.
+`idleMinutesBeforeClear` (default 30) - если чат был неактивен N минут, история очищается на следующем `send()`.
## Рекомендации моделей
@@ -107,12 +107,12 @@ User input → AiChatPanel
## Известные ограничения
-- **Multi-turn `create_trn` зависит от модели.** На `gemma4:latest` сборка транзакции через уточнения (юзер: "купил кофе" → ассистент спрашивает сумму/кошелёк → вызывает `create_trn`) работает примерно в 70% попыток. Модель иногда кладёт ответ не в то поле (например "наличными" в `description` вместо `wallet`) или забывает `type`. Для надёжного multi-turn — `qwen3:8b` или давать все поля сразу.
-- **Chain-tools (`duplicate_trn`, `delete_trn`, `update_trn`) на `gemma4:latest` в длинных сессиях** — модель иногда отвечает текстом и просит id вместо `list_trns` → мутация. Это компенсировано client-side fallback'ом (`executeFallback` в `useAiChat.ts`), который напрямую исполняет мутацию и инжектирует синтетический tool_call.
+- **Multi-turn `create_trn` зависит от модели.** На `gemma4:latest` сборка транзакции через уточнения (юзер: "купил кофе" → ассистент спрашивает сумму/кошелёк → вызывает `create_trn`) работает примерно в 70% попыток. Модель иногда кладёт ответ не в то поле (например "наличными" в `description` вместо `wallet`) или забывает `type`. Для надёжного multi-turn - `qwen3:8b` или давать все поля сразу.
+- **Chain-tools (`duplicate_trn`, `delete_trn`, `update_trn`) на `gemma4:latest` в длинных сессиях** - модель иногда отвечает текстом и просит id вместо `list_trns` → мутация. Это компенсировано client-side fallback'ом (`executeFallback` в `useAiChat.ts`), который напрямую исполняет мутацию и инжектирует синтетический tool_call.
- **Галлюцинация "я уже это сделал"** может вернуться при большом `maxContextTurns`. Default `compressToolsAfterTurns: 1` сжимает старые результаты для предотвращения; выше 8-10 turns риск возвращается.
-- **Зависимость от локальной сети.** Если Ollama не запущена на `baseUrl`, чат не работает. Remote fallback отсутствует по дизайну — всё inference локально.
+- **Зависимость от локальной сети.** Если Ollama не запущена на `baseUrl`, чат не работает. Remote fallback отсутствует по дизайну - всё inference локально.
- **Validation errors из `@tanstack/ai`** приходят с `state: 'done'` (не `error`) и `{ error: "..." }` в результате. `autoRetry` распознаёт их через helper `isTcFailed` по JSON результата.
-- **Нет массовой перестановки категорий** — `useCategoriesStore` не предоставляет `saveCategoriesOrder`, AI не может менять порядок категорий.
+- **Нет массовой перестановки категорий** - `useCategoriesStore` не предоставляет `saveCategoriesOrder`, AI не может менять порядок категорий.
## Добавление нового tool
diff --git a/docs/content/ru/index.md b/docs/content/ru/index.md
index 07485742..2b424e24 100644
--- a/docs/content/ru/index.md
+++ b/docs/content/ru/index.md
@@ -1,6 +1,6 @@
---
seo:
- title: Финапка — Управление личными финансами
+ title: Финапка - Управление личными финансами
description: Приложение с открытым кодом для управления финансами. Учёт расходов, управление кошельками и анализ трат. Работает офлайн, синхронизируется между устройствами.
---
@@ -11,7 +11,7 @@ seo:
#description
Приложение с открытым кодом для учёта личных финансов на Vue и Nuxt.
-Отслеживайте расходы, управляйте кошельками и анализируйте траты — где угодно и когда угодно.
+Отслеживайте расходы, управляйте кошельками и анализируйте траты - где угодно и когда угодно.
#links
:::u-button
@@ -49,7 +49,7 @@ seo:
Управление [кошельками]{.text-primary}
#description
- Создавайте кошельки в разных валютах. Все счета и балансы — в одном месте.
+ Создавайте кошельки в разных валютах. Все счета и балансы - в одном месте.
:::
:::u-page-feature
@@ -93,7 +93,7 @@ seo:
Поддержка [мультивалюты]{.text-primary}
#description
- Курсы обновляются автоматически. Итоги по всем кошелькам — в вашей базовой валюте.
+ Курсы обновляются автоматически. Итоги по всем кошелькам - в вашей базовой валюте.
:::
:::u-page-feature
@@ -137,6 +137,6 @@ seo:
Гибкие [настройки]{.text-primary}
#description
- Базовая валюта, язык, цветовая тема и скругления — всё настраивается под вас.
+ Базовая валюта, язык, цветовая тема и скругления - всё настраивается под вас.
:::
::