Open source personal finance application
docs(deploy): document migrating an existing env to a new prod project
Ilya Komichev0df25af0c27b
diff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.mdindex 76544a31..721309e9 100644--- a/docs/content/en/2.development/05.deployment.md+++ b/docs/content/en/2.development/05.deployment.md@@ -196,6 +196,66 @@ Do **not** use `supabase config push` for a hosted project - it pushes the wholeGoogle needs no extra app env vars - it reuses `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase issues its own JWT regardless of the sign-in provider, so PowerSync keeps validating it via JWKS unchanged.+## Migrating to a New Prod Project++Standing up a fresh prod project alongside an existing environment (promoting a dev/local dataset, or cutting over from a different backend) adds three steps the generic setup above doesn't cover: importing existing data, pointing Vercel at the new project, and flipping the deploy branch.++### Importing existing data (userId remap)++Four tables are per-user: `categories`, `wallets`, `trns`, `user_settings`. `rates` is global - **don't copy it** (it's populated by `fetch-rates`). The copy is Postgres -> Postgres (the schema is identical across environments), rewriting `userId` to the destination project's auth uid.++::callout{icon="i-lucide-info" color="warning"}+The destination `userId` is the user's auth uid **in the new project**, which only exists **after they sign in once** there. So finish [Google sign-in](#google-sign-in-production) and do a first login (a preview deploy works), read the uid, then import.+::++Stream each table with `userId` rewritten in the `SELECT`. For `user_settings` remap `id` too (it equals the uid):++```bash [Terminal]+SRC_UID=<source-auth-uid>+DST_UID=<new-prod-auth-uid>++# categories - wallets/trns follow the same pattern (full column list, userId substituted).+psql "<source-conn>" -c "\copy (+ select id, '$DST_UID' as \"userId\", name, color, icon, \"parentId\",+ \"showInLastUsed\", \"showInQuickSelector\", \"updatedAt\"+ from public.categories where \"userId\" = '$SRC_UID'+) to stdout" \+| psql "<prod-pooler-conn>" -c "\copy public.categories from stdin"+```++Writes to the prod DB go over the IPv4 **session pooler** (same IPv6 caveat as `db push`) as `postgres` / `service_role`, which bypasses RLS. The rows are inert until they match a real uid - once `userId` equals the signed-in user's uid, PowerSync streams them to the client on the next sync.++### Pointing Vercel at the new project++If your local `.vercel` is linked to a different project (e.g. a dev one), re-link before setting prod env, otherwise the vars land on the wrong project:++```bash [Terminal]+vercel link # choose the prod project+```++Set `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` / `VITE_POWERSYNC_URL` to the prod values and remove any legacy-backend vars. **Don't trigger a prod rebuild yet** if the default branch still serves the old stack - wait for the branch cutover below, or prod builds the old code against the new env.++### Branch cutover (git-connected prod)++When the new stack lives on a feature branch and prod auto-deploys from the default branch, advance the default branch instead of force-pushing:++1. **Archive the current default branch** so the old stack stays recoverable:++ ```bash [Terminal]+ git branch <archive> <default> # e.g. git branch convex main+ git push origin <archive>+ ```++2. **Fast-forward the default branch** to the feature tip (no force-push when the feature is a direct descendant - check with `git rev-list --left-right --count <default>...<feature>`, the left count must be 0):++ ```bash [Terminal]+ git checkout <default>+ git merge --ff-only <feature>+ git push origin <default>+ ```++The push triggers the prod Vercel build on the new stack. **Rollback** is cheap: re-point the default branch at the archive branch (`git push origin <archive>:<default> --force-with-lease`), or instant-rollback to the previous deploy in Vercel.+## 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**.diff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.mdindex b623f7bb..e5495e24 100644--- a/docs/content/ru/2.development/05.deployment.md+++ b/docs/content/ru/2.development/05.deployment.md@@ -196,6 +196,66 @@ curl -X PATCH "https://api.supabase.com/v1/projects/<ref>/config/auth" \Дополнительные env-переменные для Google не нужны - используются те же `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase выдаёт собственный JWT независимо от провайдера входа, поэтому PowerSync продолжает проверять его через JWKS без изменений.+## Миграция в новый прод-проект++Поднятие свежего прод-проекта рядом с существующим окружением (продвижение dev/локального набора данных или переход с другого бэкенда) добавляет три шага, которых нет в общей настройке выше: импорт существующих данных, переключение Vercel на новый проект и перемотку deploy-ветки.++### Импорт существующих данных (remap userId)++Четыре таблицы - пер-юзерные: `categories`, `wallets`, `trns`, `user_settings`. `rates` глобальная - **не копируем** (её наполняет `fetch-rates`). Копия идёт Postgres -> Postgres (схема между окружениями идентична), с переписыванием `userId` на auth-uid целевого проекта.++::callout{icon="i-lucide-info" color="warning"}+Целевой `userId` - это auth-uid пользователя **в новом проекте**, который появляется только **после первого входа** там. Поэтому: завершите [настройку Google](#вход-через-google-продакшен), сделайте первый вход (подойдёт preview-деплой), считайте uid и тогда импортируйте.+::++Стримим каждую таблицу с переписанным `userId` в `SELECT`. Для `user_settings` переписываем и `id` (он равен uid):++```bash [Terminal]+SRC_UID=<source-auth-uid>+DST_UID=<new-prod-auth-uid>++# categories - wallets/trns по тому же шаблону (полный список колонок, userId подменён).+psql "<source-conn>" -c "\copy (+ select id, '$DST_UID' as \"userId\", name, color, icon, \"parentId\",+ \"showInLastUsed\", \"showInQuickSelector\", \"updatedAt\"+ from public.categories where \"userId\" = '$SRC_UID'+) to stdout" \+| psql "<prod-pooler-conn>" -c "\copy public.categories from stdin"+```++Запись в прод-БД идёт через IPv4 **session pooler** (та же IPv6-оговорка, что и `db push`) под `postgres` / `service_role`, который обходит RLS. Строки инертны, пока не совпадут с реальным uid - как только `userId` равен uid вошедшего пользователя, PowerSync стримит их на клиент при следующей синхронизации.++### Переключение Vercel на новый проект++Если локальный `.vercel` привязан к другому проекту (например, dev), перелинкуйте перед установкой prod-env, иначе переменные уйдут не туда:++```bash [Terminal]+vercel link # выбрать прод-проект+```++Выставьте `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` / `VITE_POWERSYNC_URL` на прод-значения и удалите переменные старого бэкенда. **Не запускайте прод-ребилд**, пока дефолтная ветка отдаёт старый стек - дождитесь перемотки ветки ниже, иначе прод соберёт старый код на новом env.++### Перемотка ветки (git-connected прод)++Когда новый стек живёт на фиче-ветке, а прод авто-деплоится с дефолтной ветки, продвигайте дефолтную ветку, а не делайте force-push:++1. **Заархивируйте текущую дефолтную ветку**, чтобы старый стек оставался восстановимым:++ ```bash [Terminal]+ git branch <archive> <default> # напр. git branch convex main+ git push origin <archive>+ ```++2. **Перемотайте дефолтную ветку** на верхушку фичи (без force-push, когда фича - прямой потомок: проверьте `git rev-list --left-right --count <default>...<feature>`, левое число должно быть 0):++ ```bash [Terminal]+ git checkout <default>+ git merge --ff-only <feature>+ git push origin <default>+ ```++Пуш триггерит прод-билд Vercel на новом стеке. **Откат** дешёвый: вернуть дефолтную ветку на архивную (`git push origin <archive>:<default> --force-with-lease`) или мгновенный rollback к предыдущему деплою в Vercel.+## Premium (Finapp Premium)Finapp Premium живёт в отдельном репозитории ([finapp-premium](https://github.com/ilkome/finapp-premium)) и расширяет базовое приложение как **Nuxt layer**.