Skip to content

Open source personal finance application

docs(migrate): document the Firebase import tooling

Ilya Komichev2739ae63ea79
diff --git a/docs/content/en/2.development/04.migration.md b/docs/content/en/2.development/04.migration.md
index 340603e1..38c5f809 100644
--- a/docs/content/en/2.development/04.migration.md
+++ b/docs/content/en/2.development/04.migration.md
@@ -8,7 +8,7 @@ seo:
description: Historical note on the Finapp backend migration - from Firebase Realtime Database to Supabase Postgres with PowerSync.
---
-Finapp's backend was migrated from **Firebase Realtime Database** to **Supabase Postgres + PowerSync** (offline-first sync) with **Supabase Auth (email/password)**. This page documents that one-off migration for historical reference.
+Finapp's backend was migrated from **Firebase Realtime Database** to **Supabase Postgres + PowerSync** (offline-first sync) with **Supabase Auth (email/password)**. This page documents that migration and the script that imports a Firebase JSON export into Supabase.
The legacy Firebase (v6) source code lives on the [`firebase`](https://github.com/ilkome/finapp/tree/firebase) branch.
@@ -17,22 +17,36 @@ The legacy Firebase (v6) source code lives on the [`firebase`](https://github.co
| Entity | Firebase (v6) | Current (Supabase + PowerSync) |
|--------|---------------|--------------------------------|
| Accounts | `accounts` with string keys | `wallets` table, `text` ids |
-| Categories | String IDs, `parentId` as string | `text` ids, `parentId` as a category id or `0` |
-| Transactions | String IDs, references by old keys | `text` ids, all references remapped |
+| Categories | String IDs, `parentId` as string | `text` ids, `parentId` = a category id or `null` (root) |
+| Transactions | String IDs, references by old keys | `text` ids, Firebase ids reused (references preserved) |
| Settings | `settings.lang` (`en`, `ru`) | `user_settings.locale` (`en`, `ru`) |
| Icons | `mdi mdi-xxx` format | `mdi:xxx` format |
-## Migration tooling (historical - no longer in the repo)
+## Import tooling
-This was a one-off development-time operation, not a recurring user-facing flow. The scripts that performed it have been deleted from the repository because they are no longer relevant. Do not attempt to run them.
+The importer lives at `app/scripts/import-firebase.mjs`. It reads a Firebase JSON export (the `{ accounts, categories, trns, settings, user }` shape) and writes it into a Supabase project for one user.
-The process:
+```bash [Terminal]
+cd app
+SUPABASE_URL=https://<ref>.supabase.co \
+SUPABASE_SERVICE_ROLE_KEY=<service_role> \
+node scripts/import-firebase.mjs <backup.json> --email <owner-email> --wipe
+```
-1. Export the data from Firebase as JSON.
-2. Transform the export with a script that remapped ids to stable `text` ids, fixed icon formats, normalized settings, and mapped users to their Supabase Auth uids.
-3. Import via `psql` into the Supabase Postgres instance.
+- **Owner** - resolved from `--email` (defaults to the export's `user.email`) to an existing Supabase auth uid via the GoTrue admin API, or passed directly with `--user-id`. The user must have signed in at least once (e.g. via Google) so the imported rows' `userId` matches the uid they log in as.
+- **Config** - reads `SUPABASE_URL` + `SUPABASE_SERVICE_ROLE_KEY` from the env; with neither set it falls back to the local stack via `supabase status`. Writes go through PostgREST with the `service_role` key, so they bypass RLS and run over HTTPS (the direct Postgres connection's IPv6-only limitation does not apply).
+- **`--wipe`** deletes the user's existing `trns` / `categories` / `wallets` first; **`--dry-run`** prints the transformed counts and samples without writing.
+- **Idempotent** - rows upsert on their primary key and Firebase ids are reused verbatim (below), so re-running is safe.
-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.
+### Transforms it applies
+
+- **Ids reused, not remapped** - Supabase id columns are plain `text` with no FK constraints, so the script keeps the original Firebase keys as ids; `parentId` / `walletId` / `categoryId` references stay valid with no remap pass. (This is the main difference from the old Firebase -> Convex script, which had to remap server-generated ids.)
+- **Accounts -> wallets**; **`settings.lang` -> `user_settings.locale`**; **`settings.baseCurrency` -> `user_settings.baseCurrency`**.
+- **Icons** - `mdi mdi-xxx` -> `mdi:xxx`; empty -> `mdi:category-outline`.
+- **Transfer / adjustment** - categories named `Transfer` / `Перевод` / `Adjustment` are not real categories and are skipped; their transactions become `categoryId = 'transfer'` (type 2, with the `expense*` / `income*` fields) or `categoryId = 'adjustment'` (otherwise).
+- **Legacy fields** - `walletFromId` / `walletToId` -> `expenseWalletId` / `incomeWalletId`; `amountFrom` / `amountTo` -> `expenseAmount` / `incomeAmount`; `description` -> `desc`. Firebase-only fields with no column (category `order`, `showStat`, `budgets`, `groups`) are dropped.
+
+No FK constraints exist in the schema, so import order does not matter. RLS policies and PowerSync sync rules ensure per-user isolation; on the owner's next login PowerSync syncs the imported rows to their device.
## Current backend
diff --git a/docs/content/en/3.reference/07.firebase-migration.md b/docs/content/en/3.reference/07.firebase-migration.md
index d320f9e7..91930bd4 100644
--- a/docs/content/en/3.reference/07.firebase-migration.md
+++ b/docs/content/en/3.reference/07.firebase-migration.md
@@ -26,7 +26,7 @@ Side-by-side comparison of what the app looks like on the [`firebase`](https://g
| **Exchange rates** | Client-side fetch | `rates` table synced through PowerSync like any other table |
| **User settings** | localStorage only | `user_settings` table (baseCurrency, locale), auto-created on signup by a trigger |
| **Schema indexes** | N/A | Client SQLite indexes in `AppSchema.ts` (`userDate: ['userId','date']`, plus `userId` per table) |
-| **Migration** | N/A | One-off Firebase JSON export -> transform -> `psql` import (see [Migration History](/en/development/migration)) |
+| **Migration** | N/A | Firebase JSON export -> transform -> PostgREST import via `scripts/import-firebase.mjs` (see [Migration History](/en/development/migration)) |
| **Account deletion** | N/A | RLS-scoped delete of the user's rows + local wipe (`removeAllUserData`) |
### What the current backend gives
diff --git a/docs/content/ru/2.development/04.migration.md b/docs/content/ru/2.development/04.migration.md
index f879010e..4954da47 100644
--- a/docs/content/ru/2.development/04.migration.md
+++ b/docs/content/ru/2.development/04.migration.md
@@ -8,7 +8,7 @@ seo:
description: Историческая справка о миграции бэкенда Финапки - из Firebase Realtime Database на Supabase Postgres с PowerSync.
---
-Бэкенд Финапки был мигрирован с **Firebase Realtime Database** на **Supabase Postgres + PowerSync** (offline-first синхронизация) с **Supabase Auth (email/password)**. На этой странице эта разовая миграция описана как исторический контекст.
+Бэкенд Финапки был мигрирован с **Firebase Realtime Database** на **Supabase Postgres + PowerSync** (offline-first синхронизация) с **Supabase Auth (email/password)**. На этой странице описана и сама миграция, и скрипт, который импортирует Firebase-экспорт в Supabase.
Исходный код Firebase (v6) хранится на ветке [`firebase`](https://github.com/ilkome/finapp/tree/firebase).
@@ -17,22 +17,36 @@ seo:
| Сущность | Firebase (v6) | Текущее (Supabase + PowerSync) |
|----------|---------------|--------------------------------|
| Счета | `accounts` со строковыми ключами | Таблица `wallets`, `text`-идентификаторы |
-| Категории | Строковые ID, `parentId` строкой | `text`-идентификаторы, `parentId` как id категории или `0` |
-| Транзакции | Строковые ID, ссылки старыми ключами | `text`-идентификаторы, все ссылки перемаплены |
+| Категории | Строковые ID, `parentId` строкой | `text`-идентификаторы, `parentId` = id категории или `null` (корень) |
+| Транзакции | Строковые ID, ссылки старыми ключами | `text`-идентификаторы, id из Firebase переиспользуются (ссылки сохраняются) |
| Настройки | `settings.lang` (`en`, `ru`) | `user_settings.locale` (`en`, `ru`) |
| Иконки | Формат `mdi mdi-xxx` | Формат `mdi:xxx` |
-## Инструменты миграции (исторически - больше нет в репозитории)
+## Инструмент импорта
-Это была разовая операция во время разработки, не повторяющийся пользовательский процесс. Скрипты, которые её выполняли, удалены из репозитория как неактуальные. Запускать их не нужно.
+Импортёр лежит в `app/scripts/import-firebase.mjs`. Он читает Firebase-экспорт (структура `{ accounts, categories, trns, settings, user }`) и записывает его в проект Supabase для одного пользователя.
-Процесс:
+```bash [Terminal]
+cd app
+SUPABASE_URL=https://<ref>.supabase.co \
+SUPABASE_SERVICE_ROLE_KEY=<service_role> \
+node scripts/import-firebase.mjs <backup.json> --email <owner-email> --wipe
+```
-1. Экспорт данных из Firebase в JSON.
-2. Трансформация экспорта скриптом: ремаппинг id в стабильные `text`-идентификаторы, исправление формата иконок, нормализация настроек и сопоставление пользователей с их Supabase Auth uid.
-3. Импорт через `psql` в экземпляр Supabase Postgres.
+- **Владелец** - определяется по `--email` (по умолчанию `user.email` из экспорта) в существующий Supabase auth uid через GoTrue admin API, либо задаётся напрямую через `--user-id`. Пользователь должен хотя бы раз войти (например, через Google), чтобы `userId` импортированных строк совпал с uid, под которым он логинится.
+- **Конфиг** - читает `SUPABASE_URL` + `SUPABASE_SERVICE_ROLE_KEY` из env; если их нет, откатывается на локальный стек через `supabase status`. Запись идёт через PostgREST с ключом `service_role`, поэтому обходит RLS и работает по HTTPS (ограничение «только IPv6» прямого подключения к Postgres здесь не применяется).
+- **`--wipe`** сначала удаляет существующие `trns` / `categories` / `wallets` пользователя; **`--dry-run`** печатает преобразованные счётчики и примеры без записи.
+- **Идемпотентность** - строки upsert'ятся по первичному ключу, а id из Firebase переиспользуются дословно (ниже), поэтому повторный запуск безопасен.
-В схеме Postgres нет FK-ограничений, поэтому порядок импорта не имеет значения. RLS-политики и правила синхронизации PowerSync обеспечивают изоляцию данных по пользователям.
+### Какие преобразования применяются
+
+- **Id переиспользуются, не ремапятся** - id-колонки в Supabase это обычный `text` без FK-ограничений, поэтому скрипт сохраняет исходные ключи Firebase как id; ссылки `parentId` / `walletId` / `categoryId` остаются валидными без отдельного прохода ремаппинга. (Это главное отличие от старого скрипта Firebase -> Convex, которому приходилось ремапить сгенерированные сервером id.)
+- **Accounts -> wallets**; **`settings.lang` -> `user_settings.locale`**; **`settings.baseCurrency` -> `user_settings.baseCurrency`**.
+- **Иконки** - `mdi mdi-xxx` -> `mdi:xxx`; пустая -> `mdi:category-outline`.
+- **Transfer / adjustment** - категории с именами `Transfer` / `Перевод` / `Adjustment` не являются настоящими категориями и пропускаются; их транзакции получают `categoryId = 'transfer'` (тип 2, с полями `expense*` / `income*`) или `categoryId = 'adjustment'` (иначе).
+- **Легаси-поля** - `walletFromId` / `walletToId` -> `expenseWalletId` / `incomeWalletId`; `amountFrom` / `amountTo` -> `expenseAmount` / `incomeAmount`; `description` -> `desc`. Поля только из Firebase, которым нет колонки (`order` у категорий, `showStat`, `budgets`, `groups`), отбрасываются.
+
+В схеме нет FK-ограничений, поэтому порядок импорта не имеет значения. RLS-политики и правила синхронизации PowerSync обеспечивают изоляцию по пользователям; при следующем входе владельца PowerSync синхронизирует импортированные строки на его устройство.
## Текущий бэкенд
diff --git a/docs/content/ru/3.reference/07.firebase-migration.md b/docs/content/ru/3.reference/07.firebase-migration.md
index c4ba9a2f..3db75f78 100644
--- a/docs/content/ru/3.reference/07.firebase-migration.md
+++ b/docs/content/ru/3.reference/07.firebase-migration.md
@@ -26,7 +26,7 @@ seo:
| **Курсы валют** | Клиентский запрос | Таблица `rates`, синхронизируется через PowerSync как любая другая |
| **Настройки пользователя** | Только localStorage | Таблица `user_settings` (baseCurrency, locale), создаётся при регистрации триггером |
| **Индексы схемы** | N/A | Индексы клиентского SQLite в `AppSchema.ts` (`userDate: ['userId','date']` + `userId` на каждой таблице) |
-| **Миграция** | N/A | Разовый экспорт JSON из Firebase -> трансформация -> импорт через `psql` (см. [Историю миграций](/ru/development/migration)) |
+| **Миграция** | N/A | Экспорт JSON из Firebase -> трансформация -> импорт через PostgREST скриптом `scripts/import-firebase.mjs` (см. [Историю миграций](/ru/development/migration)) |
| **Удаление аккаунта** | N/A | RLS-ограниченное удаление строк пользователя + локальная очистка (`removeAllUserData`) |
### Что даёт текущий бэкенд