Skip to content

Open source personal finance application

chore: remove Convex backend and offline-replay layer

Ilya Komicheva6566517e902
diff --git a/.gitignore b/.gitignore
index f77d6e89..8ea6a7c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,7 +24,9 @@ logs
# Playwright
/test-results
+**/test-results/
/blob-report
+**/blob-report/
playwright/profiles
**/playwright/profiles
playwright/.auth
@@ -48,3 +50,10 @@ tests/e2e/.auth
# Migration data
utils/migrate/data.json
+
+# Generated knowledge-graph / tooling output (regenerated locally, not source)
+graphify-out
+**/graphify-out
+.understand-anything/deploy
+.understand-anything/backup-en
+.understand-anything/backup-ru
diff --git a/app/app/components/offline/helpers.test.ts b/app/app/components/offline/helpers.test.ts
deleted file mode 100644
index f7ab7b83..00000000
--- a/app/app/components/offline/helpers.test.ts
+++ /dev/null
@@ -1,244 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import {
- clearOfflineQueue,
- getAllOfflineOps,
- getOfflineOpsByEntity,
- pushOfflineOp,
- removeOfflineOp,
- removeOfflineOpByType,
- updateOfflineOpData,
-} from '~/components/offline/helpers'
-import { OfflineEntityType } from '~/components/offline/types'
-
-const store = new Map<string, any>()
-
-vi.mock('localforage', () => ({
- default: {
- getItem: vi.fn((key: string) => Promise.resolve(store.get(key) ?? null)),
- removeItem: vi.fn((key: string) => {
- store.delete(key)
- return Promise.resolve()
- }),
- setItem: vi.fn((key: string, value: any) => {
- store.set(key, value)
- return Promise.resolve()
- }),
- },
-}))
-
-beforeEach(() => {
- store.clear()
-})
-
-afterEach(() => {
- vi.clearAllMocks()
-})
-
-describe('pushOfflineOp', () => {
- it('adds operation to empty queue', async () => {
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]).toMatchObject({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
- expect(queue[0]!.timestamp).toBeGreaterThan(0)
- })
-
- it('appends operations for different entities', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(2)
- })
-
- describe('collapsing rules', () => {
- it('create + update → create with merged data', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { name: 'Cash Updated' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'update' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.type).toBe('create')
- expect(queue[0]!.data).toEqual({ name: 'Cash Updated' })
- })
-
- it('create + delete → both removed', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ entity: OfflineEntityType.Wallets, id: 'w1', type: 'delete' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(0)
- })
-
- it('update + update → update with merged data', async () => {
- await pushOfflineOp({ data: { name: 'Old' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'update' })
- await pushOfflineOp({ data: { name: 'New' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'update' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.type).toBe('update')
- expect(queue[0]!.data).toEqual({ name: 'New' })
- })
-
- it('update + delete → replace with delete', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'update' })
- await pushOfflineOp({ entity: OfflineEntityType.Wallets, id: 'w1', type: 'delete' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.type).toBe('delete')
- })
-
- it('delete + any → ignores new operation', async () => {
- await pushOfflineOp({ entity: OfflineEntityType.Wallets, id: 'w1', type: 'delete' })
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.type).toBe('delete')
- })
- })
-})
-
-describe('removeOfflineOp', () => {
- it('removes all operations for entity+id', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
-
- await removeOfflineOp(OfflineEntityType.Wallets, 'w1')
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.entity).toBe(OfflineEntityType.Trns)
- })
-
- it('does nothing when not found', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
-
- await removeOfflineOp(OfflineEntityType.Wallets, 'w999')
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- })
-})
-
-describe('removeOfflineOpByType', () => {
- it('removes specific operation by type', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
-
- await removeOfflineOpByType(OfflineEntityType.Wallets, 'w1', 'create')
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(0)
- })
-})
-
-describe('getOfflineOpsByEntity', () => {
- it('filters by entity', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
- await pushOfflineOp({ data: { name: 'Food' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'create' })
-
- const walletOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
- expect(walletOps).toHaveLength(1)
- expect(walletOps[0]!.entity).toBe(OfflineEntityType.Wallets)
- })
-
- it('returns empty array when no matching ops', async () => {
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
-
- const walletOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
- expect(walletOps).toHaveLength(0)
- })
-})
-
-describe('clearOfflineQueue', () => {
- it('removes all operations', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
-
- await clearOfflineQueue()
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(0)
- })
-})
-
-describe('updateOfflineOpData', () => {
- it('merges patch into update op data', async () => {
- await pushOfflineOp({ data: { color: '#000', name: 'old' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' })
- const before = await getAllOfflineOps()
- const t0 = before[0]!.timestamp
-
- await new Promise(r => setTimeout(r, 2))
- await updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]).toMatchObject({ data: { color: '#fff', name: 'old' }, type: 'update' })
- expect(queue[0]!.timestamp).toBeGreaterThan(t0)
- })
-
- it('merges patch into create op preserving type', async () => {
- await pushOfflineOp({ data: { name: 'A', parentId: 'local_p1' }, entity: OfflineEntityType.Categories, id: 'local_c1', type: 'create' })
- await updateOfflineOpData(OfflineEntityType.Categories, 'local_c1', { parentId: 'jd7xyz' })
-
- const queue = await getAllOfflineOps()
- expect(queue[0]).toMatchObject({ data: { name: 'A', parentId: 'jd7xyz' }, type: 'create' })
- })
-
- it('no-op when matching op missing', async () => {
- await updateOfflineOpData(OfflineEntityType.Categories, 'missing', { color: '#fff' })
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(0)
- })
-
- it('no-op when matching op is delete', async () => {
- await pushOfflineOp({ entity: OfflineEntityType.Categories, id: 'c1', type: 'delete' })
- await updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.type).toBe('delete')
- expect(queue[0]!.data).toBeUndefined()
- })
-
- it('serializes with concurrent push (no torn write)', async () => {
- await pushOfflineOp({ data: { color: '#000' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' })
- await Promise.all([
- pushOfflineOp({ data: { name: 'merged' }, entity: OfflineEntityType.Categories, id: 'c1', type: 'update' }),
- updateOfflineOpData(OfflineEntityType.Categories, 'c1', { color: '#fff' }),
- ])
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.data).toMatchObject({ color: '#fff', name: 'merged' })
- })
-})
-
-describe('cross-entity isolation', () => {
- it('different entities have separate operations', async () => {
- await pushOfflineOp({ data: { a: 1 }, entity: OfflineEntityType.Trns, id: 'id1', type: 'create' })
- await pushOfflineOp({ data: { b: 2 }, entity: OfflineEntityType.Wallets, id: 'id1', type: 'create' })
-
- const trnsOps = await getOfflineOpsByEntity(OfflineEntityType.Trns)
- const walletsOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
-
- expect(trnsOps).toHaveLength(1)
- expect(trnsOps[0]!.data).toEqual({ a: 1 })
- expect(walletsOps).toHaveLength(1)
- expect(walletsOps[0]!.data).toEqual({ b: 2 })
- })
-
- it('collapsing only applies within same entity+id', async () => {
- await pushOfflineOp({ data: { a: 1 }, entity: OfflineEntityType.Trns, id: 'id1', type: 'create' })
- await pushOfflineOp({ data: { b: 2 }, entity: OfflineEntityType.Wallets, id: 'id1', type: 'create' })
- await pushOfflineOp({ entity: OfflineEntityType.Trns, id: 'id1', type: 'delete' })
-
- const queue = await getAllOfflineOps()
- expect(queue).toHaveLength(1)
- expect(queue[0]!.entity).toBe(OfflineEntityType.Wallets)
- })
-})
diff --git a/app/app/components/offline/helpers.ts b/app/app/components/offline/helpers.ts
deleted file mode 100644
index 2f583beb..00000000
--- a/app/app/components/offline/helpers.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import localforage from 'localforage'
-
-import type { EntityType, OfflineOp, OfflineOpData, OfflineOpInput } from '~/components/offline/types'
-
-import { STORAGE_KEYS } from '~/components/offline/storageKeys'
-import { createLogger } from '~/utils/logger'
-
-const QUEUE_KEY = STORAGE_KEYS.offlineQueue
-const QUEUE_USER_KEY = STORAGE_KEYS.offlineQueueUserId
-
-const logger = createLogger('offline')
-
-let _currentUserId: string | null = null
-
-export function setOfflineQueueUserId(userId: string | null): void {
- _currentUserId = userId
-}
-
-const OLD_KEYS = [
- 'finapp.wallets.offline.update',
- 'finapp.wallets.offline.delete',
- 'finapp.categories.offline.update',
- 'finapp.categories.offline.delete',
- 'finapp.trns.offline.update',
- 'finapp.trns.offline.delete',
-]
-
-let isOldKeysCleaned = false
-
-async function cleanOldKeys() {
- if (isOldKeysCleaned)
- return
- isOldKeysCleaned = true
- for (const key of OLD_KEYS)
- await localforage.removeItem(key)
-}
-
-async function readQueue(): Promise<OfflineOp[]> {
- await cleanOldKeys()
- const raw = await localforage.getItem<OfflineOp[]>(QUEUE_KEY)
- return Array.isArray(raw) ? raw : []
-}
-
-async function writeQueue(queue: OfflineOp[]): Promise<void> {
- await localforage.setItem(QUEUE_KEY, queue)
-}
-
-/**
- * Collapsing rules (matching by entity + id):
- * | Existing | New | Result |
- * |----------|--------|-------------------------------------|
- * | create | update | create with merged data |
- * | create | delete | remove both (never reached server) |
- * | update | update | update with merged data |
- * | update | delete | replace update with delete |
- * | delete | * | ignore new (delete is terminal) |
- * | - | * | append as-is |
- */
-let writeChain = Promise.resolve()
-
-export function pushOfflineOp(op: OfflineOpInput): Promise<void> {
- writeChain = writeChain.then(() => pushOfflineOpImpl(op), () => pushOfflineOpImpl(op))
- return writeChain
-}
-
-async function pushOfflineOpImpl(op: OfflineOpInput): Promise<void> {
- if (_currentUserId) {
- const storedUserId = await localforage.getItem<string>(QUEUE_USER_KEY)
- if (!storedUserId)
- await localforage.setItem(QUEUE_USER_KEY, _currentUserId)
- }
-
- const queue = await readQueue()
-
- const existingIdx = findLastIndex(queue, o => o.entity === op.entity && o.id === op.id)
-
- if (existingIdx === -1) {
- queue.push({ ...op, timestamp: Date.now() })
- await writeQueue(queue)
- logger.log(`queued ${op.type}: ${op.entity}/${op.id}`)
- return
- }
-
- const existing = queue[existingIdx]!
-
- if (existing.type === 'delete') {
- logger.log(`skip ${op.type} (already deleted): ${op.entity}/${op.id}`)
- return
- }
-
- if (op.type === 'delete') {
- if (existing.type === 'create') {
- queue.splice(existingIdx, 1)
- logger.log(`collapsed create+delete (removed): ${op.entity}/${op.id}`)
- }
- else {
- queue[existingIdx] = { ...op, timestamp: Date.now() } as OfflineOp
- logger.log(`collapsed update→delete: ${op.entity}/${op.id}`)
- }
- await writeQueue(queue)
- return
- }
-
- queue[existingIdx] = {
- ...existing,
- data: { ...existing.data, ...op.data },
- timestamp: Date.now(),
- }
- await writeQueue(queue)
- logger.log(`collapsed ${existing.type}+${op.type}: ${op.entity}/${op.id}`)
-}
-
-export function removeOfflineOp(entity: EntityType, id: string): Promise<void> {
- writeChain = writeChain.then(() => removeOfflineOpImpl(entity, id), () => removeOfflineOpImpl(entity, id))
- return writeChain
-}
-
-async function removeOfflineOpImpl(entity: EntityType, id: string): Promise<void> {
- const queue = await readQueue()
- const filtered = queue.filter(o => !(o.entity === entity && o.id === id))
- if (filtered.length !== queue.length) {
- await writeQueue(filtered)
- logger.log(`synced: ${entity}/${id}`)
- }
-}
-
-export function removeOfflineOps(entity: EntityType, ids: string[]): Promise<void> {
- writeChain = writeChain.then(() => removeOfflineOpsImpl(entity, ids), () => removeOfflineOpsImpl(entity, ids))
- return writeChain
-}
-
-async function removeOfflineOpsImpl(entity: EntityType, ids: string[]): Promise<void> {
- const idSet = new Set(ids)
- const queue = await readQueue()
- const filtered = queue.filter(o => !(o.entity === entity && idSet.has(o.id)))
- if (filtered.length !== queue.length) {
- await writeQueue(filtered)
- logger.log(`synced ${ids.length} ops: ${entity}`)
- }
-}
-
-/**
- * Merge `patch` into the queued op's `data` (shallow), bump timestamp.
- * No-op if no op matches, op is `delete`, or op carries no `data`.
- * Op type is preserved.
- */
-export function updateOfflineOpData(entity: EntityType, id: string, patch: OfflineOpData): Promise<void> {
- writeChain = writeChain.then(() => updateOfflineOpDataImpl(entity, id, patch), () => updateOfflineOpDataImpl(entity, id, patch))
- return writeChain
-}
-
-async function updateOfflineOpDataImpl(entity: EntityType, id: string, patch: OfflineOpData): Promise<void> {
- const queue = await readQueue()
- const idx = findLastIndex(queue, o => o.entity === entity && o.id === id)
- if (idx === -1) {
- logger.log(`skip update-data (no op): ${entity}/${id}`)
- return
- }
- const existing = queue[idx]!
- if (existing.type === 'delete') {
- logger.log(`skip update-data (delete is terminal): ${entity}/${id}`)
- return
- }
- if (!existing.data) {
- logger.warn(`skip update-data (no data field): ${entity}/${id}`)
- return
- }
- queue[idx] = { ...existing, data: { ...existing.data, ...patch }, timestamp: Date.now() }
- await writeQueue(queue)
- logger.log(`patched ${existing.type} data: ${entity}/${id}`)
-}
-
-export function removeOfflineOpByType(entity: EntityType, id: string, type: OfflineOp['type']): Promise<void> {
- writeChain = writeChain.then(() => removeOfflineOpByTypeImpl(entity, id, type), () => removeOfflineOpByTypeImpl(entity, id, type))
- return writeChain
-}
-
-async function removeOfflineOpByTypeImpl(entity: EntityType, id: string, type: OfflineOp['type']): Promise<void> {
- const queue = await readQueue()
- const filtered = queue.filter(o => !(o.entity === entity && o.id === id && o.type === type))
- if (filtered.length !== queue.length) {
- await writeQueue(filtered)
- logger.log(`synced ${type}: ${entity}/${id}`)
- }
-}
-
-export async function getAllOfflineOps(): Promise<OfflineOp[]> {
- return readQueue()
-}
-
-export async function getOfflineOpsByEntity(entity: EntityType): Promise<OfflineOp[]> {
- const queue = await readQueue()
- return queue.filter(o => o.entity === entity)
-}
-
-export async function getQueueUserId(): Promise<string | null> {
- return localforage.getItem<string>(QUEUE_USER_KEY)
-}
-
-export async function setQueueUserId(userId: string): Promise<void> {
- await localforage.setItem(QUEUE_USER_KEY, userId)
-}
-
-export function clearOfflineQueue(): Promise<void> {
- writeChain = writeChain.then(() => clearOfflineQueueImpl(), () => clearOfflineQueueImpl())
- return writeChain
-}
-
-async function clearOfflineQueueImpl(): Promise<void> {
- await localforage.removeItem(QUEUE_KEY)
- await localforage.removeItem(QUEUE_USER_KEY)
- _currentUserId = null
- logger.log('queue cleared')
-}
-
-function findLastIndex<T>(arr: T[], predicate: (item: T) => boolean): number {
- for (let i = arr.length - 1; i >= 0; i--) {
- if (predicate(arr[i] as T))
- return i
- }
- return -1
-}
diff --git a/app/app/components/offline/replay.test.ts b/app/app/components/offline/replay.test.ts
deleted file mode 100644
index 06304c24..00000000
--- a/app/app/components/offline/replay.test.ts
+++ /dev/null
@@ -1,283 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-import type { OfflineOp } from '~/components/offline/types'
-
-import { OfflineEntityType } from '~/components/offline/types'
-
-// Import once - _isReplaying resets via finally block after each test
-import { isReplaying, replayOfflineQueue } from './replay'
-
-// --- Mocks ---
-
-const mockClearOfflineQueue = vi.fn(() => Promise.resolve())
-const mockGetAllOfflineOps = vi.fn((): Promise<OfflineOp[]> => Promise.resolve([]))
-const mockGetQueueUserId = vi.fn((): Promise<string | null> => Promise.resolve(null))
-const mockRemoveOfflineOp = vi.fn(() => Promise.resolve())
-const mockSetOfflineQueueUserId = vi.fn()
-const mockSetQueueUserId = vi.fn(() => Promise.resolve())
-
-vi.mock('~/components/offline/helpers', () => ({
- clearOfflineQueue: (...args: any[]) => (mockClearOfflineQueue as any)(...args),
- getAllOfflineOps: (...args: any[]) => (mockGetAllOfflineOps as any)(...args),
- getQueueUserId: (...args: any[]) => (mockGetQueueUserId as any)(...args),
- removeOfflineOp: (...args: any[]) => (mockRemoveOfflineOp as any)(...args),
- setOfflineQueueUserId: (...args: any[]) => (mockSetOfflineQueueUserId as any)(...args),
- setQueueUserId: (...args: any[]) => (mockSetQueueUserId as any)(...args),
-}))
-
-const mockReplayWalletOps = vi.fn(() => Promise.resolve())
-const mockReplayCategoryOps = vi.fn(() => Promise.resolve())
-const mockReplayTrnOps = vi.fn((): Promise<number> => Promise.resolve(0))
-const mockReplaySettingsOps = vi.fn(() => Promise.resolve())
-const mockGroupOpsByEntity = vi.fn(() => ({
- categoryOps: [] as OfflineOp[],
- settingsOps: [] as OfflineOp[],
- trnOps: [] as OfflineOp[],
- unknownOps: [] as OfflineOp[],
- walletOps: [] as OfflineOp[],
-}))
-
-vi.mock('~/components/offline/replayHelpers', () => ({
- groupOpsByEntity: (...args: any[]) => (mockGroupOpsByEntity as any)(...args),
- replayCategoryOps: (...args: any[]) => (mockReplayCategoryOps as any)(...args),
- replaySettingsOps: (...args: any[]) => (mockReplaySettingsOps as any)(...args),
- replayTrnOps: (...args: any[]) => (mockReplayTrnOps as any)(...args),
- replayWalletOps: (...args: any[]) => (mockReplayWalletOps as any)(...args),
-}))
-
-let mockUid: string | null = 'user1'
-
-vi.mock('~/components/wallets/useWalletsStore', () => ({
- useWalletsStore: () => ({ deleteWallet: vi.fn(), items: { w1: {} }, saveWallet: vi.fn() }),
-}))
-
-vi.mock('~/components/categories/useCategoriesStore', () => ({
- useCategoriesStore: () => ({ deleteCategory: vi.fn(), items: { c1: {} }, saveCategory: vi.fn() }),
-}))
-
-vi.mock('~/components/trns/useTrnsStore', () => ({
- useTrnsStore: () => ({ deleteTrn: vi.fn(), removeTrnsFromStore: vi.fn(), saveTrn: vi.fn() }),
-}))
-
-vi.mock('~/components/user/useUserStore', () => ({
- useUserStore: () => ({
- saveUserBaseCurrency: vi.fn(),
- saveUserLocale: vi.fn(),
- get uid() { return mockUid },
- }),
-}))
-
-const mockShowWarningToast = vi.fn()
-vi.mock('~/composables/useStoreSync', () => ({
- showWarningToast: (...args: unknown[]) => mockShowWarningToast(...args),
-}))
-
-vi.mock('~/utils/logger', () => ({
- createLogger: () => ({ error: vi.fn(), log: vi.fn(), warn: vi.fn() }),
-}))
-
-vi.mock('~/utils/convexId', () => ({
- isLocalId: (id: string) => id.startsWith('local_'),
-}))
-
-function makeOp(entity: OfflineOp['entity'], id: string, type: OfflineOp['type'] = 'create', data?: Record<string, unknown>): OfflineOp {
- return { data, entity, id, timestamp: Date.now(), type }
-}
-
-beforeEach(() => {
- vi.clearAllMocks()
- mockUid = 'user1'
- mockGetQueueUserId.mockResolvedValue(null)
- mockGetAllOfflineOps.mockResolvedValue([])
- mockReplayTrnOps.mockResolvedValue(0)
- mockReplayWalletOps.mockResolvedValue(undefined)
- mockReplayCategoryOps.mockResolvedValue(undefined)
- mockReplaySettingsOps.mockResolvedValue(undefined)
- mockGroupOpsByEntity.mockReturnValue({
- categoryOps: [],
- settingsOps: [],
- trnOps: [],
- unknownOps: [],
- walletOps: [],
- })
-})
-
-describe('replayOfflineQueue', () => {
- it('does nothing when queue is empty', async () => {
- await replayOfflineQueue()
-
- expect(mockGetAllOfflineOps).toHaveBeenCalled()
- expect(mockReplayWalletOps).not.toHaveBeenCalled()
- expect(mockReplayCategoryOps).not.toHaveBeenCalled()
- expect(mockReplayTrnOps).not.toHaveBeenCalled()
- })
-
- it('clears queue if it belongs to another user', async () => {
- mockGetQueueUserId.mockResolvedValue('other-user')
-
- await replayOfflineQueue()
-
- expect(mockClearOfflineQueue).toHaveBeenCalled()
- expect(mockGetAllOfflineOps).not.toHaveBeenCalled()
- })
-
- it('sets queue ownership for current user', async () => {
- await replayOfflineQueue()
-
- expect(mockSetOfflineQueueUserId).toHaveBeenCalledWith('user1')
- expect(mockSetQueueUserId).toHaveBeenCalledWith('user1')
- })
-
- it('does not set ownership when no current user', async () => {
- mockUid = null
-
- await replayOfflineQueue()
-
- expect(mockSetOfflineQueueUserId).not.toHaveBeenCalled()
- expect(mockSetQueueUserId).not.toHaveBeenCalled()
- })
-
- it('proceeds when queue belongs to current user', async () => {
- mockGetQueueUserId.mockResolvedValue('user1')
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Wallets, 'w1', 'create'),
- ])
-
- await replayOfflineQueue()
-
- expect(mockReplayWalletOps).toHaveBeenCalled()
- })
-
- it('filters out frontend-ID delete ops', async () => {
- const realOp = makeOp(OfflineEntityType.Wallets, 'real_w2', 'create', { name: 'Cash' })
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Wallets, 'local_w1', 'delete'),
- realOp,
- ])
-
- await replayOfflineQueue()
-
- expect(mockRemoveOfflineOp).toHaveBeenCalledWith(OfflineEntityType.Wallets, 'local_w1')
- expect(mockGroupOpsByEntity).toHaveBeenCalledWith([realOp])
- })
-
- it('replays phases in order: wallets -> categories -> trns -> settings', async () => {
- const callOrder: string[] = []
- mockReplayWalletOps.mockImplementation(async () => {
- callOrder.push('wallets')
- })
- mockReplayCategoryOps.mockImplementation(async () => {
- callOrder.push('categories')
- })
- mockReplayTrnOps.mockImplementation(async () => {
- callOrder.push('trns')
- return 0
- })
- mockReplaySettingsOps.mockImplementation(async () => {
- callOrder.push('settings')
- })
-
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Wallets, 'w1', 'create'),
- ])
- mockGroupOpsByEntity.mockReturnValue({
- categoryOps: [makeOp(OfflineEntityType.Categories, 'c1', 'create')],
- settingsOps: [makeOp(OfflineEntityType.UserSettings, 's1', 'update')],
- trnOps: [makeOp(OfflineEntityType.Trns, 't1', 'create')],
- unknownOps: [],
- walletOps: [makeOp(OfflineEntityType.Wallets, 'w1', 'create')],
- })
-
- await replayOfflineQueue()
-
- expect(callOrder).toEqual(['wallets', 'categories', 'trns', 'settings'])
- })
-
- it('resets isReplaying after success', async () => {
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Wallets, 'w1', 'create'),
- ])
-
- await replayOfflineQueue()
-
- expect(isReplaying()).toBe(false)
- })
-
- it('resets isReplaying after error', async () => {
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Wallets, 'w1', 'create'),
- ])
- mockReplayWalletOps.mockRejectedValueOnce(new Error('network'))
-
- await expect(replayOfflineQueue()).rejects.toThrow('network')
-
- expect(isReplaying()).toBe(false)
- })
-
- it('clears queue on ownership check error', async () => {
- mockGetQueueUserId.mockRejectedValueOnce(new Error('storage error'))
-
- await replayOfflineQueue()
-
- expect(mockClearOfflineQueue).toHaveBeenCalled()
- expect(mockGetAllOfflineOps).not.toHaveBeenCalled()
- })
-
- it('shows warning toast when orphaned trns exist', async () => {
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Trns, 't1', 'create'),
- ])
- mockGroupOpsByEntity.mockReturnValue({
- categoryOps: [],
- settingsOps: [],
- trnOps: [makeOp(OfflineEntityType.Trns, 't1', 'create')],
- unknownOps: [],
- walletOps: [],
- })
- mockReplayTrnOps.mockResolvedValue(3)
-
- await replayOfflineQueue()
-
- expect(mockShowWarningToast).toHaveBeenCalledWith('trns.errors.orphanedSkipped', { count: 3 })
- })
-
- it('removes ops with unknown entity from queue', async () => {
- const unknownOp = { entity: 'loanPaymentLinks', id: 'x1', timestamp: 0, type: 'update' } as unknown as OfflineOp
- mockGetAllOfflineOps.mockResolvedValue([unknownOp])
- mockGroupOpsByEntity.mockReturnValue({
- categoryOps: [],
- settingsOps: [],
- trnOps: [],
- unknownOps: [unknownOp],
- walletOps: [],
- })
-
- await replayOfflineQueue()
-
- expect(mockRemoveOfflineOp).toHaveBeenCalledWith('loanPaymentLinks', 'x1')
- })
-
- it('does not show toast when no orphans', async () => {
- mockGetAllOfflineOps.mockResolvedValue([
- makeOp(OfflineEntityType.Trns, 't1', 'create'),
- ])
- mockGroupOpsByEntity.mockReturnValue({
- categoryOps: [],
- settingsOps: [],
- trnOps: [makeOp(OfflineEntityType.Trns, 't1', 'create')],
- unknownOps: [],
- walletOps: [],
- })
- mockReplayTrnOps.mockResolvedValue(0)
-
- await replayOfflineQueue()
-
- expect(mockShowWarningToast).not.toHaveBeenCalled()
- })
-})
-
-describe('isReplaying', () => {
- it('returns false when not replaying', () => {
- expect(isReplaying()).toBe(false)
- })
-})
diff --git a/app/app/components/offline/replay.ts b/app/app/components/offline/replay.ts
deleted file mode 100644
index d8aba2d9..00000000
--- a/app/app/components/offline/replay.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import type { LocaleSlug } from '~/components/locale/types'
-
-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { clearOfflineQueue, getAllOfflineOps, getQueueUserId, removeOfflineOp, setOfflineQueueUserId, setQueueUserId } from '~/components/offline/helpers'
-import { groupOpsByEntity, replayCategoryOps, replaySettingsOps, replayTrnOps, replayWalletOps } from '~/components/offline/replayHelpers'
-import { useTrnsStore } from '~/components/trns/useTrnsStore'
-import { useUserStore } from '~/components/user/useUserStore'
-import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import { isLocalId } from '~/utils/convexId'
-import { createLogger } from '~/utils/logger'
-
-const logger = createLogger('offline/replay')
-
-let _isReplaying = false
-
-export function isReplaying(): boolean {
- return _isReplaying
-}
-
-export async function replayOfflineQueue(): Promise<void> {
- if (_isReplaying)
- return
-
- const userStore = useUserStore()
- const currentUserId = userStore.uid
-
- try {
- const queueUserId = await getQueueUserId()
- if (queueUserId && queueUserId !== currentUserId) {
- logger.log(`queue belongs to ${queueUserId}, current user is ${currentUserId} — clearing`)
- await clearOfflineQueue()
- return
- }
-
- if (currentUserId) {
- setOfflineQueueUserId(currentUserId)
- await setQueueUserId(currentUserId)
- }
- }
- catch (e) {
- logger.error('queue ownership check failed, clearing queue for safety', e)
- await clearOfflineQueue().catch(() => {})
- return
- }
-
- const queue = await getAllOfflineOps()
- if (!queue.length)
- return
-
- logger.log(`replaying ${queue.length} operations`)
-
- const walletsStore = useWalletsStore()
- const categoriesStore = useCategoriesStore()
- const trnsStore = useTrnsStore()
-
- const filteredOps = []
- for (const op of queue) {
- if (isLocalId(op.id) && op.type === 'delete') {
- logger.log(`skip delete (frontend ID): ${op.entity}/${op.id}`)
- await removeOfflineOp(op.entity, op.id)
- continue
- }
- filteredOps.push(op)
- }
-
- const { categoryOps, settingsOps, trnOps, unknownOps, walletOps } = groupOpsByEntity(filteredOps)
-
- // Purge ops from removed/renamed features so the queue doesn't grow unbounded.
- if (unknownOps.length > 0) {
- logger.warn(`removing ${unknownOps.length} ops with unknown entity`)
- for (const op of unknownOps) {
- try {
- await removeOfflineOp(op.entity, op.id)
- }
- catch (e) {
- logger.error(`failed to remove unknown op ${op.entity}/${op.id}:`, e)
- }
- }
- }
-
- _isReplaying = true
- const remapIds = new Map<string, string>()
-
- try {
- // Phase 1: Replay wallets
- if (walletOps.length > 0)
- logger.log(`phase 1: ${walletOps.length} wallet ops`)
- await replayWalletOps(walletOps, remapIds, {
- deleteWallet: id => walletsStore.deleteWallet(id),
- saveWallet: ({ id, values }) => walletsStore.saveWallet({ id, values }),
- })
-
- // Phase 2: Replay categories — parents first, then children
- if (categoryOps.length > 0)
- logger.log(`phase 2: ${categoryOps.length} category ops`)
- await replayCategoryOps(categoryOps, remapIds, {
- deleteCategory: id => categoriesStore.deleteCategory(id),
- saveCategory: params => categoriesStore.saveCategory(params),
- })
-
- // Phase 3: Replay trns — remap wallet/category IDs
- if (trnOps.length > 0)
- logger.log(`phase 3: ${trnOps.length} trn ops`)
- const orphanCount = await replayTrnOps(trnOps, remapIds, {
- deleteTrn: id => trnsStore.deleteTrn(id),
- removeOfflineOp: (entity, id) => removeOfflineOp(entity as Parameters<typeof removeOfflineOp>[0], id),
- saveTrn: params => trnsStore.saveTrn(params),
- }, {
- categoriesItems: categoriesStore.items,
- walletsItems: walletsStore.items ?? {},
- })
-
- // Phase 4: Replay settings
- await replaySettingsOps(settingsOps, {
- saveBaseCurrency: currency => userStore.saveUserBaseCurrency(currency),
- saveLocale: locale => userStore.saveUserLocale(locale as LocaleSlug),
- })
-
- if (orphanCount > 0) {
- const { showWarningToast } = await import('~/composables/useStoreSync')
- showWarningToast('trns.errors.orphanedSkipped', { count: orphanCount })
- }
- }
- finally {
- _isReplaying = false
- }
-
- if (remapIds.size > 0)
- logger.log(`replay complete: ${remapIds.size} IDs remapped`)
- else
- logger.log('replay complete')
-}
diff --git a/app/app/components/offline/replayHelpers.test.ts b/app/app/components/offline/replayHelpers.test.ts
deleted file mode 100644
index cd44796b..00000000
--- a/app/app/components/offline/replayHelpers.test.ts
+++ /dev/null
@@ -1,617 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-
-import type { OfflineOp } from '~/components/offline/types'
-import type { Transaction, Transfer, TrnItem } from '~/components/trns/types'
-
-import { OfflineEntityType } from '~/components/offline/types'
-import { TrnType } from '~/components/trns/types'
-
-import { collectRemaps, extractRemaps, groupOpsByEntity, isTrnOrphaned, remapTrnIds, replayCategoryOps, replaySettingsOps, replayTrnOps, replayWalletOps, splitCategoryOps } from './replayHelpers'
-
-vi.mock('~/components/offline/helpers', () => ({
- removeOfflineOp: vi.fn(() => Promise.resolve()),
-}))
-
-function makeOp(entity: OfflineOp['entity'], id: string, type: OfflineOp['type'] = 'create', data?: Record<string, unknown>): OfflineOp {
- return { data, entity, id, timestamp: Date.now(), type }
-}
-
-// --- remapTrnIds ---
-
-describe('remapTrnIds', () => {
- const remap = new Map([['local_w1', 'convex_w1'], ['local_c1', 'convex_c1']])
-
- it('remaps walletId and categoryId for transaction', () => {
- const trn = {
- amount: 100,
- categoryId: 'local_c1',
- date: 1000,
- type: TrnType.Expense,
- updatedAt: 1000,
- walletId: 'local_w1',
- } as TrnItem
-
- const result = remapTrnIds(trn, remap) as Transaction
- expect(result.walletId).toBe('convex_w1')
- expect(result.categoryId).toBe('convex_c1')
- })
-
- it('remaps expenseWalletId and incomeWalletId for transfer', () => {
- const remap2 = new Map([['local_w1', 'convex_w1'], ['local_w2', 'convex_w2']])
- const trn = {
- categoryId: 'transfer',
- date: 1000,
- expenseAmount: 100,
- expenseWalletId: 'local_w1',
- incomeAmount: 100,
- incomeWalletId: 'local_w2',
- type: TrnType.Transfer,
- updatedAt: 1000,
- } as TrnItem
-
- const result = remapTrnIds(trn, remap2) as Transfer
- expect(result.expenseWalletId).toBe('convex_w1')
- expect(result.incomeWalletId).toBe('convex_w2')
- })
-
- it('keeps original IDs when no remap exists', () => {
- const trn = {
- amount: 50,
- categoryId: 'food',
- date: 1000,
- type: TrnType.Income,
- updatedAt: 1000,
- walletId: 'real_w1',
- } as TrnItem
-
- const result = remapTrnIds(trn, remap) as Transaction
- expect(result.walletId).toBe('real_w1')
- expect(result.categoryId).toBe('food')
- })
-
- it('does not mutate original', () => {
- const trn = {
- amount: 100,
- categoryId: 'local_c1',
- date: 1000,
- type: TrnType.Expense,
- updatedAt: 1000,
- walletId: 'local_w1',
- } as Transaction
-
- remapTrnIds(trn, remap)
- expect(trn.walletId).toBe('local_w1')
- })
-})
-
-// --- isTrnOrphaned ---
-
-describe('isTrnOrphaned', () => {
- const wallets = { w1: {}, w2: {} }
- const categories = { food: {}, transport: {} }
-
- it('returns false for valid transaction', () => {
- const trn = { categoryId: 'food', type: TrnType.Expense, walletId: 'w1' } as TrnItem
- expect(isTrnOrphaned(trn, wallets, categories)).toBe(false)
- })
-
- it('returns true for missing wallet', () => {
- const trn = { categoryId: 'food', type: TrnType.Expense, walletId: 'missing' } as TrnItem
- expect(isTrnOrphaned(trn, wallets, categories)).toBe(true)
- })
-
- it('returns true for missing category', () => {
- const trn = { categoryId: 'missing', type: TrnType.Expense, walletId: 'w1' } as TrnItem
- expect(isTrnOrphaned(trn, wallets, categories)).toBe(true)
- })
-
- it('returns false for valid transfer', () => {
- const trn = {
- expenseWalletId: 'w1',
- incomeWalletId: 'w2',
- type: TrnType.Transfer,
- } as TrnItem
- expect(isTrnOrphaned(trn, wallets, categories)).toBe(false)
- })
-
- it('returns true for transfer with missing wallet', () => {
- const trn = {
- expenseWalletId: 'w1',
- incomeWalletId: 'missing',
- type: TrnType.Transfer,
- } as TrnItem
- expect(isTrnOrphaned(trn, wallets, categories)).toBe(true)
- })
-})
-
-// --- groupOpsByEntity ---
-
-describe('groupOpsByEntity', () => {
- it('groups operations by entity type', () => {
- const ops = [
- makeOp(OfflineEntityType.Wallets, 'w1'),
- makeOp(OfflineEntityType.Trns, 't1'),
- makeOp(OfflineEntityType.Categories, 'c1'),
- makeOp(OfflineEntityType.Wallets, 'w2'),
- makeOp(OfflineEntityType.UserSettings, 's1'),
- makeOp(OfflineEntityType.Trns, 't2'),
- ]
-
- const result = groupOpsByEntity(ops)
- expect(result.walletOps).toHaveLength(2)
- expect(result.categoryOps).toHaveLength(1)
- expect(result.trnOps).toHaveLength(2)
- expect(result.settingsOps).toHaveLength(1)
- })
-
- it('returns empty arrays for empty input', () => {
- const result = groupOpsByEntity([])
- expect(result.walletOps).toEqual([])
- expect(result.categoryOps).toEqual([])
- expect(result.trnOps).toEqual([])
- expect(result.settingsOps).toEqual([])
- expect(result.unknownOps).toEqual([])
- })
-
- it('preserves op references', () => {
- const op = makeOp(OfflineEntityType.Trns, 't1')
- const result = groupOpsByEntity([op])
- expect(result.trnOps[0]).toBe(op)
- })
-
- it('collects ops with unknown entity into unknownOps', () => {
- const known = makeOp(OfflineEntityType.Trns, 't1')
- const unknown = { entity: 'loanPaymentLinks', id: 'x1', timestamp: 0, type: 'update' } as unknown as OfflineOp
- const result = groupOpsByEntity([known, unknown])
-
- expect(result.trnOps).toHaveLength(1)
- expect(result.walletOps).toHaveLength(0)
- expect(result.categoryOps).toHaveLength(0)
- expect(result.settingsOps).toHaveLength(0)
- expect(result.unknownOps).toHaveLength(1)
- expect(result.unknownOps[0]).toBe(unknown)
- })
-})
-
-// --- splitCategoryOps ---
-
-describe('splitCategoryOps', () => {
- it('splits parent and child categories', () => {
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'create', { name: 'Food', parentId: 0 }),
- makeOp(OfflineEntityType.Categories, 'c2', 'create', { name: 'Groceries', parentId: 'c1' }),
- makeOp(OfflineEntityType.Categories, 'c3', 'create', { name: 'Transport', parentId: 0 }),
- ]
-
- const result = splitCategoryOps(ops)
- expect(result.parentOps).toHaveLength(2)
- expect(result.childOps).toHaveLength(1)
- expect(result.childOps[0]!.id).toBe('c2')
- })
-
- it('puts delete ops in parentOps', () => {
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'delete'),
- makeOp(OfflineEntityType.Categories, 'c2', 'create', { name: 'Child', parentId: 'c1' }),
- ]
-
- const result = splitCategoryOps(ops)
- expect(result.parentOps).toHaveLength(1)
- expect(result.parentOps[0]!.type).toBe('delete')
- expect(result.childOps).toHaveLength(1)
- })
-
- it('treats no parentId as root', () => {
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'create', { name: 'Root' }),
- ]
-
- const result = splitCategoryOps(ops)
- expect(result.parentOps).toHaveLength(1)
- expect(result.childOps).toHaveLength(0)
- })
-
- it('returns empty arrays for empty input', () => {
- const result = splitCategoryOps([])
- expect(result.parentOps).toEqual([])
- expect(result.childOps).toEqual([])
- })
-})
-
-// --- extractRemaps ---
-
-describe('extractRemaps', () => {
- it('extracts localId/convexId pairs', () => {
- const results = [
- { convexId: 'convex_1', localId: 'local_1' },
- { convexId: 'convex_2', localId: 'local_2' },
- ]
- const remaps = extractRemaps(results)
- expect(remaps).toHaveLength(2)
- expect(remaps[0]).toEqual({ convexId: 'convex_1', localId: 'local_1' })
- })
-
- it('skips non-remap results', () => {
- const results = [
- undefined,
- null,
- 'string',
- 42,
- { other: 'data' },
- { convexId: 'c1', localId: 'l1' },
- ]
- const remaps = extractRemaps(results)
- expect(remaps).toHaveLength(1)
- })
-
- it('returns empty for empty results', () => {
- expect(extractRemaps([])).toEqual([])
- })
-})
-
-// --- collectRemaps ---
-
-describe('collectRemaps', () => {
- it('collects remap entries from resolved promises', async () => {
- const remapIds = new Map<string, string>()
- const promises = [
- Promise.resolve({ convexId: 'convex_1', localId: 'local_1' }),
- Promise.resolve({ convexId: 'convex_2', localId: 'local_2' }),
- ]
-
- await collectRemaps(promises, remapIds)
- expect(remapIds.get('local_1')).toBe('convex_1')
- expect(remapIds.get('local_2')).toBe('convex_2')
- })
-
- it('handles void and undefined promises', async () => {
- const remapIds = new Map<string, string>()
- const promises: (Promise<unknown> | void | undefined)[] = [
- undefined,
- Promise.resolve(undefined),
- Promise.resolve({ convexId: 'c1', localId: 'l1' }),
- ]
-
- await collectRemaps(promises, remapIds)
- expect(remapIds.size).toBe(1)
- expect(remapIds.get('l1')).toBe('c1')
- })
-
- it('appends to existing remap map', async () => {
- const remapIds = new Map([['existing_l', 'existing_c']])
- const promises = [
- Promise.resolve({ convexId: 'c1', localId: 'l1' }),
- ]
-
- await collectRemaps(promises, remapIds)
- expect(remapIds.size).toBe(2)
- expect(remapIds.get('existing_l')).toBe('existing_c')
- expect(remapIds.get('l1')).toBe('c1')
- })
-})
-
-// --- replayWalletOps ---
-
-describe('replayWalletOps', () => {
- it('does nothing for empty ops', async () => {
- const saveWallet = vi.fn()
- const deleteWallet = vi.fn()
- const remapIds = new Map<string, string>()
-
- await replayWalletOps([], remapIds, { deleteWallet, saveWallet })
- expect(saveWallet).not.toHaveBeenCalled()
- expect(deleteWallet).not.toHaveBeenCalled()
- })
-
- it('calls saveWallet for create/update ops', async () => {
- const saveWallet = vi.fn(() => Promise.resolve())
- const deleteWallet = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Wallets, 'w1', 'create', { currency: 'USD', name: 'Cash', type: 'cash' }),
- makeOp(OfflineEntityType.Wallets, 'w2', 'update', { name: 'Bank', type: 'cashless' }),
- ]
-
- await replayWalletOps(ops, remapIds, { deleteWallet, saveWallet })
- expect(saveWallet).toHaveBeenCalledTimes(2)
- expect(saveWallet).toHaveBeenCalledWith({ id: 'w1', values: expect.objectContaining({ currency: 'USD', name: 'Cash', type: 'cash' }) })
- expect(saveWallet).toHaveBeenCalledWith({ id: 'w2', values: expect.objectContaining({ name: 'Bank', type: 'cashless' }) })
- expect(deleteWallet).not.toHaveBeenCalled()
- })
-
- it('calls deleteWallet for delete ops', async () => {
- const saveWallet = vi.fn()
- const deleteWallet = vi.fn(() => Promise.resolve())
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Wallets, 'w1', 'delete'),
- ]
-
- await replayWalletOps(ops, remapIds, { deleteWallet, saveWallet })
- expect(deleteWallet).toHaveBeenCalledWith('w1')
- expect(saveWallet).not.toHaveBeenCalled()
- })
-
- it('collects remaps from save results', async () => {
- const saveWallet = vi.fn(() => Promise.resolve({ convexId: 'convex_w1', localId: 'local_w1' }))
- const deleteWallet = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Wallets, 'local_w1', 'create', { name: 'Cash', type: 'cash' }),
- ]
-
- await replayWalletOps(ops, remapIds, { deleteWallet, saveWallet })
- expect(remapIds.get('local_w1')).toBe('convex_w1')
- })
-})
-
-// --- replayCategoryOps ---
-
-describe('replayCategoryOps', () => {
- it('does nothing for empty ops', async () => {
- const saveCategory = vi.fn()
- const deleteCategory = vi.fn()
- const remapIds = new Map<string, string>()
-
- await replayCategoryOps([], remapIds, { deleteCategory, saveCategory })
- expect(saveCategory).not.toHaveBeenCalled()
- expect(deleteCategory).not.toHaveBeenCalled()
- })
-
- it('processes parent categories before children', async () => {
- const callOrder: string[] = []
- const saveCategory = vi.fn((params) => {
- callOrder.push(params.id)
- return Promise.resolve()
- })
- const deleteCategory = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'create', { name: 'Food', parentId: 0 }),
- makeOp(OfflineEntityType.Categories, 'c2', 'create', { name: 'Groceries', parentId: 'c1' }),
- ]
-
- await replayCategoryOps(ops, remapIds, { deleteCategory, saveCategory })
- expect(callOrder).toEqual(['c1', 'c2'])
- })
-
- it('remaps parentId for child categories', async () => {
- const saveCategory = vi.fn(() => Promise.resolve())
- const deleteCategory = vi.fn()
- const remapIds = new Map([['local_c1', 'convex_c1']])
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c2', 'create', { name: 'Groceries', parentId: 'local_c1' }),
- ]
-
- await replayCategoryOps(ops, remapIds, { deleteCategory, saveCategory })
- expect(saveCategory).toHaveBeenCalledWith(expect.objectContaining({
- values: expect.objectContaining({ parentId: 'convex_c1' }),
- }))
- })
-
- it('calls deleteCategory for delete ops', async () => {
- const saveCategory = vi.fn()
- const deleteCategory = vi.fn(() => Promise.resolve())
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'delete'),
- ]
-
- await replayCategoryOps(ops, remapIds, { deleteCategory, saveCategory })
- expect(deleteCategory).toHaveBeenCalledWith('c1')
- })
-
- it('always passes isUpdateChildCategoriesColor as false', async () => {
- const saveCategory = vi.fn(() => Promise.resolve())
- const deleteCategory = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Categories, 'c1', 'create', { name: 'Food', parentId: 0 }),
- ]
-
- await replayCategoryOps(ops, remapIds, { deleteCategory, saveCategory })
- expect(saveCategory).toHaveBeenCalledWith(expect.objectContaining({
- isUpdateChildCategoriesColor: false,
- }))
- })
-
- it('collects remaps from parent and child saves', async () => {
- let callCount = 0
- const saveCategory = vi.fn(() => {
- callCount++
- if (callCount === 1)
- return Promise.resolve({ convexId: 'convex_c1', localId: 'local_c1' })
- return Promise.resolve({ convexId: 'convex_c2', localId: 'local_c2' })
- })
- const deleteCategory = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Categories, 'local_c1', 'create', { name: 'Food', parentId: 0 }),
- makeOp(OfflineEntityType.Categories, 'local_c2', 'create', { name: 'Groceries', parentId: 'local_c1' }),
- ]
-
- await replayCategoryOps(ops, remapIds, { deleteCategory, saveCategory })
- expect(remapIds.get('local_c1')).toBe('convex_c1')
- expect(remapIds.get('local_c2')).toBe('convex_c2')
- })
-})
-
-// --- replayTrnOps ---
-
-describe('replayTrnOps', () => {
- const wallets = { w1: {}, w2: {} }
- const categories = { food: {} }
-
- it('does nothing for empty ops', async () => {
- const saveTrn = vi.fn()
- const deleteTrn = vi.fn()
- const removeOp = vi.fn()
- const remapIds = new Map<string, string>()
-
- const orphanCount = await replayTrnOps([], remapIds, {
- deleteTrn,
- removeOfflineOp: removeOp,
- saveTrn,
- }, { categoriesItems: categories, walletsItems: wallets })
- expect(orphanCount).toBe(0)
- expect(saveTrn).not.toHaveBeenCalled()
- expect(deleteTrn).not.toHaveBeenCalled()
- })
-
- it('calls saveTrn for valid create ops', async () => {
- const saveTrn = vi.fn()
- const deleteTrn = vi.fn()
- const removeOp = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Trns, 't1', 'create', {
- amount: 100,
- categoryId: 'food',
- date: 1000,
- type: TrnType.Expense,
- updatedAt: 1000,
- walletId: 'w1',
- }),
- ]
-
- const orphanCount = await replayTrnOps(ops, remapIds, {
- deleteTrn,
- removeOfflineOp: removeOp,
- saveTrn,
- }, { categoriesItems: categories, walletsItems: wallets })
- expect(orphanCount).toBe(0)
- expect(saveTrn).toHaveBeenCalledTimes(1)
- })
-
- it('calls deleteTrn for delete ops', async () => {
- const saveTrn = vi.fn()
- const deleteTrn = vi.fn()
- const removeOp = vi.fn()
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Trns, 't1', 'delete'),
- ]
-
- await replayTrnOps(ops, remapIds, {
- deleteTrn,
- removeOfflineOp: removeOp,
- saveTrn,
- }, { categoriesItems: categories, walletsItems: wallets })
- expect(deleteTrn).toHaveBeenCalledWith('t1')
- expect(saveTrn).not.toHaveBeenCalled()
- })
-
- it('skips orphaned trns and returns orphan count', async () => {
- const saveTrn = vi.fn()
- const deleteTrn = vi.fn()
- const removeOp = vi.fn(() => Promise.resolve())
- const remapIds = new Map<string, string>()
- const ops = [
- makeOp(OfflineEntityType.Trns, 't1', 'create', {
- amount: 100,
- categoryId: 'food',
- date: 1000,
- type: TrnType.Expense,
- updatedAt: 1000,
- walletId: 'missing_wallet',
- }),
- ]
-
- const orphanCount = await replayTrnOps(ops, remapIds, {
- deleteTrn,
- removeOfflineOp: removeOp,
- saveTrn,
- }, { categoriesItems: categories, walletsItems: wallets })
- expect(orphanCount).toBe(1)
- expect(saveTrn).not.toHaveBeenCalled()
- expect(removeOp).toHaveBeenCalledWith(OfflineEntityType.Trns, 't1')
- })
-
- it('remaps wallet and category IDs before saving', async () => {
- const saveTrn = vi.fn()
- const deleteTrn = vi.fn()
- const removeOp = vi.fn()
- const remapIds = new Map([['local_w', 'w1'], ['local_c', 'food']])
- const ops = [
- makeOp(OfflineEntityType.Trns, 't1', 'create', {
- amount: 100,
- categoryId: 'local_c',
- date: 1000,
- type: TrnType.Expense,
- updatedAt: 1000,
- walletId: 'local_w',
- }),
- ]
-
- await replayTrnOps(ops, remapIds, {
- deleteTrn,
- removeOfflineOp: removeOp,
- saveTrn,
- }, { categoriesItems: categories, walletsItems: wallets })
- expect(saveTrn).toHaveBeenCalledWith(expect.objectContaining({
- values: expect.objectContaining({ categoryId: 'food', walletId: 'w1' }),
- }))
- })
-})
-
-// --- replaySettingsOps ---
-
-describe('replaySettingsOps', () => {
- it('does nothing for empty ops', async () => {
- const saveBaseCurrency = vi.fn()
- const saveLocale = vi.fn()
-
- await replaySettingsOps([], { saveBaseCurrency, saveLocale })
- expect(saveBaseCurrency).not.toHaveBeenCalled()
- expect(saveLocale).not.toHaveBeenCalled()
- })
-
- it('calls saveBaseCurrency when baseCurrency is present', async () => {
- const saveBaseCurrency = vi.fn()
- const saveLocale = vi.fn()
- const ops = [
- makeOp(OfflineEntityType.UserSettings, 's1', 'update', { baseCurrency: 'EUR' }),
- ]
-
- await replaySettingsOps(ops, { saveBaseCurrency, saveLocale })
- expect(saveBaseCurrency).toHaveBeenCalledWith('EUR')
- expect(saveLocale).not.toHaveBeenCalled()
- })
-
- it('calls saveLocale when locale is present', async () => {
- const saveBaseCurrency = vi.fn()
- const saveLocale = vi.fn()
- const ops = [
- makeOp(OfflineEntityType.UserSettings, 's1', 'update', { locale: 'ru' }),
- ]
-
- await replaySettingsOps(ops, { saveBaseCurrency, saveLocale })
- expect(saveLocale).toHaveBeenCalledWith('ru')
- expect(saveBaseCurrency).not.toHaveBeenCalled()
- })
-
- it('calls both when both are present', async () => {
- const saveBaseCurrency = vi.fn()
- const saveLocale = vi.fn()
- const ops = [
- makeOp(OfflineEntityType.UserSettings, 's1', 'update', { baseCurrency: 'USD', locale: 'en' }),
- ]
-
- await replaySettingsOps(ops, { saveBaseCurrency, saveLocale })
- expect(saveBaseCurrency).toHaveBeenCalledWith('USD')
- expect(saveLocale).toHaveBeenCalledWith('en')
- })
-
- it('processes multiple settings ops', async () => {
- const saveBaseCurrency = vi.fn()
- const saveLocale = vi.fn()
- const ops = [
- makeOp(OfflineEntityType.UserSettings, 's1', 'update', { baseCurrency: 'EUR' }),
- makeOp(OfflineEntityType.UserSettings, 's2', 'update', { locale: 'ru' }),
- ]
-
- await replaySettingsOps(ops, { saveBaseCurrency, saveLocale })
- expect(saveBaseCurrency).toHaveBeenCalledTimes(1)
- expect(saveLocale).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/app/app/components/offline/replayHelpers.ts b/app/app/components/offline/replayHelpers.ts
deleted file mode 100644
index 54b3955a..00000000
--- a/app/app/components/offline/replayHelpers.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-import { z } from 'zod/v4'
-
-import type { CategoryItem } from '~/components/categories/types'
-import type { OfflineOp } from '~/components/offline/types'
-import type { TrnItem } from '~/components/trns/types'
-import type { WalletItem } from '~/components/wallets/types'
-
-import { categoryFormSchema } from '~/components/categories/types'
-import { localeSchema } from '~/components/locale/types'
-import { removeOfflineOp } from '~/components/offline/helpers'
-import { OfflineEntityType } from '~/components/offline/types'
-import { trnItemSchema, TrnType } from '~/components/trns/types'
-import { walletItemSchema } from '~/components/wallets/types'
-import { createLogger } from '~/utils/logger'
-
-const logger = createLogger('offline/replayHelpers')
-
-const categoryItemSchema = categoryFormSchema.extend({
- updatedAt: z.number().optional(),
-})
-
-const settingsSchema = z.object({
- baseCurrency: z.string().min(1).optional(),
- locale: localeSchema.optional(),
-}).passthrough()
-
-/**
- * Validate offline op data against a Zod schema.
- * Returns parsed data on success, or null if validation fails (logs warning and removes op).
- */
-async function validateOpData<T>(
- op: OfflineOp,
- schema: z.ZodType<T>,
- label: string,
-): Promise<T | null> {
- const result = schema.safeParse(op.data)
- if (result.success)
- return result.data
-
- logger.warn(`corrupted ${label} data, removing op ${op.entity}/${op.id}:`, result.error.issues)
- await removeOfflineOp(op.entity, op.id)
- return null
-}
-
-export function remapTrnIds(data: TrnItem, remapIds: Map<string, string>): TrnItem {
- if (data.type === TrnType.Transfer) {
- return {
- ...data,
- expenseWalletId: remapIds.get(data.expenseWalletId) ?? data.expenseWalletId,
- incomeWalletId: remapIds.get(data.incomeWalletId) ?? data.incomeWalletId,
- }
- }
- return {
- ...data,
- categoryId: remapIds.get(data.categoryId) ?? data.categoryId,
- walletId: remapIds.get(data.walletId) ?? data.walletId,
- }
-}
-
-export function isTrnOrphaned(
- data: TrnItem,
- walletsItems: Record<string, unknown>,
- categoriesItems: Record<string, unknown>,
-): boolean {
- if (data.type === TrnType.Transfer)
- return !walletsItems[data.expenseWalletId] || !walletsItems[data.incomeWalletId]
- return !walletsItems[data.walletId] || !categoriesItems[data.categoryId]
-}
-
-type GroupedOps = {
- categoryOps: OfflineOp[]
- settingsOps: OfflineOp[]
- trnOps: OfflineOp[]
- unknownOps: OfflineOp[]
- walletOps: OfflineOp[]
-}
-
-export function groupOpsByEntity(ops: OfflineOp[]): GroupedOps {
- const walletOps: OfflineOp[] = []
- const categoryOps: OfflineOp[] = []
- const trnOps: OfflineOp[] = []
- const settingsOps: OfflineOp[] = []
- const unknownOps: OfflineOp[] = []
-
- for (const op of ops) {
- switch (op.entity) {
- case OfflineEntityType.Wallets:
- walletOps.push(op)
- break
- case OfflineEntityType.Categories:
- categoryOps.push(op)
- break
- case OfflineEntityType.Trns:
- trnOps.push(op)
- break
- case OfflineEntityType.UserSettings:
- settingsOps.push(op)
- break
- default:
- unknownOps.push(op)
- }
- }
-
- return { categoryOps, settingsOps, trnOps, unknownOps, walletOps }
-}
-
-/**
- * Split category ops into parent-first and child-second groups.
- * Delete ops go into parents (processed first).
- */
-export function splitCategoryOps(ops: OfflineOp[]): {
- childOps: OfflineOp[]
- parentOps: OfflineOp[]
-} {
- const parentOps: OfflineOp[] = []
- const childOps: OfflineOp[] = []
-
- for (const op of ops) {
- if (op.type === 'delete') {
- parentOps.push(op)
- continue
- }
- const data = op.data as Record<string, unknown> | undefined
- const parentId = data?.parentId
- if (!parentId || parentId === 0) {
- parentOps.push(op)
- }
- else {
- childOps.push(op)
- }
- }
-
- return { childOps, parentOps }
-}
-
-export function extractRemaps(results: unknown[]): Array<{ convexId: string, localId: string }> {
- const remaps: Array<{ convexId: string, localId: string }> = []
- for (const r of results) {
- if (r && typeof r === 'object' && 'localId' in r && 'convexId' in r)
- remaps.push({ convexId: r.convexId as string, localId: r.localId as string })
- }
- return remaps
-}
-
-export async function collectRemaps(promises: (Promise<unknown> | void | undefined)[], remapIds: Map<string, string>): Promise<void> {
- const results = await Promise.all(promises.map(p => p ?? Promise.resolve()))
- for (const { convexId, localId } of extractRemaps(results)) {
- remapIds.set(localId, convexId)
- }
-}
-
-type WalletActions = {
- deleteWallet: (id: string) => Promise<unknown> | void | undefined
- saveWallet: (params: { id: string, values: WalletItem }) => Promise<unknown> | void | undefined
-}
-
-export async function replayWalletOps(ops: OfflineOp[], remapIds: Map<string, string>, actions: WalletActions): Promise<void> {
- if (ops.length === 0)
- return
-
- const promises: (Promise<unknown> | void | undefined)[] = []
- for (const op of ops) {
- if (op.type === 'delete') {
- promises.push(actions.deleteWallet(op.id))
- continue
- }
- const values = await validateOpData<WalletItem>(op, walletItemSchema, 'wallet')
- if (!values)
- continue
- promises.push(actions.saveWallet({ id: op.id, values }))
- }
- await collectRemaps(promises, remapIds)
-}
-
-type CategoryActions = {
- deleteCategory: (id: string) => Promise<unknown> | void | undefined
- saveCategory: (params: { id: string, isUpdateChildCategoriesColor: boolean, values: CategoryItem }) => Promise<unknown> | void | undefined
-}
-
-/** Parents first, then children (with parentId remapping). */
-export async function replayCategoryOps(ops: OfflineOp[], remapIds: Map<string, string>, actions: CategoryActions): Promise<void> {
- if (ops.length === 0)
- return
-
- const { childOps, parentOps } = splitCategoryOps(ops)
-
- if (parentOps.length > 0) {
- const promises: (Promise<unknown> | void | undefined)[] = []
- for (const op of parentOps) {
- if (op.type === 'delete') {
- promises.push(actions.deleteCategory(op.id))
- continue
- }
- const values = await validateOpData<CategoryItem>(op, categoryItemSchema, 'category')
- if (!values)
- continue
- promises.push(actions.saveCategory({
- id: op.id,
- isUpdateChildCategoriesColor: false,
- values,
- }))
- }
- await collectRemaps(promises, remapIds)
- }
-
- if (childOps.length > 0) {
- const promises: (Promise<unknown> | void | undefined)[] = []
- for (const op of childOps) {
- const data = await validateOpData<CategoryItem>(op, categoryItemSchema, 'category')
- if (!data)
- continue
- const remappedParentId = remapIds.get(String(data.parentId)) ?? data.parentId
- const values = remappedParentId !== data.parentId
- ? { ...data, parentId: remappedParentId }
- : data
- promises.push(actions.saveCategory({
- id: op.id,
- isUpdateChildCategoriesColor: false,
- values,
- }))
- }
- await collectRemaps(promises, remapIds)
- }
-}
-
-type TrnActions = {
- deleteTrn: (id: string) => void
- removeOfflineOp: (entity: string, id: string) => Promise<void>
- saveTrn: (params: { id: string, values: TrnItem }) => void
-}
-
-type TrnContext = {
- categoriesItems: Record<string, unknown>
- walletsItems: Record<string, unknown>
-}
-
-/** Returns count of orphaned trns that were skipped. */
-export async function replayTrnOps(ops: OfflineOp[], remapIds: Map<string, string>, actions: TrnActions, context: TrnContext): Promise<number> {
- if (ops.length === 0)
- return 0
-
- let orphanCount = 0
-
- for (const op of ops) {
- if (op.type === 'delete') {
- actions.deleteTrn(op.id)
- continue
- }
-
- const data = await validateOpData<TrnItem>(op, trnItemSchema, 'trn')
- if (!data)
- continue
-
- const remapped = remapTrnIds(data, remapIds)
-
- if (isTrnOrphaned(remapped, context.walletsItems, context.categoriesItems)) {
- orphanCount++
- try {
- await actions.removeOfflineOp(op.entity, op.id)
- }
- catch (e) {
- logger.warn(`failed to remove orphan op ${op.entity}/${op.id}:`, e)
- }
- continue
- }
-
- actions.saveTrn({ id: op.id, values: remapped })
- }
-
- return orphanCount
-}
-
-type SettingsActions = {
- saveBaseCurrency: (currency: string) => void
- saveLocale: (locale: string) => void
-}
-
-export async function replaySettingsOps(ops: OfflineOp[], actions: SettingsActions): Promise<void> {
- for (const op of ops) {
- const settings = await validateOpData(op, settingsSchema, 'settings')
- if (!settings)
- continue
- if (settings.baseCurrency)
- actions.saveBaseCurrency(settings.baseCurrency)
- if (settings.locale)
- actions.saveLocale(settings.locale)
- }
-}
diff --git a/app/app/components/offline/types.ts b/app/app/components/offline/types.ts
deleted file mode 100644
index 80ccf7f6..00000000
--- a/app/app/components/offline/types.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export const OfflineEntityType = {
- Categories: 'categories',
- Trns: 'trns',
- UserSettings: 'userSettings',
- Wallets: 'wallets',
-} as const
-
-export type EntityType = typeof OfflineEntityType[keyof typeof OfflineEntityType]
-
-export type OfflineOpData = Record<string, unknown>
-
-export type OfflineOp = {
- data?: OfflineOpData
- entity: EntityType
- id: string
- timestamp: number
- type: 'create' | 'delete' | 'update'
-}
-
-/** Accepted input for pushOfflineOp — allows typed domain objects */
-export type OfflineOpInput = Omit<OfflineOp, 'data' | 'timestamp'> & {
- data?: Record<string, unknown>
-}
diff --git a/app/app/composables/useAuth.ts b/app/app/composables/useAuth.ts
deleted file mode 100644
index b040ceb4..00000000
--- a/app/app/composables/useAuth.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { convexClient, crossDomainClient } from '@convex-dev/better-auth/client/plugins'
-import { createAuthClient } from 'better-auth/vue'
-
-function createClient(siteUrl: string) {
- return createAuthClient({
- baseURL: siteUrl,
- plugins: [
- convexClient(),
- crossDomainClient(),
- ],
- })
-}
-
-type AuthClient = ReturnType<typeof createClient>
-
-export function useAuth(): AuthClient {
- const nuxtApp = useNuxtApp() as { _authClient?: AuthClient } & ReturnType<typeof useNuxtApp>
-
- if (!nuxtApp._authClient) {
- const config = useRuntimeConfig()
- const siteUrl = config.public.convexSiteUrl as string
- nuxtApp._authClient = createClient(siteUrl)
- }
-
- return nuxtApp._authClient
-}
diff --git a/app/app/composables/useAuthCookie.test.ts b/app/app/composables/useAuthCookie.test.ts
deleted file mode 100644
index f4346cb3..00000000
--- a/app/app/composables/useAuthCookie.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-describe('useAuthCookie', () => {
- let cookieJar: string
-
- beforeEach(() => {
- cookieJar = ''
- vi.stubGlobal('document', {
- get cookie() { return cookieJar },
- set cookie(val: string) { cookieJar = val },
- })
- vi.resetModules()
- })
-
- afterEach(() => {
- vi.unstubAllGlobals()
- })
-
- describe('hasAuthCookie', () => {
- it('returns true when cookie exists', async () => {
- const { hasAuthCookie } = await import('~/composables/useAuthCookie')
- cookieJar = 'other=1; finapp.localAuthUid=abc'
- expect(hasAuthCookie()).toBe(true)
- })
-
- it('returns false when cookie absent', async () => {
- const { hasAuthCookie } = await import('~/composables/useAuthCookie')
- cookieJar = 'other=1'
- expect(hasAuthCookie()).toBe(false)
- })
- })
-
- describe('setAuthCookie', () => {
- it('writes cookie with correct flags', async () => {
- const { setAuthCookie } = await import('~/composables/useAuthCookie')
- setAuthCookie('user-123')
- expect(cookieJar).toBe('finapp.localAuthUid=user-123;path=/;max-age=31536000;SameSite=Lax')
- })
-
- it('encodes uid to prevent cookie injection', async () => {
- const { setAuthCookie } = await import('~/composables/useAuthCookie')
- setAuthCookie('a=b;c=d')
- expect(cookieJar).toContain('finapp.localAuthUid=a%3Db%3Bc%3Dd')
- })
- })
-
- describe('clearAuthCookie', () => {
- it('flags match setAuthCookie with max-age=0', async () => {
- const { clearAuthCookie } = await import('~/composables/useAuthCookie')
- clearAuthCookie()
- expect(cookieJar).toBe('finapp.localAuthUid=;path=/;max-age=0;SameSite=Lax')
- })
- })
-
- describe('secure flag', () => {
- it('included on https', async () => {
- vi.stubGlobal('location', { protocol: 'https:' })
- vi.resetModules()
- const { setAuthCookie } = await import('~/composables/useAuthCookie')
- setAuthCookie('uid')
- expect(cookieJar).toContain(';Secure')
- })
-
- it('omitted on http', async () => {
- vi.stubGlobal('location', { protocol: 'http:' })
- vi.resetModules()
- const { setAuthCookie } = await import('~/composables/useAuthCookie')
- setAuthCookie('uid')
- expect(cookieJar).not.toContain('Secure')
- })
- })
-})
diff --git a/app/app/composables/useAuthCookie.ts b/app/app/composables/useAuthCookie.ts
deleted file mode 100644
index cf4002fd..00000000
--- a/app/app/composables/useAuthCookie.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-let _sessionInitialized = false
-
-export function isSessionInitialized(): boolean {
- return _sessionInitialized
-}
-
-export function setSessionInitialized(value: boolean) {
- _sessionInitialized = value
-}
-
-export function hasAuthCookie(): boolean {
- return /(?:^|;\s*)finapp\.localAuthUid=/.test(document.cookie)
-}
-
-const secureSuffix = globalThis.location?.protocol === 'https:' ? ';Secure' : ''
-
-export function setAuthCookie(uid: string) {
- const ONE_YEAR = 60 * 60 * 24 * 365
- document.cookie = `finapp.localAuthUid=${encodeURIComponent(uid)};path=/;max-age=${ONE_YEAR};SameSite=Lax${secureSuffix}`
-}
-
-export function clearAuthCookie() {
- document.cookie = `finapp.localAuthUid=;path=/;max-age=0;SameSite=Lax${secureSuffix}`
-}
diff --git a/app/app/composables/useConvex.ts b/app/app/composables/useConvex.ts
deleted file mode 100644
index b5395bd0..00000000
--- a/app/app/composables/useConvex.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { ConvexClient } from 'convex/browser'
-
-import { api } from '~~/convex/_generated/api'
-
-export function useConvexClient(): ConvexClient {
- const { $convex } = useNuxtApp()
- return $convex as ConvexClient
-}
-
-export function useConvexClientWithApi() {
- return {
- api,
- client: useConvexClient(),
- }
-}
diff --git a/app/app/composables/useRealtimeSync.ts b/app/app/composables/useRealtimeSync.ts
deleted file mode 100644
index 5e815fb6..00000000
--- a/app/app/composables/useRealtimeSync.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import type { FunctionReference } from 'convex/server'
-
-import localforage from 'localforage'
-
-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { STORAGE_KEYS } from '~/components/offline/storageKeys'
-import { useTrnsStore } from '~/components/trns/useTrnsStore'
-import { useUserStore } from '~/components/user/useUserStore'
-import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-import { createLogger } from '~/utils/logger'
-
-const logger = createLogger('realtime')
-
-export type RealtimeDelta<TDoc> = {
- deletedIds: string[]
- docs: TDoc[]
- serverTime: number
- truncated: boolean
-}
-
-export type SubscriptionHandle = {
- label: string
- stop: () => void
-}
-
-type ConvexOnUpdateClient = {
- onUpdate: <T>(query: FunctionReference<'query'>, args: Record<string, unknown>, cb: (value: T) => void, onError?: (e: Error) => void) => () => void
-}
-
-let _handles: SubscriptionHandle[] = []
-const _lastErrorByLabel = new Map<string, string>()
-
-function handleSubscriptionError(label: string, error: Error): void {
- if (_lastErrorByLabel.get(label) === error.message)
- return
- _lastErrorByLabel.set(label, error.message)
- logger.warn(`${label}: subscription error`, error.message)
-}
-
-/**
- * Subscribe to a delta query. Convex keeps the subscription reactive — it
- * re-runs the query on the server whenever the dependent tables change and
- * pushes the updated result to `applyPatch`. No manual re-subscribe needed.
- *
- * `applyPatch` is expected to be idempotent (skip already-applied docs via
- * `updatedAt` monotonic check) because the server result accumulates all
- * changes since `initialSince`. A `truncated` flag signals the caller should
- * fall back to a fullSync; returning `null` from applyPatch stops the sub.
- */
-export function subscribeDelta<TDoc>(opts: {
- applyPatch: (patch: RealtimeDelta<TDoc>) => Promise<number | null> | number | null
- client: ConvexOnUpdateClient
- initialSince: number
- label: string
- query: FunctionReference<'query'>
-}): SubscriptionHandle {
- let stopped = false
-
- const stopInner = opts.client.onUpdate(opts.query, { since: opts.initialSince }, async (value: RealtimeDelta<TDoc> | null) => {
- if (!value || stopped)
- return
- if (value.truncated)
- logger.warn(`${opts.label}: truncated delta, caller should fullSync`)
- const next = await opts.applyPatch(value)
- if (next === null)
- stop()
- }, (error) => {
- if (stopped)
- return
- handleSubscriptionError(opts.label, error)
- })
-
- function stop(): void {
- stopped = true
- stopInner()
- }
-
- return { label: opts.label, stop }
-}
-
-export function stopAllRealtime(): void {
- for (const h of _handles) {
- try {
- h.stop()
- }
- catch (e) {
- logger.warn(`stop ${h.label} failed`, e)
- }
- }
- if (_handles.length > 0)
- logger.log(`stopped ${_handles.length} subscriptions`)
- _handles = []
- _lastErrorByLabel.clear()
-}
-
-export async function startAllRealtime(): Promise<void> {
- stopAllRealtime()
-
- const { api, client } = useConvexClientWithApi()
- const onUpdateClient = client as unknown as ConvexOnUpdateClient
-
- const trnsStore = useTrnsStore()
- const walletsStore = useWalletsStore()
- const categoriesStore = useCategoriesStore()
- const userStore = useUserStore()
-
- const trnsMeta = await localforage.getItem<{ lastSyncedAt: number }>(STORAGE_KEYS.trnsSyncMeta)
- const trnsSince = trnsMeta?.lastSyncedAt ?? Date.now()
-
- _handles.push(subscribeDelta({
- applyPatch: patch => trnsStore.applyRealtimePatch(patch as never),
- client: onUpdateClient,
- initialSince: trnsSince,
- label: 'trns',
- query: api.trns.deltaRealtime,
- }))
-
- _handles.push(subscribeDelta({
- applyPatch: patch => walletsStore.applyRealtimePatch(patch as never),
- client: onUpdateClient,
- initialSince: walletsStore.lastSyncedAt || Date.now(),
- label: 'wallets',
- query: api.wallets.deltaRealtime,
- }))
-
- _handles.push(subscribeDelta({
- applyPatch: patch => categoriesStore.applyRealtimePatch(patch as never),
- client: onUpdateClient,
- initialSince: categoriesStore.lastSyncedAt || Date.now(),
- label: 'categories',
- query: api.categories.deltaRealtime,
- }))
-
- const stopSettings = onUpdateClient.onUpdate(api.user.get, {}, (settings) => {
- userStore.applyRealtimeSettings(settings)
- }, (error) => {
- handleSubscriptionError('userSettings', error)
- })
- _handles.push({ label: 'userSettings', stop: stopSettings })
-
- logger.log(`started ${_handles.length} subscriptions`)
-}
diff --git a/app/app/pages/auth/callback.vue b/app/app/pages/auth/callback.vue
deleted file mode 100644
index 1cbb244a..00000000
--- a/app/app/pages/auth/callback.vue
+++ /dev/null
@@ -1,72 +0,0 @@
-<script setup lang="ts">
-import { hasAuthCookie } from '~/composables/useAuthCookie'
-import { showErrorToast } from '~/composables/useStoreSync'
-
-definePageMeta({
- layout: 'empty',
-})
-
-const route = useRoute()
-const logger = createLogger('auth/callback')
-
-onMounted(async () => {
- const ott = route.query.ott as string
- if (!ott) {
- navigateTo('/login', { replace: true })
- return
- }
-
- if (hasAuthCookie()) {
- const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
- localStorage.removeItem('finapp.authRedirect')
- navigateTo(redirectTo, { replace: true })
- return
- }
-
- const authClient = useAuth()
-
- try {
- const result = await authClient.$fetch<{
- session: { expiresAt: number, token: string }
- }>('/cross-domain/one-time-token/verify', {
- body: { token: ott },
- method: 'POST',
- })
-
- if (!result.data?.session?.token) {
- navigateTo('/login', { replace: true })
- return
- }
-
- const session = await authClient.getSession()
-
- if (session.data?.user) {
- const uid = session.data.user.id
-
- setAuthCookie(uid)
-
- const { $ensureConvexAuth } = useNuxtApp()
- ;($ensureConvexAuth as () => void)()
-
- const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
- localStorage.removeItem('finapp.authRedirect')
-
- navigateTo(redirectTo, { replace: true })
- return
- }
- }
- catch (error: unknown) {
- logger.error('Error:', error)
- showErrorToast('login.error')
- }
-
- localStorage.removeItem('finapp.authRedirect')
- navigateTo('/login', { replace: true })
-})
-</script>
-
-<template>
- <div class="flex-center h-dvh">
- <UIcon name="lucide:loader-circle" class="text-muted size-6 animate-spin" />
- </div>
-</template>
diff --git a/app/app/plugins/convex.ts b/app/app/plugins/convex.ts
deleted file mode 100644
index 7bf42d36..00000000
--- a/app/app/plugins/convex.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { createConvexClient } from '~~/services/convex/client'
-
-import { clearAuthCookie, hasAuthCookie } from '~/composables/useAuthCookie'
-import { createLogger } from '~/utils/logger'
-
-const logger = createLogger('convex')
-
-export default defineNuxtPlugin(() => {
- // Request persistent storage to protect IndexedDB data from automatic
- // eviction on iOS Safari and Android Chrome when device is low on space.
- navigator.storage?.persist?.()
-
- const config = useRuntimeConfig()
- const convexUrl = config.public.convexUrl as string
-
- if (!convexUrl)
- throw new Error('CONVEX_URL is not set in environment variables')
-
- const client = createConvexClient(convexUrl)
- const authClient = useAuth()
- const session = authClient.useSession()
-
- let authReadyResolve: (() => void) | null = null
- let authReadyPromise: Promise<void> | null = null
-
- const fetchToken = async (_opts: { forceRefreshToken: boolean }) => {
- if (!hasAuthCookie() || !navigator.onLine) {
- authReadyResolve?.()
- return null
- }
-
- try {
- const { data } = await authClient.convex.token()
- const token = data?.token || null
- authReadyResolve?.()
- return token
- }
- catch (error) {
- if (navigator.onLine)
- logger.error('fetchConvexToken error:', error)
- authReadyResolve?.()
- return null
- }
- }
-
- function startAuth() {
- authReadyPromise = new Promise<void>((resolve) => {
- authReadyResolve = resolve
- })
- client.setAuth(fetchToken)
- // Eagerly fetch token so authReadyPromise resolves immediately,
- // rather than waiting for the Convex client to schedule fetchToken.
- fetchToken({ forceRefreshToken: false })
- }
-
- let authSet = false
- if (hasAuthCookie() && navigator.onLine) {
- startAuth()
- authSet = true
- }
-
- // Ignore isPending and error states to avoid logging out on network failures.
- watch(
- () => {
- const s = session.value
- if (!s || s.isPending)
- return undefined
- if (s.error)
- return undefined
- return s.data?.user?.id ?? null
- },
- (resolvedUid) => {
- if (resolvedUid === undefined)
- return
- if (resolvedUid) {
- if (!authSet) {
- startAuth()
- authSet = true
- }
- }
- else {
- client.client.clearAuth()
- authSet = false
- clearAuthCookie()
- }
- },
- )
-
- window.addEventListener('online', () => {
- if (hasAuthCookie()) {
- startAuth()
- authSet = true
- }
- })
-
- function ensureConvexAuth() {
- if (hasAuthCookie()) {
- startAuth()
- authSet = true
- }
- }
-
- function waitForAuth(): Promise<void> {
- return authReadyPromise ?? Promise.resolve()
- }
-
- return {
- provide: {
- convex: client,
- ensureConvexAuth,
- waitForConvexAuth: waitForAuth,
- },
- }
-})
diff --git a/app/app/utils/convexId.test.ts b/app/app/utils/convexId.test.ts
deleted file mode 100644
index 565cfcf6..00000000
--- a/app/app/utils/convexId.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { cleanupFrontendIds, isLocalId } from '~/utils/convexId'
-
-describe('cleanupFrontendIds', () => {
- it('removes stale local IDs not in pending queue', () => {
- const data = { local_abc: { n: 1 }, server123: { n: 2 } }
- const result = cleanupFrontendIds(data, {})
-
- expect(result).not.toHaveProperty('local_abc')
- expect(result).toHaveProperty('server123')
- })
-
- it('keeps local IDs that are still pending', () => {
- const data = { local_abc: { n: 1 }, local_def: { n: 2 } }
- const pending = { local_abc: { n: 1 } }
- const result = cleanupFrontendIds(data, pending)
-
- expect(result).toHaveProperty('local_abc')
- expect(result).not.toHaveProperty('local_def')
- })
-
- it('does not mutate original data', () => {
- const data = { local_abc: { n: 1 } }
- cleanupFrontendIds(data, {})
-
- expect(data).toHaveProperty('local_abc')
- })
-})
-
-describe('generateId + isLocalId contract', () => {
- it('generateId produces IDs recognized by isLocalId', async () => {
- const { generateId } = await import('~~/utils/generateId')
-
- expect(isLocalId(generateId())).toBe(true)
- })
-})
diff --git a/app/app/utils/convexId.ts b/app/app/utils/convexId.ts
deleted file mode 100644
index ec018fdc..00000000
--- a/app/app/utils/convexId.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { GenericId } from 'convex/values'
-import type { TableNames } from '~~/convex/_generated/dataModel'
-
-export function asConvexId<T extends TableNames>(id: string): GenericId<T> {
- return id as unknown as GenericId<T>
-}
-
-export function isLocalId(id: string): boolean {
- return id.startsWith('local_')
-}
-
-/**
- * Remove stale frontend-generated IDs from data.
- * Keeps IDs that are in the pending offline queue (awaiting creation).
- */
-export function cleanupFrontendIds<T>(
- data: Record<string, T>,
- pendingUpdates: Record<string, T>,
-): Record<string, T> {
- const result = { ...data }
- for (const id of Object.keys(result)) {
- if (isLocalId(id) && !pendingUpdates[id])
- delete result[id]
- }
- return result
-}
diff --git a/app/convex/_generated/api.d.ts b/app/convex/_generated/api.d.ts
deleted file mode 100644
index b0fd038f..00000000
--- a/app/convex/_generated/api.d.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/* eslint-disable */
-/**
- * Generated `api` utility.
- *
- * THIS CODE IS AUTOMATICALLY GENERATED.
- *
- * To regenerate, run `npx convex dev`.
- * @module
- */
-
-import type * as auth from "../auth.js";
-import type * as categories from "../categories.js";
-import type * as crons from "../crons.js";
-import type * as http from "../http.js";
-import type * as migrate from "../migrate.js";
-import type * as rates from "../rates.js";
-import type * as shared from "../shared.js";
-import type * as tombstones from "../tombstones.js";
-import type * as trns from "../trns.js";
-import type * as trnsHash from "../trnsHash.js";
-import type * as user from "../user.js";
-import type * as validators from "../validators.js";
-import type * as wallets from "../wallets.js";
-
-import type {
- ApiFromModules,
- FilterApi,
- FunctionReference,
-} from "convex/server";
-
-declare const fullApi: ApiFromModules<{
- auth: typeof auth;
- categories: typeof categories;
- crons: typeof crons;
- http: typeof http;
- migrate: typeof migrate;
- rates: typeof rates;
- shared: typeof shared;
- tombstones: typeof tombstones;
- trns: typeof trns;
- trnsHash: typeof trnsHash;
- user: typeof user;
- validators: typeof validators;
- wallets: typeof wallets;
-}>;
-
-/**
- * A utility for referencing Convex functions in your app's public API.
- *
- * Usage:
- * ```js
- * const myFunctionReference = api.myModule.myFunction;
- * ```
- */
-export declare const api: FilterApi<
- typeof fullApi,
- FunctionReference<any, "public">
->;
-
-/**
- * A utility for referencing Convex functions in your app's internal API.
- *
- * Usage:
- * ```js
- * const myFunctionReference = internal.myModule.myFunction;
- * ```
- */
-export declare const internal: FilterApi<
- typeof fullApi,
- FunctionReference<any, "internal">
->;
-
-export declare const components: {
- betterAuth: import("@convex-dev/better-auth/_generated/component.js").ComponentApi<"betterAuth">;
-};
diff --git a/app/convex/_generated/api.js b/app/convex/_generated/api.js
deleted file mode 100644
index 44bf9858..00000000
--- a/app/convex/_generated/api.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* eslint-disable */
-/**
- * Generated `api` utility.
- *
- * THIS CODE IS AUTOMATICALLY GENERATED.
- *
- * To regenerate, run `npx convex dev`.
- * @module
- */
-
-import { anyApi, componentsGeneric } from "convex/server";
-
-/**
- * A utility for referencing Convex functions in your app's API.
- *
- * Usage:
- * ```js
- * const myFunctionReference = api.myModule.myFunction;
- * ```
- */
-export const api = anyApi;
-export const internal = anyApi;
-export const components = componentsGeneric();
diff --git a/app/convex/_generated/dataModel.d.ts b/app/convex/_generated/dataModel.d.ts
deleted file mode 100644
index f97fd194..00000000
--- a/app/convex/_generated/dataModel.d.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/* eslint-disable */
-/**
- * Generated data model types.
- *
- * THIS CODE IS AUTOMATICALLY GENERATED.
- *
- * To regenerate, run `npx convex dev`.
- * @module
- */
-
-import type {
- DataModelFromSchemaDefinition,
- DocumentByName,
- TableNamesInDataModel,
- SystemTableNames,
-} from "convex/server";
-import type { GenericId } from "convex/values";
-import schema from "../schema.js";
-
-/**
- * The names of all of your Convex tables.
- */
-export type TableNames = TableNamesInDataModel<DataModel>;
-
-/**
- * The type of a document stored in Convex.
- *
- * @typeParam TableName - A string literal type of the table name (like "users").
- */
-export type Doc<TableName extends TableNames> = DocumentByName<
- DataModel,
- TableName
->;
-
-/**
- * An identifier for a document in Convex.
- *
- * Convex documents are uniquely identified by their `Id`, which is accessible
- * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
- *
- * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
- *
- * IDs are just strings at runtime, but this type can be used to distinguish them from other
- * strings when type checking.
- *
- * @typeParam TableName - A string literal type of the table name (like "users").
- */
-export type Id<TableName extends TableNames | SystemTableNames> =
- GenericId<TableName>;
-
-/**
- * A type describing your Convex data model.
- *
- * This type includes information about what tables you have, the type of
- * documents stored in those tables, and the indexes defined on them.
- *
- * This type is used to parameterize methods like `queryGeneric` and
- * `mutationGeneric` to make them type-safe.
- */
-export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
diff --git a/app/convex/_generated/server.d.ts b/app/convex/_generated/server.d.ts
deleted file mode 100644
index bec05e68..00000000
--- a/app/convex/_generated/server.d.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/* eslint-disable */
-/**
- * Generated utilities for implementing server-side Convex query and mutation functions.
- *
- * THIS CODE IS AUTOMATICALLY GENERATED.
- *
- * To regenerate, run `npx convex dev`.
- * @module
- */
-
-import {
- ActionBuilder,
- HttpActionBuilder,
- MutationBuilder,
- QueryBuilder,
- GenericActionCtx,
- GenericMutationCtx,
- GenericQueryCtx,
- GenericDatabaseReader,
- GenericDatabaseWriter,
-} from "convex/server";
-import type { DataModel } from "./dataModel.js";
-
-/**
- * Define a query in this Convex app's public API.
- *
- * This function will be allowed to read your Convex database and will be accessible from the client.
- *
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
- */
-export declare const query: QueryBuilder<DataModel, "public">;
-
-/**
- * Define a query that is only accessible from other Convex functions (but not from the client).
- *
- * This function will be allowed to read from your Convex database. It will not be accessible from the client.
- *
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
- */
-export declare const internalQuery: QueryBuilder<DataModel, "internal">;
-
-/**
- * Define a mutation in this Convex app's public API.
- *
- * This function will be allowed to modify your Convex database and will be accessible from the client.
- *
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
- */
-export declare const mutation: MutationBuilder<DataModel, "public">;
-
-/**
- * Define a mutation that is only accessible from other Convex functions (but not from the client).
- *
- * This function will be allowed to modify your Convex database. It will not be accessible from the client.
- *
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
- */
-export declare const internalMutation: MutationBuilder<DataModel, "internal">;
-
-/**
- * Define an action in this Convex app's public API.
- *
- * An action is a function which can execute any JavaScript code, including non-deterministic
- * code and code with side-effects, like calling third-party services.
- * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
- * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
- *
- * @param func - The action. It receives an {@link ActionCtx} as its first argument.
- * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
- */
-export declare const action: ActionBuilder<DataModel, "public">;
-
-/**
- * Define an action that is only accessible from other Convex functions (but not from the client).
- *
- * @param func - The function. It receives an {@link ActionCtx} as its first argument.
- * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
- */
-export declare const internalAction: ActionBuilder<DataModel, "internal">;
-
-/**
- * Define an HTTP action.
- *
- * The wrapped function will be used to respond to HTTP requests received
- * by a Convex deployment if the requests matches the path and method where
- * this action is routed. Be sure to route your httpAction in `convex/http.js`.
- *
- * @param func - The function. It receives an {@link ActionCtx} as its first argument
- * and a Fetch API `Request` object as its second.
- * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
- */
-export declare const httpAction: HttpActionBuilder;
-
-/**
- * A set of services for use within Convex query functions.
- *
- * The query context is passed as the first argument to any Convex query
- * function run on the server.
- *
- * This differs from the {@link MutationCtx} because all of the services are
- * read-only.
- */
-export type QueryCtx = GenericQueryCtx<DataModel>;
-
-/**
- * A set of services for use within Convex mutation functions.
- *
- * The mutation context is passed as the first argument to any Convex mutation
- * function run on the server.
- */
-export type MutationCtx = GenericMutationCtx<DataModel>;
-
-/**
- * A set of services for use within Convex action functions.
- *
- * The action context is passed as the first argument to any Convex action
- * function run on the server.
- */
-export type ActionCtx = GenericActionCtx<DataModel>;
-
-/**
- * An interface to read from the database within Convex query functions.
- *
- * The two entry points are {@link DatabaseReader.get}, which fetches a single
- * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
- * building a query.
- */
-export type DatabaseReader = GenericDatabaseReader<DataModel>;
-
-/**
- * An interface to read from and write to the database within Convex mutation
- * functions.
- *
- * Convex guarantees that all writes within a single mutation are
- * executed atomically, so you never have to worry about partial writes leaving
- * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
- * for the guarantees Convex provides your functions.
- */
-export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
diff --git a/app/convex/_generated/server.js b/app/convex/_generated/server.js
deleted file mode 100644
index bf3d25ad..00000000
--- a/app/convex/_generated/server.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* eslint-disable */
-/**
- * Generated utilities for implementing server-side Convex query and mutation functions.
- *
- * THIS CODE IS AUTOMATICALLY GENERATED.
- *
- * To regenerate, run `npx convex dev`.
- * @module
- */
-
-import {
- actionGeneric,
- httpActionGeneric,
- queryGeneric,
- mutationGeneric,
- internalActionGeneric,
- internalMutationGeneric,
- internalQueryGeneric,
-} from "convex/server";
-
-/**
- * Define a query in this Convex app's public API.
- *
- * This function will be allowed to read your Convex database and will be accessible from the client.
- *
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
- */
-export const query = queryGeneric;
-
-/**
- * Define a query that is only accessible from other Convex functions (but not from the client).
- *
- * This function will be allowed to read from your Convex database. It will not be accessible from the client.
- *
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
- */
-export const internalQuery = internalQueryGeneric;
-
-/**
- * Define a mutation in this Convex app's public API.
- *
- * This function will be allowed to modify your Convex database and will be accessible from the client.
- *
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
- */
-export const mutation = mutationGeneric;
-
-/**
- * Define a mutation that is only accessible from other Convex functions (but not from the client).
- *
- * This function will be allowed to modify your Convex database. It will not be accessible from the client.
- *
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
- */
-export const internalMutation = internalMutationGeneric;
-
-/**
- * Define an action in this Convex app's public API.
- *
- * An action is a function which can execute any JavaScript code, including non-deterministic
- * code and code with side-effects, like calling third-party services.
- * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
- * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
- *
- * @param func - The action. It receives an {@link ActionCtx} as its first argument.
- * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
- */
-export const action = actionGeneric;
-
-/**
- * Define an action that is only accessible from other Convex functions (but not from the client).
- *
- * @param func - The function. It receives an {@link ActionCtx} as its first argument.
- * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
- */
-export const internalAction = internalActionGeneric;
-
-/**
- * Define an HTTP action.
- *
- * The wrapped function will be used to respond to HTTP requests received
- * by a Convex deployment if the requests matches the path and method where
- * this action is routed. Be sure to route your httpAction in `convex/http.js`.
- *
- * @param func - The function. It receives an {@link ActionCtx} as its first argument
- * and a Fetch API `Request` object as its second.
- * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
- */
-export const httpAction = httpActionGeneric;
diff --git a/app/convex/auth.config.ts b/app/convex/auth.config.ts
deleted file mode 100644
index 68b60e9c..00000000
--- a/app/convex/auth.config.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { AuthConfig } from 'convex/server'
-
-import { getAuthConfigProvider } from '@convex-dev/better-auth/auth-config'
-
-export default {
- providers: [getAuthConfigProvider()],
-} satisfies AuthConfig
diff --git a/app/convex/auth.ts b/app/convex/auth.ts
deleted file mode 100644
index c80f8216..00000000
--- a/app/convex/auth.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { GenericCtx } from '@convex-dev/better-auth'
-
-import { createClient } from '@convex-dev/better-auth'
-import { convex, crossDomain } from '@convex-dev/better-auth/plugins'
-import { betterAuth } from 'better-auth'
-
-import type { DataModel } from './_generated/dataModel'
-
-import { components } from './_generated/api'
-import authConfig from './auth.config'
-
-const siteUrl = process.env.CONVEX_SITE_URL!
-const appUrl = process.env.APP_URL!
-
-export const authComponent = createClient<DataModel>(components.betterAuth)
-
-function createAuth(ctx: GenericCtx<DataModel>) {
- return betterAuth({
- account: {
- encryptOAuthTokens: true,
- },
- baseURL: siteUrl,
- database: authComponent.adapter(ctx),
- onAPIError: {
- errorURL: `${appUrl}/login`,
- },
- plugins: [
- convex({
- authConfig,
- jwksRotateOnTokenGenerationError: true,
- }),
- crossDomain({
- siteUrl: appUrl,
- }),
- ],
- session: {
- expiresIn: 60 * 60 * 24 * 30, // 30 days
- updateAge: 60 * 60 * 24, // 1 day (refresh on each visit)
- },
- socialProviders: {
- google: {
- clientId: process.env.GOOGLE_CLIENT_ID!,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
- },
- },
- trustedOrigins: [appUrl],
- })
-}
-
-export { createAuth }
diff --git a/app/convex/categories.test.ts b/app/convex/categories.test.ts
deleted file mode 100644
index d9bc91b7..00000000
--- a/app/convex/categories.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { convexTest } from 'convex-test'
-import { describe, expect, it } from 'vitest'
-
-import { api } from './_generated/api'
-import schema from './schema'
-import { modules } from './test_utils/setup.helper'
-
-const validCategory = {
- color: '#ff0000',
- icon: 'food',
- name: 'Food',
- showInLastUsed: true,
- showInQuickSelector: true,
-}
-
-const validWallet = {
- color: '#000',
- currency: 'USD',
- name: 'Cash',
- order: 0,
- type: 'cash' as const,
-}
-
-describe('convex/categories', () => {
- describe('create', () => {
- it('creates a root category', async () => {
- const t = convexTest(schema, modules)
- const id = await t.mutation(api.categories.create, validCategory)
-
- const categories = await t.query(api.categories.list)
- expect(categories).toHaveLength(1)
- expect(categories![0]).toMatchObject({
- ...validCategory,
- _id: id,
- parentId: 0,
- userId: 'test-user-id',
- })
- })
-
- it('creates a child category', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- const childId = await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Groceries',
- parentId,
- })
-
- const categories = await t.query(api.categories.list)
- const child = categories!.find(c => c._id === childId)!
- expect(child.parentId).toBe(parentId)
- })
-
- it('throws for duplicate name at same level', async () => {
- const t = convexTest(schema, modules)
- await t.mutation(api.categories.create, validCategory)
- await expect(
- t.mutation(api.categories.create, validCategory),
- ).rejects.toThrow('Category with this name already exists')
- })
-
- it('allows same name under different parents', async () => {
- const t = convexTest(schema, modules)
- const parent1 = await t.mutation(api.categories.create, validCategory)
- const parent2 = await t.mutation(api.categories.create, { ...validCategory, name: 'Transport' })
-
- await t.mutation(api.categories.create, { ...validCategory, name: 'Taxi', parentId: parent1 })
- await t.mutation(api.categories.create, { ...validCategory, name: 'Taxi', parentId: parent2 })
-
- const categories = await t.query(api.categories.list)
- const taxis = categories!.filter(c => c.name === 'Taxi')
- expect(taxis).toHaveLength(2)
- })
-
- it('throws for nesting more than 2 levels deep', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- const childId = await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Groceries',
- parentId,
- })
-
- await expect(
- t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Dairy',
- parentId: childId,
- }),
- ).rejects.toThrow('Cannot nest more than 2 levels deep')
- })
- })
-
- describe('update', () => {
- it('throws for duplicate name on rename', async () => {
- const t = convexTest(schema, modules)
- await t.mutation(api.categories.create, validCategory)
- const id2 = await t.mutation(api.categories.create, { ...validCategory, name: 'Transport' })
-
- await expect(
- t.mutation(api.categories.update, { id: id2, name: 'Food' }),
- ).rejects.toThrow('Category with this name already exists')
- })
-
- it('prevents setting self as parent', async () => {
- const t = convexTest(schema, modules)
- const id = await t.mutation(api.categories.create, validCategory)
- await expect(
- t.mutation(api.categories.update, { id, parentId: id }),
- ).rejects.toThrow('Category cannot be its own parent')
- })
-
- it('rejects making a category with children into a child', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Groceries',
- parentId,
- })
- const otherRootId = await t.mutation(api.categories.create, { ...validCategory, name: 'Transport' })
-
- await expect(
- t.mutation(api.categories.update, { id: parentId, parentId: otherRootId }),
- ).rejects.toThrow('Cannot move a category that has its own children')
- })
-
- it('allows clearing parentId on root with children (no-op)', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Groceries',
- parentId,
- })
-
- await t.mutation(api.categories.update, { id: parentId, name: 'Food updated', parentId: 0 })
-
- const list = await t.query(api.categories.list)
- const updated = list!.find(c => c._id === parentId)!
- expect(updated.name).toBe('Food updated')
- expect(updated.parentId).toBe(0)
- })
- })
-
- describe('updateWithChildren', () => {
- it('propagates color to children', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- const childId = await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Groceries',
- parentId,
- })
-
- await t.mutation(api.categories.updateWithChildren, {
- childIds: [childId],
- color: '#00ff00',
- id: parentId,
- })
-
- const categories = await t.query(api.categories.list)
- const parent = categories!.find(c => c._id === parentId)!
- const child = categories!.find(c => c._id === childId)!
- expect(parent.color).toBe('#00ff00')
- expect(child.color).toBe('#00ff00')
- })
-
- it('throws if child does not belong to parent', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- const otherId = await t.mutation(api.categories.create, { ...validCategory, name: 'Other' })
-
- await expect(
- t.mutation(api.categories.updateWithChildren, {
- childIds: [otherId],
- color: '#00ff00',
- id: parentId,
- }),
- ).rejects.toThrow('Child does not belong to this parent')
- })
- })
-
- describe('remove (cascade)', () => {
- it('deletes category and its transactions', async () => {
- const t = convexTest(schema, modules)
- const walletId = await t.mutation(api.wallets.create, validWallet)
- const catId = await t.mutation(api.categories.create, validCategory)
-
- await t.mutation(api.trns.create, {
- amount: 50,
- categoryId: catId,
- date: Date.now(),
- type: 0,
- walletId,
- })
-
- await t.action(api.categories.remove, { id: catId })
-
- expect(await t.query(api.categories.list)).toHaveLength(0)
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page).toHaveLength(0)
- })
-
- it('throws when deleting category with children', async () => {
- const t = convexTest(schema, modules)
- const parentId = await t.mutation(api.categories.create, validCategory)
- await t.mutation(api.categories.create, {
- ...validCategory,
- name: 'Child',
- parentId,
- })
-
- await expect(
- t.action(api.categories.remove, { id: parentId }),
- ).rejects.toThrow('Cannot delete category with children')
- })
- })
-})
diff --git a/app/convex/categories.ts b/app/convex/categories.ts
deleted file mode 100644
index 5265c468..00000000
--- a/app/convex/categories.ts
+++ /dev/null
@@ -1,381 +0,0 @@
-import { v } from 'convex/values'
-
-import type { Id } from './_generated/dataModel'
-import type { MutationCtx } from './_generated/server'
-
-import { internal } from './_generated/api'
-import { action, internalMutation, internalQuery, mutation, query } from './_generated/server'
-import { getAuthUser, getOwnEntity, requireAuthUser, validateStringLength } from './shared'
-import { emitTombstone, emitTombstones } from './tombstones'
-import { toggleTrnsHash } from './trnsHash'
-
-async function validateParentId(ctx: MutationCtx, parentId: Id<'categories'> | 0, userId: string, selfId?: Id<'categories'>) {
- if (parentId === 0)
- return
- if (selfId && parentId === selfId)
- throw new Error('Category cannot be its own parent')
- const parent = await getOwnEntity(ctx, parentId, userId, 'Parent category not found')
- if (parent.parentId !== 0)
- throw new Error('Cannot nest more than 2 levels deep')
-}
-
-async function validateNameUniqueness(ctx: MutationCtx, name: string, parentId: Id<'categories'> | 0, userId: string, excludeId?: Id<'categories'>) {
- const duplicate = await ctx.db
- .query('categories')
- .withIndex('by_user_name_parent', q => q.eq('userId', userId).eq('name', name).eq('parentId', parentId))
- .filter(q => excludeId ? q.neq(q.field('_id'), excludeId) : true)
- .first()
- if (duplicate)
- throw new Error('Category with this name already exists')
-}
-
-async function updateCategoryCore(
- ctx: MutationCtx,
- id: Id<'categories'>,
- args: {
- color?: string
- icon?: string
- name?: string
- parentId?: Id<'categories'> | 0
- showInLastUsed?: boolean
- showInQuickSelector?: boolean
- },
- userId: string,
-) {
- if (args.icon !== undefined && !args.icon.trim())
- throw new Error('Icon is required')
- if (args.name !== undefined && !args.name.trim())
- throw new Error('Name is required')
- if (args.color !== undefined && !args.color.trim())
- throw new Error('Color is required')
- validateStringLength(args.name, 100, 'Name')
- validateStringLength(args.color, 50, 'Color')
- validateStringLength(args.icon, 50, 'Icon')
-
- const category = await getOwnEntity(ctx, id, userId)
-
- if (args.parentId !== undefined && args.parentId !== 0) {
- await validateParentId(ctx, args.parentId, userId, id)
- // Only block when the parent actually changes — a redundant resend of the
- // current parentId (common in updateWithChildren / formless updates) is fine.
- if (args.parentId !== category.parentId) {
- const ownChild = await ctx.db
- .query('categories')
- .withIndex('by_user_parent', q => q.eq('userId', userId).eq('parentId', id))
- .first()
- if (ownChild)
- throw new Error('Cannot move a category that has its own children')
- }
- }
- if (args.name !== undefined || args.parentId !== undefined)
- await validateNameUniqueness(ctx, args.name ?? category.name, args.parentId ?? category.parentId, userId, id)
-
- const now = Date.now()
- await ctx.db.patch(id, { ...args, updatedAt: now })
- return now
-}
-
-export const list = query({
- args: {},
- handler: async (ctx) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- return await ctx.db
- .query('categories')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .collect()
- },
-})
-
-const REALTIME_DELTA_LIMIT = 500
-
-export const deltaRealtime = query({
- args: { since: v.number() },
- handler: async (ctx, { since }) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- const serverTime = Date.now()
- const docsPlusOne = await ctx.db
- .query('categories')
- .withIndex('by_user_updatedAt', q =>
- q.eq('userId', user._id).gt('updatedAt', since))
- .take(REALTIME_DELTA_LIMIT + 1)
- const truncated = docsPlusOne.length > REALTIME_DELTA_LIMIT
- const docs = truncated ? docsPlusOne.slice(0, REALTIME_DELTA_LIMIT) : docsPlusOne
- const tombstones = await ctx.db
- .query('tombstones')
- .withIndex('by_user_entity_deletedAt', q =>
- q.eq('userId', user._id).eq('entity', 'categories').gt('deletedAt', since))
- .take(REALTIME_DELTA_LIMIT)
- return {
- deletedIds: tombstones.map(t => t.entityId),
- docs,
- serverTime,
- truncated,
- }
- },
-})
-
-export const create = mutation({
- args: {
- color: v.string(),
- icon: v.string(),
- name: v.string(),
- parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
- showInLastUsed: v.boolean(),
- showInQuickSelector: v.boolean(),
- },
- handler: async (ctx, args) => {
- const user = await requireAuthUser(ctx)
- if (!args.icon.trim())
- throw new Error('Icon is required')
- if (!args.name.trim())
- throw new Error('Name is required')
- if (!args.color.trim())
- throw new Error('Color is required')
- validateStringLength(args.name, 100, 'Name')
- validateStringLength(args.color, 50, 'Color')
- validateStringLength(args.icon, 50, 'Icon')
-
- const parentId = args.parentId ?? 0
-
- await validateNameUniqueness(ctx, args.name, parentId, user._id)
- if (parentId !== 0)
- await validateParentId(ctx, parentId, user._id)
-
- const newId = await ctx.db.insert('categories', {
- ...args,
- parentId,
- updatedAt: Date.now(),
- userId: user._id,
- })
-
- return newId
- },
-})
-
-export const update = mutation({
- args: {
- color: v.optional(v.string()),
- icon: v.optional(v.string()),
- id: v.id('categories'),
- name: v.optional(v.string()),
- parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
- showInLastUsed: v.optional(v.boolean()),
- showInQuickSelector: v.optional(v.boolean()),
- },
- handler: async (ctx, { id, ...args }) => {
- const user = await requireAuthUser(ctx)
- await updateCategoryCore(ctx, id, args, user._id)
- },
-})
-
-export const validateCategoryRemoval = internalQuery({
- args: { id: v.id('categories'), userId: v.string() },
- handler: async (ctx, { id, userId }) => {
- const category = await ctx.db.get(id)
- if (!category || category.userId !== userId)
- throw new Error('Not found')
- const child = await ctx.db
- .query('categories')
- .withIndex('by_user_parent', q => q.eq('userId', userId).eq('parentId', id))
- .first()
- if (child)
- throw new Error('Cannot delete category with children')
- },
-})
-
-export const removeTrnsByCategoryPage = internalMutation({
- args: {
- categoryId: v.id('categories'),
- cursor: v.union(v.string(), v.null()),
- userId: v.string(),
- },
- handler: async (ctx, { categoryId, cursor, userId }) => {
- const page = await ctx.db
- .query('trns')
- .withIndex('by_user_category', q => q.eq('userId', userId).eq('categoryId', categoryId))
- .paginate({ cursor, numItems: 500 })
-
- const deletedIds: string[] = []
- for (const trn of page.page) {
- await ctx.db.delete(trn._id)
- deletedIds.push(trn._id)
- }
-
- if (deletedIds.length) {
- await toggleTrnsHash(ctx, userId, deletedIds)
- await emitTombstones(ctx, userId, 'trns', deletedIds)
- }
-
- return { continueCursor: page.continueCursor, isDone: page.isDone }
- },
-})
-
-export const removeCategoryFinalize = internalMutation({
- args: {
- categoryId: v.id('categories'),
- userId: v.string(),
- },
- handler: async (ctx, { categoryId, userId }) => {
- const category = await ctx.db.get(categoryId)
- if (!category || category.userId !== userId)
- return
- await ctx.db.delete(categoryId)
- await emitTombstone(ctx, userId, 'categories', categoryId)
- },
-})
-
-export const remove = action({
- args: { id: v.id('categories') },
- handler: async (ctx, { id }) => {
- const user = await ctx.runQuery(internal.user.getCurrentUser)
- if (!user)
- throw new Error('Unauthorized')
-
- // Validate before cascade delete (ownership + no children)
- await ctx.runQuery(internal.categories.validateCategoryRemoval, {
- id,
- userId: user._id,
- })
-
- let cursor: string | null = null
- let isDone = false
- while (!isDone) {
- const result: { continueCursor: string, isDone: boolean } = await ctx.runMutation(internal.categories.removeTrnsByCategoryPage, {
- categoryId: id,
- cursor,
- userId: user._id,
- })
- isDone = result.isDone
- cursor = result.continueCursor
- }
-
- await ctx.runMutation(internal.categories.removeCategoryFinalize, {
- categoryId: id,
- userId: user._id,
- })
- },
-})
-
-export const setChildren = mutation({
- args: {
- addIds: v.array(v.id('categories')),
- childrenColor: v.optional(v.string()),
- id: v.id('categories'),
- removeIds: v.array(v.id('categories')),
- },
- handler: async (ctx, { addIds, childrenColor, id, removeIds }) => {
- const user = await requireAuthUser(ctx)
- const parent = await getOwnEntity(ctx, id, user._id)
- if (parent.parentId !== 0)
- throw new Error('Only a root category can adopt children')
-
- // Dedupe and reject overlap
- const addSet = new Set(addIds)
- const removeSet = new Set(removeIds)
- if (addSet.size !== addIds.length || removeSet.size !== removeIds.length)
- throw new Error('Duplicate IDs in addIds or removeIds')
- for (const id of addSet) {
- if (removeSet.has(id))
- throw new Error('Same ID appears in both addIds and removeIds')
- }
- if (addSet.has(id))
- throw new Error('Category cannot be its own child')
-
- validateStringLength(childrenColor, 50, 'Color')
-
- // Validate each add: own, leaf (no own children)
- for (const addId of addSet) {
- await getOwnEntity(ctx, addId, user._id)
- const ownChild = await ctx.db
- .query('categories')
- .withIndex('by_user_parent', q => q.eq('userId', user._id).eq('parentId', addId))
- .first()
- if (ownChild)
- throw new Error('Cannot move a category that has its own children')
- }
-
- // Validate each remove currently belongs to this parent
- for (const removeId of removeSet) {
- const cat = await getOwnEntity(ctx, removeId, user._id)
- if (cat.parentId !== id)
- throw new Error('Child does not belong to this parent')
- }
-
- // Name uniqueness: existing kept + added
- const existingChildren = await ctx.db
- .query('categories')
- .withIndex('by_user_parent', q => q.eq('userId', user._id).eq('parentId', id))
- .collect()
- const finalNames = new Set<string>()
- for (const child of existingChildren) {
- if (removeSet.has(child._id) || addSet.has(child._id))
- continue
- if (finalNames.has(child.name))
- throw new Error('Duplicate child name under parent')
- finalNames.add(child.name)
- }
- for (const addId of addSet) {
- const cat = await ctx.db.get(addId)
- if (!cat)
- throw new Error('Not found')
- if (finalNames.has(cat.name))
- throw new Error(`Category with name "${cat.name}" already exists under parent`)
- finalNames.add(cat.name)
- }
-
- const now = Date.now()
-
- for (const addId of addSet) {
- const patch: { color?: string, parentId: typeof id, updatedAt: number } = {
- parentId: id,
- updatedAt: now,
- }
- if (childrenColor)
- patch.color = childrenColor
- await ctx.db.patch(addId, patch)
- }
- for (const removeId of removeSet)
- await ctx.db.patch(removeId, { parentId: 0, updatedAt: now })
-
- // Propagate color to kept children if requested
- if (childrenColor) {
- for (const child of existingChildren) {
- if (removeSet.has(child._id) || addSet.has(child._id))
- continue
- await ctx.db.patch(child._id, { color: childrenColor, updatedAt: now })
- }
- }
-
- return now
- },
-})
-
-export const updateWithChildren = mutation({
- args: {
- childIds: v.array(v.id('categories')),
- color: v.string(),
- icon: v.optional(v.string()),
- id: v.id('categories'),
- name: v.optional(v.string()),
- parentId: v.optional(v.union(v.id('categories'), v.literal(0))),
- showInLastUsed: v.optional(v.boolean()),
- showInQuickSelector: v.optional(v.boolean()),
- },
- handler: async (ctx, { childIds, id, ...args }) => {
- const user = await requireAuthUser(ctx)
- const now = await updateCategoryCore(ctx, id, args, user._id)
-
- for (const childId of childIds) {
- const child = await ctx.db.get(childId)
- if (!child || child.userId !== user._id)
- continue
- if (child.parentId !== id)
- throw new Error('Child does not belong to this parent')
- await ctx.db.patch(childId, { color: args.color, updatedAt: now })
- }
- },
-})
diff --git a/app/convex/convex.config.ts b/app/convex/convex.config.ts
deleted file mode 100644
index 979b556b..00000000
--- a/app/convex/convex.config.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import betterAuth from '@convex-dev/better-auth/convex.config'
-import { defineApp } from 'convex/server'
-
-const app = defineApp()
-app.use(betterAuth)
-
-export default app
diff --git a/app/convex/crons.ts b/app/convex/crons.ts
deleted file mode 100644
index d3ab7369..00000000
--- a/app/convex/crons.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { cronJobs } from 'convex/server'
-
-import { internal } from './_generated/api'
-
-const crons = cronJobs()
-
-crons.daily(
- 'fetch exchange rates',
- { hourUTC: 6, minuteUTC: 0 },
- internal.rates.fetchAndSaveRates,
-)
-
-crons.daily(
- 'purge old tombstones',
- { hourUTC: 4, minuteUTC: 0 },
- internal.tombstones.purgeOld,
-)
-
-export default crons
diff --git a/app/convex/http.ts b/app/convex/http.ts
deleted file mode 100644
index 44b9e2a5..00000000
--- a/app/convex/http.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { httpRouter } from 'convex/server'
-
-import { authComponent, createAuth } from './auth'
-
-const http = httpRouter()
-
-authComponent.registerRoutes(http, createAuth, {
- cors: true,
-})
-
-export default http
diff --git a/app/convex/migrate.ts b/app/convex/migrate.ts
deleted file mode 100644
index b686f5b4..00000000
--- a/app/convex/migrate.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import { v } from 'convex/values'
-
-import type { Id } from './_generated/dataModel'
-
-import { components, internal } from './_generated/api'
-import { internalAction, internalMutation } from './_generated/server'
-import { toggleTrnsHash } from './trnsHash'
-
-export const deleteTablePage = internalMutation({
- args: {
- table: v.string(),
- userId: v.string(),
- },
- handler: async (ctx, { table, userId }) => {
- const page = await ctx.db
- .query(table as 'categories' | 'wallets' | 'trns' | 'userSettings' | 'syncMeta')
- .withIndex('by_user', q => q.eq('userId', userId))
- .paginate({ cursor: null, numItems: 500 })
- for (const row of page.page)
- await ctx.db.delete(row._id)
- return { count: page.page.length, hasMore: !page.isDone }
- },
-})
-
-export const deleteUserData = internalAction({
- args: {
- userId: v.string(),
- },
- handler: async (ctx, { userId }) => {
- const tables = ['categories', 'wallets', 'trns', 'userSettings', 'syncMeta'] as const
- const counts: Record<string, number> = {}
-
- for (const table of tables) {
- let total = 0
- let hasMore = true
- while (hasMore) {
- const result = await ctx.runMutation(internal.migrate.deleteTablePage, { table, userId })
- total += result.count
- hasMore = result.hasMore
- }
- counts[table] = total
- if (total > 0)
- console.log(`deleted ${total} rows from ${table}`)
- }
-
- console.log('deleteUserData: done', counts)
- return counts
- },
-})
-
-export const deleteAuthTablePage = internalMutation({
- args: {
- model: v.string(),
- userId: v.string(),
- },
- handler: async (ctx, { model, userId }) => {
- const field = model === 'user' ? '_id' : 'userId'
- const result = await ctx.runMutation(components.betterAuth.adapter.deleteMany, {
- input: {
- // @ts-expect-error BetterAuth adapter expects specific model names but we iterate dynamically
- model,
- where: [{ field, operator: 'eq', value: userId }],
- },
- paginationOpts: { cursor: null, numItems: 500 },
- })
- return { count: result?.deletedCount ?? 0 }
- },
-})
-
-export const deleteUserDataFull = internalAction({
- args: {
- userId: v.string(),
- },
- handler: async (ctx, { userId }) => {
- // Delete app tables
- const appResult = await ctx.runAction(internal.migrate.deleteUserData, { userId })
- console.log('App data deleted:', appResult)
-
- // Delete auth tables
- const authTables = ['session', 'account', 'twoFactor', 'passkey', 'oauthApplication', 'oauthAccessToken', 'oauthConsent', 'user']
- for (const model of authTables) {
- const result = await ctx.runMutation(internal.migrate.deleteAuthTablePage, { model, userId })
- if (result.count > 0)
- console.log(`Deleted ${result.count} rows from auth:${model}`)
- }
-
- console.log('deleteUserDataFull: done for', userId)
- },
-})
-
-export const insertWallets = internalMutation({
- args: {
- userId: v.string(),
- wallets: v.any(),
- },
- handler: async (ctx, { userId, wallets }) => {
- const idMap: Record<string, string> = {}
- for (const { oldId, ...data } of wallets) {
- const id = await ctx.db.insert('wallets', { ...data, userId })
- idMap[oldId] = id
- }
- return idMap
- },
-})
-
-export const insertCategories = internalMutation({
- args: {
- categories: v.any(),
- userId: v.string(),
- },
- handler: async (ctx, { categories, userId }) => {
- const idMap: Record<string, string> = {}
- const inserts: Array<{ id: string, oldParentId?: string }> = []
-
- for (const { oldChildIds: _oldChildIds, oldId, oldParentId, ...data } of categories) {
- const id = await ctx.db.insert('categories', { ...data, userId })
- idMap[oldId] = id
- inserts.push({ id, oldParentId })
- }
-
- for (const { id, oldParentId } of inserts) {
- if (oldParentId && idMap[oldParentId]) {
- await ctx.db.patch(id as Id<'categories'>, { parentId: idMap[oldParentId] as unknown as Id<'categories'> })
- }
- }
-
- return idMap
- },
-})
-
-export const insertTrnsBatch = internalMutation({
- args: {
- trns: v.any(),
- userId: v.string(),
- },
- handler: async (ctx, { trns, userId }) => {
- const newIds: string[] = []
- for (const data of trns) {
- const id = await ctx.db.insert('trns', { ...data, userId })
- newIds.push(id)
- }
- await toggleTrnsHash(ctx, userId, newIds)
- return (trns as unknown[]).length
- },
-})
-
-export const insertUserSettings = internalMutation({
- args: {
- baseCurrency: v.string(),
- locale: v.optional(v.string()),
- userId: v.string(),
- },
- handler: async (ctx, args) => {
- await ctx.db.insert('userSettings', {
- baseCurrency: args.baseCurrency,
- locale: args.locale as 'en' | 'ru' | undefined,
- userId: args.userId,
- })
- },
-})
diff --git a/app/convex/rates.ts b/app/convex/rates.ts
deleted file mode 100644
index cd2cd585..00000000
--- a/app/convex/rates.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { v } from 'convex/values'
-
-import { internal } from './_generated/api'
-import { internalAction, internalMutation, query } from './_generated/server'
-
-const OER_API_URL = 'https://openexchangerates.org/api/latest.json'
-const COINBASE_API_URL = 'https://api.coinbase.com/v2/exchange-rates'
-
-async function fetchFromCoinbase(): Promise<Record<string, number> | null> {
- try {
- const res = await fetch(`${COINBASE_API_URL}?currency=USD`)
-
- if (!res.ok) {
- console.error(`Coinbase fetch failed: ${res.status} ${res.statusText}`)
- return null
- }
-
- const json = await res.json()
- const rawRates: Record<string, string> = json.data?.rates
-
- if (!rawRates) {
- console.error('Coinbase: unexpected response shape')
- return null
- }
-
- const parsed: Record<string, number> = {}
- for (const [code, value] of Object.entries(rawRates)) {
- const num = Number.parseFloat(value)
- if (Number.isFinite(num) && num > 0) {
- parsed[code] = num
- }
- }
-
- return parsed
- }
- catch (e) {
- console.error('Coinbase fetch error:', e)
- return null
- }
-}
-
-async function fetchFromOER(): Promise<Record<string, number> | null> {
- const appId = process.env.OPEN_EXCHANGE_RATES_KEY
-
- if (!appId) {
- console.error('OPEN_EXCHANGE_RATES_KEY not set')
- return null
- }
-
- try {
- const res = await fetch(`${OER_API_URL}?app_id=${appId}`)
-
- if (!res.ok) {
- console.error(`OER fetch failed: ${res.status} ${res.statusText}`)
- return null
- }
-
- const data = await res.json()
- return data.rates ?? null
- }
- catch (e) {
- console.error('OER fetch error:', e)
- return null
- }
-}
-
-export const getLatest = query({
- args: {},
- handler: async (ctx) => {
- const records = await ctx.db
- .query('rates')
- .withIndex('by_date')
- .order('desc')
- .take(4)
-
- if (records.length === 0)
- return null
-
- // Merge: newest first, first-seen currency wins
- const merged: Record<string, number> = {}
-
- for (const record of records) {
- for (const [currency, rate] of Object.entries(record.rates)) {
- if (!(currency in merged)) {
- merged[currency] = rate
- }
- }
- }
-
- return {
- date: records[0]!.date,
- rates: merged,
- updatedAt: records[0]!.updatedAt,
- }
- },
-})
-
-export const saveRates = internalMutation({
- args: {
- date: v.string(),
- rates: v.record(v.string(), v.number()),
- source: v.string(),
- },
- handler: async (ctx, { date, rates, source }) => {
- const existing = await ctx.db
- .query('rates')
- .withIndex('by_date_source', q => q.eq('date', date).eq('source', source))
- .first()
-
- if (existing) {
- await ctx.db.patch(existing._id, { rates, updatedAt: Date.now() })
- }
- else {
- await ctx.db.insert('rates', { date, rates, source, updatedAt: Date.now() })
- }
- },
-})
-
-export const fetchAndSaveRates = internalAction({
- args: {},
- handler: async (ctx) => {
- const today = new Date().toISOString().slice(0, 10)
-
- // Coinbase (primary — no API key, ~960 currencies incl. crypto)
- const coinbaseRates = await fetchFromCoinbase()
- if (coinbaseRates) {
- await ctx.runMutation(internal.rates.saveRates, {
- date: today,
- rates: coinbaseRates,
- source: 'coinbase',
- })
- console.log(`Coinbase: saved ${Object.keys(coinbaseRates).length} rates`)
- }
-
- // OER (secondary — better fiat precision, ~173 currencies)
- const oerRates = await fetchFromOER()
- if (oerRates) {
- await ctx.runMutation(internal.rates.saveRates, {
- date: today,
- rates: oerRates,
- source: 'oer',
- })
- console.log(`OER: saved ${Object.keys(oerRates).length} rates`)
- }
-
- if (!coinbaseRates && !oerRates) {
- console.error('All exchange rate sources failed')
- }
- },
-})
diff --git a/app/convex/schema.ts b/app/convex/schema.ts
deleted file mode 100644
index ef744166..00000000
--- a/app/convex/schema.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { defineSchema, defineTable } from 'convex/server'
-import { v } from 'convex/values'
-
-import { TrnType, walletTypeValidator } from './validators'
-
-export default defineSchema({
- categories: defineTable({
- color: v.string(),
- icon: v.string(),
- name: v.string(),
- parentId: v.union(v.id('categories'), v.literal(0)),
- showInLastUsed: v.boolean(),
- showInQuickSelector: v.boolean(),
- updatedAt: v.optional(v.number()),
- userId: v.string(),
- })
- .index('by_user', ['userId'])
- .index('by_user_name_parent', ['userId', 'name', 'parentId'])
- .index('by_user_parent', ['userId', 'parentId'])
- .index('by_user_updatedAt', ['userId', 'updatedAt']),
-
- rates: defineTable({
- date: v.string(),
- rates: v.record(v.string(), v.number()),
- source: v.optional(v.string()),
- updatedAt: v.number(),
- })
- .index('by_date', ['date'])
- .index('by_date_source', ['date', 'source']),
-
- syncMeta: defineTable({
- trnsIdsHash: v.optional(v.string()),
- userId: v.string(),
- }).index('by_user', ['userId']),
-
- tombstones: defineTable({
- deletedAt: v.number(),
- entity: v.union(v.literal('trns'), v.literal('wallets'), v.literal('categories')),
- entityId: v.string(),
- userId: v.string(),
- })
- .index('by_user_entity_deletedAt', ['userId', 'entity', 'deletedAt'])
- .index('by_user_deletedAt', ['userId', 'deletedAt']),
-
- trns: defineTable({
- amount: v.optional(v.number()),
- categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
- date: v.number(),
- desc: v.optional(v.string()),
- expenseAmount: v.optional(v.number()),
- expenseWalletId: v.optional(v.id('wallets')),
- incomeAmount: v.optional(v.number()),
- incomeWalletId: v.optional(v.id('wallets')),
- type: v.union(
- v.literal(TrnType.Expense),
- v.literal(TrnType.Income),
- v.literal(TrnType.Transfer),
- ),
- updatedAt: v.number(),
- userId: v.string(),
- walletId: v.optional(v.id('wallets')),
- })
- .index('by_user', ['userId'])
- .index('by_user_date', ['userId', 'date'])
- .index('by_user_wallet', ['userId', 'walletId'])
- .index('by_user_expenseWallet', ['userId', 'expenseWalletId'])
- .index('by_user_incomeWallet', ['userId', 'incomeWalletId'])
- .index('by_user_category', ['userId', 'categoryId'])
- .index('by_user_updatedAt', ['userId', 'updatedAt']),
-
- userSettings: defineTable({
- baseCurrency: v.string(),
- locale: v.optional(v.union(v.literal('en'), v.literal('ru'))),
- userId: v.string(),
- }).index('by_user', ['userId']),
-
- wallets: defineTable({
- color: v.string(),
- creditLimit: v.optional(v.number()),
- currency: v.string(),
- desc: v.optional(v.string()),
- isArchived: v.boolean(),
- isExcludeInTotal: v.boolean(),
- isWithdrawal: v.boolean(),
- name: v.string(),
- order: v.number(),
- type: walletTypeValidator,
- updatedAt: v.optional(v.number()),
- userId: v.string(),
- })
- .index('by_user', ['userId'])
- .index('by_user_updatedAt', ['userId', 'updatedAt']),
-})
diff --git a/app/convex/shared.test.ts b/app/convex/shared.test.ts
deleted file mode 100644
index 6e54320f..00000000
--- a/app/convex/shared.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { validateNumberRange, validateStringLength } from './shared'
-
-describe('convex/shared validators', () => {
- describe('validateStringLength', () => {
- it('does nothing for undefined', () => {
- expect(() => validateStringLength(undefined, 10, 'Test')).not.toThrow()
- })
-
- it('does nothing for string within limit', () => {
- expect(() => validateStringLength('hello', 10, 'Test')).not.toThrow()
- })
-
- it('does nothing for string at exact limit', () => {
- expect(() => validateStringLength('a'.repeat(100), 100, 'Name')).not.toThrow()
- })
-
- it('throws for string exceeding limit', () => {
- expect(() => validateStringLength('a'.repeat(101), 100, 'Name'))
- .toThrow('Name must be at most 100 characters')
- })
-
- it('throws with correct field name', () => {
- expect(() => validateStringLength('too long', 5, 'Description'))
- .toThrow('Description must be at most 5 characters')
- })
- })
-
- describe('validateNumberRange', () => {
- it('does nothing for undefined', () => {
- expect(() => validateNumberRange(undefined, 0, 100, 'Amount')).not.toThrow()
- })
-
- it('does nothing for value within range', () => {
- expect(() => validateNumberRange(50, 0, 100, 'Amount')).not.toThrow()
- })
-
- it('does nothing for value at boundaries', () => {
- expect(() => validateNumberRange(0, 0, 100, 'Amount')).not.toThrow()
- expect(() => validateNumberRange(100, 0, 100, 'Amount')).not.toThrow()
- })
-
- it('throws for value below min', () => {
- expect(() => validateNumberRange(-1, 0, 100, 'Amount'))
- .toThrow('Amount must be between 0 and 100')
- })
-
- it('throws for value above max', () => {
- expect(() => validateNumberRange(101, 0, 100, 'Amount'))
- .toThrow('Amount must be between 0 and 100')
- })
- })
-})
diff --git a/app/convex/shared.ts b/app/convex/shared.ts
deleted file mode 100644
index 7c6fe705..00000000
--- a/app/convex/shared.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import type { Doc, Id, TableNames } from './_generated/dataModel'
-import type { MutationCtx, QueryCtx } from './_generated/server'
-
-import { authComponent } from './auth'
-
-export { TrnType } from './validators'
-
-/**
- * Validate string field length. Throws if value exceeds maxLen.
- */
-export function validateStringLength(value: string | undefined, maxLen: number, fieldName: string) {
- if (value !== undefined && value.length > maxLen)
- throw new Error(`${fieldName} must be at most ${maxLen} characters`)
-}
-
-/**
- * Validate numeric field range. Throws if value is outside [min, max].
- * Skips check when value is undefined (optional fields).
- */
-export function validateNumberRange(value: number | undefined, min: number, max: number, fieldName: string) {
- if (value !== undefined && (value < min || value > max))
- throw new Error(`${fieldName} must be between ${min} and ${max}`)
-}
-
-// 2000-01-01 .. 2100-01-01 in ms
-export const DATE_MIN = 946_684_800_000
-export const DATE_MAX = 4_102_444_800_000
-
-export const AMOUNT_MAX = 1_000_000_000_000
-export const CREDIT_LIMIT_MAX = 1_000_000_000
-
-/**
- * Get authenticated user or return null (for queries).
- */
-export async function getAuthUser(ctx: QueryCtx) {
- return await authComponent.safeGetAuthUser(ctx)
-}
-
-/**
- * Get authenticated user or throw (for mutations/actions).
- */
-export async function requireAuthUser(ctx: QueryCtx) {
- const user = await authComponent.safeGetAuthUser(ctx)
- if (!user)
- throw new Error('Unauthorized')
- return user
-}
-
-type OwnedTable = {
- [K in TableNames]: Doc<K> extends { userId: string } ? K : never
-}[TableNames]
-
-export async function getOwnEntity<T extends OwnedTable>(
- ctx: MutationCtx,
- id: Id<T>,
- userId: string,
- errorMessage = 'Not found',
-): Promise<Doc<T>> {
- const entity = await ctx.db.get(id)
- if (!entity || entity.userId !== userId)
- throw new Error(errorMessage)
- return entity
-}
diff --git a/app/convex/test_utils/setup.helper.ts b/app/convex/test_utils/setup.helper.ts
deleted file mode 100644
index 8997a944..00000000
--- a/app/convex/test_utils/setup.helper.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/// <reference types="vite/client" />
-import { beforeEach, vi } from 'vitest'
-
-const state = { mockUserId: 'test-user-id' as string | null }
-
-export function getMockUserId() {
- return state.mockUserId
-}
-
-export function setMockUser(userId: string | null) {
- state.mockUserId = userId
-}
-
-beforeEach(() => {
- state.mockUserId = 'test-user-id'
-})
-
-vi.mock('../auth', () => ({
- authComponent: {
- safeGetAuthUser: vi.fn(async () => {
- if (!state.mockUserId)
- return null
- return { _id: state.mockUserId }
- }),
- },
-}))
-
-export const modules = import.meta.glob('../**/*.ts')
diff --git a/app/convex/tombstones.ts b/app/convex/tombstones.ts
deleted file mode 100644
index 3e5d4213..00000000
--- a/app/convex/tombstones.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { v } from 'convex/values'
-
-import type { MutationCtx } from './_generated/server'
-
-import { internal } from './_generated/api'
-import { internalAction, internalMutation } from './_generated/server'
-
-export type TombstoneEntity = 'categories' | 'trns' | 'wallets'
-
-const RETAIN_MS = 30 * 24 * 60 * 60 * 1000
-
-export const purgeOldPage = internalMutation({
- args: { cursor: v.union(v.string(), v.null()), cutoff: v.number() },
- handler: async (ctx, { cursor, cutoff }) => {
- const page = await ctx.db
- .query('tombstones')
- .withIndex('by_user_deletedAt')
- .paginate({ cursor, numItems: 500 })
-
- let removed = 0
- for (const t of page.page) {
- if (t.deletedAt < cutoff) {
- await ctx.db.delete(t._id)
- removed++
- }
- }
- return { continueCursor: page.continueCursor, isDone: page.isDone, removed }
- },
-})
-
-export const purgeOld = internalAction({
- args: {},
- handler: async (ctx) => {
- const cutoff = Date.now() - RETAIN_MS
- let cursor: string | null = null
- let isDone = false
- let total = 0
- while (!isDone) {
- const result: { continueCursor: string, isDone: boolean, removed: number } = await ctx.runMutation(
- internal.tombstones.purgeOldPage,
- { cursor, cutoff },
- )
- total += result.removed
- cursor = result.continueCursor
- isDone = result.isDone
- }
- return { removed: total }
- },
-})
-
-export async function emitTombstone(
- ctx: MutationCtx,
- userId: string,
- entity: TombstoneEntity,
- entityId: string,
-): Promise<void> {
- await ctx.db.insert('tombstones', {
- deletedAt: Date.now(),
- entity,
- entityId,
- userId,
- })
-}
-
-export async function emitTombstones(
- ctx: MutationCtx,
- userId: string,
- entity: TombstoneEntity,
- entityIds: string[],
-): Promise<void> {
- if (entityIds.length === 0)
- return
- const deletedAt = Date.now()
- for (const entityId of entityIds)
- await ctx.db.insert('tombstones', { deletedAt, entity, entityId, userId })
-}
diff --git a/app/convex/trns.test.ts b/app/convex/trns.test.ts
deleted file mode 100644
index 3a1ab5be..00000000
--- a/app/convex/trns.test.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-import type { TestConvex } from 'convex-test'
-
-import { convexTest } from 'convex-test'
-import { describe, expect, it } from 'vitest'
-
-import { api } from './_generated/api'
-import schema from './schema'
-import { modules, setMockUser } from './test_utils/setup.helper'
-
-const validWallet = {
- color: '#000',
- currency: 'USD',
- name: 'Cash',
- order: 0,
- type: 'cash' as const,
-}
-
-const validCategory = {
- color: '#ff0000',
- icon: 'food',
- name: 'Food',
- showInLastUsed: true,
- showInQuickSelector: true,
-}
-
-async function setupWalletAndCategory(t: TestConvex<typeof schema>) {
- const walletId = await t.mutation(api.wallets.create, validWallet)
- const categoryId = await t.mutation(api.categories.create, validCategory)
- return { categoryId, walletId }
-}
-
-async function setupTwoWallets(t: TestConvex<typeof schema>) {
- const w1 = await t.mutation(api.wallets.create, { ...validWallet, order: 0 })
- const w2 = await t.mutation(api.wallets.create, { ...validWallet, name: 'Card', order: 1 })
- return { w1, w2 }
-}
-
-describe('convex/trns', () => {
- describe('create — expense', () => {
- it('creates an expense transaction', async () => {
- const t = convexTest(schema, modules)
- const { categoryId, walletId } = await setupWalletAndCategory(t)
-
- const id = await t.mutation(api.trns.create, {
- amount: 42.5,
- categoryId,
- date: Date.now(),
- type: 0,
- walletId,
- })
-
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page).toHaveLength(1)
- expect(trns!.page[0]).toMatchObject({
- _id: id,
- amount: 42.5,
- categoryId,
- type: 0,
- userId: 'test-user-id',
- walletId,
- })
- })
-
- it('creates an adjustment transaction', async () => {
- const t = convexTest(schema, modules)
- const { walletId } = await setupWalletAndCategory(t)
-
- const id = await t.mutation(api.trns.create, {
- amount: 500,
- categoryId: 'adjustment',
- date: Date.now(),
- type: 0,
- walletId,
- })
- expect(id).toBeDefined()
- })
-
- it('throws for zero amount', async () => {
- const t = convexTest(schema, modules)
- const { categoryId, walletId } = await setupWalletAndCategory(t)
-
- await expect(
- t.mutation(api.trns.create, {
- amount: 0,
- categoryId,
- date: Date.now(),
- type: 0,
- walletId,
- }),
- ).rejects.toThrow('Amount must be positive')
- })
-
- it('throws without wallet', async () => {
- const t = convexTest(schema, modules)
- const { categoryId } = await setupWalletAndCategory(t)
-
- await expect(
- t.mutation(api.trns.create, {
- amount: 100,
- categoryId,
- date: Date.now(),
- type: 0,
- }),
- ).rejects.toThrow('Wallet is required')
- })
-
- it('throws for wallet owned by another user', async () => {
- const t = convexTest(schema, modules)
- const { walletId } = await setupWalletAndCategory(t)
-
- setMockUser('other-user')
- const otherCat = await t.mutation(api.categories.create, { ...validCategory, name: 'Other' })
-
- await expect(
- t.mutation(api.trns.create, {
- amount: 100,
- categoryId: otherCat,
- date: Date.now(),
- type: 0,
- walletId,
- }),
- ).rejects.toThrow('Wallet not found')
- })
-
- it('throws for "transfer" categoryId on non-transfer type', async () => {
- const t = convexTest(schema, modules)
- const { walletId } = await setupWalletAndCategory(t)
-
- await expect(
- t.mutation(api.trns.create, {
- amount: 100,
- categoryId: 'transfer',
- date: Date.now(),
- type: 0,
- walletId,
- }),
- ).rejects.toThrow('categoryId "transfer" is only allowed for Transfer type')
- })
- })
-
- describe('create — transfer', () => {
- it('creates a transfer between two wallets', async () => {
- const t = convexTest(schema, modules)
- const { w1, w2 } = await setupTwoWallets(t)
-
- const id = await t.mutation(api.trns.create, {
- date: Date.now(),
- expenseAmount: 100,
- expenseWalletId: w1,
- incomeAmount: 95,
- incomeWalletId: w2,
- type: 2,
- })
-
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page[0]).toMatchObject({
- _id: id,
- categoryId: 'transfer',
- expenseAmount: 100,
- incomeAmount: 95,
- type: 2,
- })
- })
-
- it('throws for same wallet on both sides', async () => {
- const t = convexTest(schema, modules)
- const { w1 } = await setupTwoWallets(t)
-
- await expect(
- t.mutation(api.trns.create, {
- date: Date.now(),
- expenseAmount: 100,
- expenseWalletId: w1,
- incomeAmount: 100,
- incomeWalletId: w1,
- type: 2,
- }),
- ).rejects.toThrow('Transfer wallets must be different')
- })
-
- it('throws for non-"transfer" categoryId', async () => {
- const t = convexTest(schema, modules)
- const { w1, w2 } = await setupTwoWallets(t)
- const catId = await t.mutation(api.categories.create, validCategory)
-
- await expect(
- t.mutation(api.trns.create, {
- categoryId: catId,
- date: Date.now(),
- expenseAmount: 100,
- expenseWalletId: w1,
- incomeAmount: 100,
- incomeWalletId: w2,
- type: 2,
- }),
- ).rejects.toThrow('Transfer categoryId must be "transfer"')
- })
- })
-
- describe('remove', () => {
- it('removes a transaction', async () => {
- const t = convexTest(schema, modules)
- const { categoryId, walletId } = await setupWalletAndCategory(t)
- const id = await t.mutation(api.trns.create, {
- amount: 100,
- categoryId,
- date: Date.now(),
- type: 0,
- walletId,
- })
-
- await t.mutation(api.trns.remove, { id })
-
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page).toHaveLength(0)
- })
-
- it('silently ignores trn owned by another user', async () => {
- const t = convexTest(schema, modules)
- const { categoryId, walletId } = await setupWalletAndCategory(t)
- const id = await t.mutation(api.trns.create, {
- amount: 100,
- categoryId,
- date: Date.now(),
- type: 0,
- walletId,
- })
-
- setMockUser('other-user')
- await t.mutation(api.trns.remove, { id })
-
- setMockUser('test-user-id')
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page).toHaveLength(1)
- })
- })
-
- describe('idsHash', () => {
- it('returns consistent hash after create+delete cycle (XOR symmetry)', async () => {
- const t = convexTest(schema, modules)
- const { categoryId, walletId } = await setupWalletAndCategory(t)
-
- const hashBefore = await t.query(api.trns.idsHash)
-
- const id = await t.mutation(api.trns.create, {
- amount: 50,
- categoryId,
- date: Date.now(),
- type: 0,
- walletId,
- })
- await t.mutation(api.trns.remove, { id })
-
- const hashAfter = await t.query(api.trns.idsHash)
- expect(hashAfter!.hash).toBe(hashBefore!.hash)
- })
- })
-})
diff --git a/app/convex/trns.ts b/app/convex/trns.ts
deleted file mode 100644
index 525ef3d5..00000000
--- a/app/convex/trns.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-import { paginationOptsValidator } from 'convex/server'
-import { v } from 'convex/values'
-
-import type { Id } from './_generated/dataModel'
-import type { MutationCtx } from './_generated/server'
-
-import { internal } from './_generated/api'
-import { mutation, query } from './_generated/server'
-import { AMOUNT_MAX, DATE_MAX, DATE_MIN, getAuthUser, getOwnEntity, requireAuthUser, TrnType, validateNumberRange, validateStringLength } from './shared'
-import { emitTombstone } from './tombstones'
-import { fnv1aNum, toggleTrnHash } from './trnsHash'
-
-export async function validateTrnFields(ctx: MutationCtx, args: Record<string, any>, userId: string) {
- validateStringLength(args.desc, 500, 'Description')
- validateNumberRange(args.date, DATE_MIN, DATE_MAX, 'Date')
-
- if (args.type === TrnType.Transfer) {
- if (args.categoryId && args.categoryId !== 'transfer')
- throw new Error('Transfer categoryId must be "transfer"')
- if (!args.expenseWalletId || !args.incomeWalletId)
- throw new Error('Transfer requires both wallets')
- if (args.expenseWalletId === args.incomeWalletId)
- throw new Error('Transfer wallets must be different')
- if (!args.expenseAmount || args.expenseAmount <= 0)
- throw new Error('Transfer expense amount must be positive')
- if (!args.incomeAmount || args.incomeAmount <= 0)
- throw new Error('Transfer income amount must be positive')
- validateNumberRange(args.expenseAmount, 0, AMOUNT_MAX, 'Expense amount')
- validateNumberRange(args.incomeAmount, 0, AMOUNT_MAX, 'Income amount')
- await Promise.all([
- getOwnEntity(ctx, args.expenseWalletId as Id<'wallets'>, userId, 'Expense wallet not found'),
- getOwnEntity(ctx, args.incomeWalletId as Id<'wallets'>, userId, 'Income wallet not found'),
- ])
- }
- else {
- if (!args.amount || args.amount <= 0)
- throw new Error('Amount must be positive')
- validateNumberRange(args.amount, 0, AMOUNT_MAX, 'Amount')
- if (!args.walletId)
- throw new Error('Wallet is required')
- if (!args.categoryId)
- throw new Error('Category is required')
- if (args.categoryId === 'transfer')
- throw new Error('categoryId "transfer" is only allowed for Transfer type')
- await getOwnEntity(ctx, args.walletId as Id<'wallets'>, userId, 'Wallet not found')
- if (args.categoryId !== 'adjustment')
- await getOwnEntity(ctx, args.categoryId as Id<'categories'>, userId, 'Category not found')
- }
-}
-
-const trnTypeValidator = v.union(
- v.literal(TrnType.Expense),
- v.literal(TrnType.Income),
- v.literal(TrnType.Transfer),
-)
-
-export const delta = query({
- args: { paginationOpts: paginationOptsValidator, since: v.number() },
- handler: async (ctx, { paginationOpts, since }) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- return ctx.db
- .query('trns')
- .withIndex('by_user_updatedAt', q =>
- q.eq('userId', user._id).gt('updatedAt', since))
- .paginate(paginationOpts)
- },
-})
-
-const REALTIME_DELTA_LIMIT = 500
-
-export const deltaRealtime = query({
- args: { since: v.number() },
- handler: async (ctx, { since }) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- const serverTime = Date.now()
- const docsPlusOne = await ctx.db
- .query('trns')
- .withIndex('by_user_updatedAt', q =>
- q.eq('userId', user._id).gt('updatedAt', since))
- .take(REALTIME_DELTA_LIMIT + 1)
- const truncated = docsPlusOne.length > REALTIME_DELTA_LIMIT
- const docs = truncated ? docsPlusOne.slice(0, REALTIME_DELTA_LIMIT) : docsPlusOne
- const tombstones = await ctx.db
- .query('tombstones')
- .withIndex('by_user_entity_deletedAt', q =>
- q.eq('userId', user._id).eq('entity', 'trns').gt('deletedAt', since))
- .take(REALTIME_DELTA_LIMIT)
- return {
- deletedIds: tombstones.map(t => t.entityId),
- docs,
- serverTime,
- truncated,
- }
- },
-})
-
-export const ensureSyncMeta = mutation({
- args: {},
- handler: async (ctx) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return
- const existing = await ctx.db
- .query('syncMeta')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .first()
- if (existing?.trnsIdsHash)
- return
- await ctx.scheduler.runAfter(0, internal.trnsHash.recalcHashForUser, { userId: user._id })
- },
-})
-
-export const idsHash = query({
- args: {},
- handler: async (ctx) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- const serverTime = Date.now()
- const meta = await ctx.db
- .query('syncMeta')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .first()
- if (meta?.trnsIdsHash)
- return { hash: meta.trnsIdsHash, serverTime }
- // Fallback: compute XOR hash via pagination (before syncMeta row exists)
- let hash = 0
- let isDone = false
- let cursor: string | null = null
- while (!isDone) {
- const page = await ctx.db
- .query('trns')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .paginate({ cursor, numItems: 5000 })
- for (const t of page.page)
- hash = (hash ^ fnv1aNum(t._id)) >>> 0
- isDone = page.isDone
- cursor = page.continueCursor
- }
- return { hash: hash.toString(36), serverTime }
- },
-})
-
-export const list = query({
- args: { paginationOpts: paginationOptsValidator },
- handler: async (ctx, { paginationOpts }) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- return ctx.db
- .query('trns')
- .withIndex('by_user_date', q => q.eq('userId', user._id))
- .order('desc')
- .paginate(paginationOpts)
- },
-})
-
-export const create = mutation({
- args: {
- amount: v.optional(v.number()),
- categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
- date: v.number(),
- desc: v.optional(v.string()),
- expenseAmount: v.optional(v.number()),
- expenseWalletId: v.optional(v.id('wallets')),
- incomeAmount: v.optional(v.number()),
- incomeWalletId: v.optional(v.id('wallets')),
- type: trnTypeValidator,
- walletId: v.optional(v.id('wallets')),
- },
- handler: async (ctx, args) => {
- const user = await requireAuthUser(ctx)
- await validateTrnFields(ctx, args, user._id)
- const data = args.type === TrnType.Transfer
- ? { ...args, categoryId: 'transfer' as const }
- : args
- const id = await ctx.db.insert('trns', {
- ...data,
- updatedAt: Date.now(),
- userId: user._id,
- })
- await toggleTrnHash(ctx, user._id, id)
- return id
- },
-})
-
-export const update = mutation({
- args: {
- amount: v.optional(v.number()),
- categoryId: v.optional(v.union(v.id('categories'), v.literal('transfer'), v.literal('adjustment'))),
- date: v.optional(v.number()),
- desc: v.optional(v.string()),
- expenseAmount: v.optional(v.number()),
- expenseWalletId: v.optional(v.id('wallets')),
- id: v.id('trns'),
- incomeAmount: v.optional(v.number()),
- incomeWalletId: v.optional(v.id('wallets')),
- type: v.optional(trnTypeValidator),
- walletId: v.optional(v.id('wallets')),
- },
- handler: async (ctx, { id, ...args }) => {
- const user = await requireAuthUser(ctx)
- const trn = await getOwnEntity(ctx, id, user._id)
-
- // Build patch first — normalize stale fields when type changes
- const patch: Record<string, any> = { ...args, updatedAt: Date.now() }
- if (args.type !== undefined && args.type !== trn.type) {
- if (args.type === TrnType.Transfer) {
- patch.walletId = undefined
- patch.amount = undefined
- if (!args.categoryId)
- patch.categoryId = 'transfer'
- }
- else {
- patch.expenseWalletId = undefined
- patch.incomeWalletId = undefined
- patch.expenseAmount = undefined
- patch.incomeAmount = undefined
- }
- }
-
- // Validate the final state (existing trn + normalized patch)
- await validateTrnFields(ctx, { ...trn, ...patch }, user._id)
- await ctx.db.patch(id, patch)
- },
-})
-
-async function removeUserTrn(ctx: MutationCtx, id: Id<'trns'>, userId: string): Promise<boolean> {
- const trn = await ctx.db.get(id)
- if (trn && trn.userId === userId) {
- await ctx.db.delete(id)
- return true
- }
- return false
-}
-
-export const remove = mutation({
- args: { id: v.id('trns') },
- handler: async (ctx, { id }) => {
- const user = await requireAuthUser(ctx)
- const deleted = await removeUserTrn(ctx, id, user._id)
- if (deleted) {
- await toggleTrnHash(ctx, user._id, id)
- await emitTombstone(ctx, user._id, 'trns', id)
- }
- },
-})
diff --git a/app/convex/trnsHash.ts b/app/convex/trnsHash.ts
deleted file mode 100644
index 18a8dbd5..00000000
--- a/app/convex/trnsHash.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { v } from 'convex/values'
-
-import type { MutationCtx } from './_generated/server'
-
-import { internal } from './_generated/api'
-import { internalAction, internalMutation } from './_generated/server'
-
-// Duplicate: also in utils/fnv1a.ts (Convex has its own bundler, can't share)
-export function fnv1aNum(str: string): number {
- let hash = 0x811C9DC5
- for (let i = 0; i < str.length; i++) {
- hash ^= str.charCodeAt(i)
- hash = Math.imul(hash, 0x01000193)
- }
- return hash >>> 0
-}
-
-export async function getOrCreateSyncMeta(ctx: MutationCtx, userId: string) {
- const existing = await ctx.db
- .query('syncMeta')
- .withIndex('by_user', q => q.eq('userId', userId))
- .first()
- if (existing)
- return existing
- const id = await ctx.db.insert('syncMeta', { userId })
- return (await ctx.db.get(id))!
-}
-
-// XOR is symmetric: toggling an ID in = adding, toggling it out = removing.
-export async function toggleTrnHash(ctx: MutationCtx, userId: string, trnId: string) {
- const meta = await getOrCreateSyncMeta(ctx, userId)
- const current = meta.trnsIdsHash ? Number.parseInt(meta.trnsIdsHash, 36) : 0
- const updated = (current ^ fnv1aNum(trnId)) >>> 0
- await ctx.db.patch(meta._id, { trnsIdsHash: updated.toString(36) })
-}
-
-export async function toggleTrnsHash(ctx: MutationCtx, userId: string, trnIds: string[]) {
- if (trnIds.length === 0)
- return
- const meta = await getOrCreateSyncMeta(ctx, userId)
- let hash = meta.trnsIdsHash ? Number.parseInt(meta.trnsIdsHash, 36) : 0
- for (const id of trnIds)
- hash = (hash ^ fnv1aNum(id)) >>> 0
- await ctx.db.patch(meta._id, { trnsIdsHash: hash.toString(36) })
-}
-
-export const recalcHashPage = internalMutation({
- args: {
- cursor: v.union(v.string(), v.null()),
- runningHash: v.number(),
- userId: v.string(),
- },
- handler: async (ctx, { cursor, runningHash, userId }) => {
- const page = await ctx.db
- .query('trns')
- .withIndex('by_user', q => q.eq('userId', userId))
- .paginate({ cursor, numItems: 5000 })
-
- let hash = runningHash
- for (const t of page.page)
- hash = (hash ^ fnv1aNum(t._id)) >>> 0
-
- if (page.isDone) {
- const meta = await getOrCreateSyncMeta(ctx, userId)
- await ctx.db.patch(meta._id, { trnsIdsHash: hash.toString(36) })
- return { isDone: true as const }
- }
-
- return {
- continueCursor: page.continueCursor,
- hash,
- isDone: false as const,
- }
- },
-})
-
-export const recalcHashForUser = internalAction({
- args: { userId: v.string() },
- handler: async (ctx, { userId }) => {
- let cursor: string | null = null
- let hash = 0
-
- while (true) {
- const result: { isDone: true } | { continueCursor: string, hash: number, isDone: false }
- = await ctx.runMutation(internal.trnsHash.recalcHashPage, {
- cursor,
- runningHash: hash,
- userId,
- })
-
- if (result.isDone)
- break
-
- cursor = result.continueCursor
- hash = result.hash
- }
- },
-})
diff --git a/app/convex/tsconfig.json b/app/convex/tsconfig.json
deleted file mode 100644
index 849f5e16..00000000
--- a/app/convex/tsconfig.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "compilerOptions": {
- "target": "ESNext",
- "jsx": "react-jsx",
- "module": "ESNext",
- "moduleResolution": "bundler",
- "types": ["node"],
- "strict": true,
- "noEmit": true,
- "skipLibCheck": true
- },
- "include": ["./**/*.ts"]
-}
diff --git a/app/convex/user.ts b/app/convex/user.ts
deleted file mode 100644
index 975ab54e..00000000
--- a/app/convex/user.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { v } from 'convex/values'
-
-import { internal } from './_generated/api'
-import { action, internalQuery, mutation, query } from './_generated/server'
-import { getAuthUser, requireAuthUser, validateStringLength } from './shared'
-
-export const get = query({
- args: {},
- handler: async (ctx) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- return await ctx.db
- .query('userSettings')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .first()
- },
-})
-
-export const upsert = mutation({
- args: {
- baseCurrency: v.optional(v.string()),
- locale: v.optional(v.union(v.literal('en'), v.literal('ru'))),
- },
- handler: async (ctx, args) => {
- const user = await requireAuthUser(ctx)
-
- if (args.baseCurrency !== undefined && !args.baseCurrency.trim())
- throw new Error('Base currency is required')
- validateStringLength(args.baseCurrency, 10, 'Base currency')
-
- const existing = await ctx.db
- .query('userSettings')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .first()
-
- if (existing) {
- await ctx.db.patch(existing._id, args)
- return existing._id
- }
-
- return await ctx.db.insert('userSettings', {
- baseCurrency: args.baseCurrency ?? 'USD',
- locale: args.locale,
- userId: user._id,
- })
- },
-})
-
-export const removeAllUserData = action({
- args: {},
- handler: async (ctx) => {
- const user = await ctx.runQuery(internal.user.getCurrentUser)
- if (!user)
- throw new Error('Unauthorized')
- await ctx.runAction(internal.migrate.deleteUserData, { userId: user._id })
- },
-})
-
-export const getCurrentUser = internalQuery({
- args: {},
- handler: async (ctx) => {
- return await getAuthUser(ctx)
- },
-})
diff --git a/app/convex/validators.ts b/app/convex/validators.ts
deleted file mode 100644
index 4b500e70..00000000
--- a/app/convex/validators.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { v } from 'convex/values'
-
-export const walletTypes = ['cash', 'credit', 'cashless', 'deposit', 'crypto', 'debt'] as const
-export type WalletType = typeof walletTypes[number]
-
-export const walletTypeValidator = v.union(
- ...walletTypes.map(t => v.literal(t)) as [
- ReturnType<typeof v.literal>,
- ReturnType<typeof v.literal>,
- ...ReturnType<typeof v.literal>[],
- ],
-)
-
-export enum TrnType {
- Expense = 0,
- Income = 1,
- Transfer = 2,
-}
diff --git a/app/convex/wallets.test.ts b/app/convex/wallets.test.ts
deleted file mode 100644
index d15760f2..00000000
--- a/app/convex/wallets.test.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { convexTest } from 'convex-test'
-import { describe, expect, it } from 'vitest'
-
-import { api } from './_generated/api'
-import schema from './schema'
-import { modules, setMockUser } from './test_utils/setup.helper'
-
-const validWallet = {
- color: '#ff0000',
- currency: 'USD',
- name: 'Cash',
- order: 0,
- type: 'cash' as const,
-}
-
-describe('convex/wallets', () => {
- describe('create', () => {
- it('creates a wallet with defaults', async () => {
- const t = convexTest(schema, modules)
- const id = await t.mutation(api.wallets.create, validWallet)
-
- const wallets = await t.query(api.wallets.list)
- expect(wallets).toHaveLength(1)
- expect(wallets![0]).toMatchObject({
- ...validWallet,
- _id: id,
- isArchived: false,
- isExcludeInTotal: false,
- isWithdrawal: false,
- userId: 'test-user-id',
- })
- })
-
- it('throws for empty name', async () => {
- const t = convexTest(schema, modules)
- await expect(
- t.mutation(api.wallets.create, { ...validWallet, name: ' ' }),
- ).rejects.toThrow('Name is required')
- })
-
- it('throws for unauthenticated user', async () => {
- const t = convexTest(schema, modules)
- setMockUser(null)
- await expect(
- t.mutation(api.wallets.create, validWallet),
- ).rejects.toThrow('Unauthorized')
- })
- })
-
- describe('update', () => {
- it('updates wallet fields', async () => {
- const t = convexTest(schema, modules)
- const id = await t.mutation(api.wallets.create, validWallet)
- await t.mutation(api.wallets.update, { color: '#00ff00', id, name: 'Updated' })
-
- const wallets = await t.query(api.wallets.list)
- expect(wallets![0]).toMatchObject({ color: '#00ff00', name: 'Updated' })
- })
-
- it('throws for wallet owned by another user', async () => {
- const t = convexTest(schema, modules)
- const id = await t.mutation(api.wallets.create, validWallet)
-
- setMockUser('other-user')
- await expect(
- t.mutation(api.wallets.update, { id, name: 'Hack' }),
- ).rejects.toThrow('Not found')
- })
- })
-
- describe('updateOrder', () => {
- it('reorders wallets', async () => {
- const t = convexTest(schema, modules)
- const id1 = await t.mutation(api.wallets.create, { ...validWallet, order: 0 })
- const id2 = await t.mutation(api.wallets.create, { ...validWallet, name: 'Card', order: 1 })
-
- await t.mutation(api.wallets.updateOrder, {
- orders: [{ id: id1, order: 1 }, { id: id2, order: 0 }],
- })
-
- const wallets = await t.query(api.wallets.list)
- const w1 = wallets!.find(w => w._id === id1)!
- const w2 = wallets!.find(w => w._id === id2)!
- expect(w1.order).toBe(1)
- expect(w2.order).toBe(0)
- })
- })
-
- describe('list', () => {
- it('returns null for unauthenticated user', async () => {
- const t = convexTest(schema, modules)
- setMockUser(null)
- expect(await t.query(api.wallets.list)).toBeNull()
- })
-
- it('returns only own wallets', async () => {
- const t = convexTest(schema, modules)
- await t.mutation(api.wallets.create, validWallet)
-
- setMockUser('other-user')
- await t.mutation(api.wallets.create, { ...validWallet, name: 'Other' })
-
- const otherWallets = await t.query(api.wallets.list)
- expect(otherWallets).toHaveLength(1)
- expect(otherWallets![0].name).toBe('Other')
- })
- })
-
- describe('remove (cascade)', () => {
- it('deletes wallet and its transactions', async () => {
- const t = convexTest(schema, modules)
- const walletId = await t.mutation(api.wallets.create, validWallet)
-
- const catId = await t.mutation(api.categories.create, {
- color: '#000',
- icon: 'food',
- name: 'Food',
- showInLastUsed: true,
- showInQuickSelector: true,
- })
-
- await t.mutation(api.trns.create, {
- amount: 100,
- categoryId: catId,
- date: Date.now(),
- type: 0,
- walletId,
- })
-
- await t.action(api.wallets.remove, { id: walletId })
-
- expect(await t.query(api.wallets.list)).toHaveLength(0)
- const trns = await t.query(api.trns.list, { paginationOpts: { cursor: null, numItems: 10 } })
- expect(trns!.page).toHaveLength(0)
- })
- })
-})
diff --git a/app/convex/wallets.ts b/app/convex/wallets.ts
deleted file mode 100644
index a2265883..00000000
--- a/app/convex/wallets.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { v } from 'convex/values'
-
-import { internal } from './_generated/api'
-import { action, internalMutation, mutation, query } from './_generated/server'
-import { CREDIT_LIMIT_MAX, getAuthUser, getOwnEntity, requireAuthUser, validateNumberRange, validateStringLength } from './shared'
-import { emitTombstone, emitTombstones } from './tombstones'
-import { toggleTrnsHash } from './trnsHash'
-import { walletTypeValidator } from './validators'
-
-export const list = query({
- args: {},
- handler: async (ctx) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- return await ctx.db
- .query('wallets')
- .withIndex('by_user', q => q.eq('userId', user._id))
- .collect()
- },
-})
-
-const REALTIME_DELTA_LIMIT = 500
-
-export const deltaRealtime = query({
- args: { since: v.number() },
- handler: async (ctx, { since }) => {
- const user = await getAuthUser(ctx)
- if (!user)
- return null
- const serverTime = Date.now()
- const docsPlusOne = await ctx.db
- .query('wallets')
- .withIndex('by_user_updatedAt', q =>
- q.eq('userId', user._id).gt('updatedAt', since))
- .take(REALTIME_DELTA_LIMIT + 1)
- const truncated = docsPlusOne.length > REALTIME_DELTA_LIMIT
- const docs = truncated ? docsPlusOne.slice(0, REALTIME_DELTA_LIMIT) : docsPlusOne
- const tombstones = await ctx.db
- .query('tombstones')
- .withIndex('by_user_entity_deletedAt', q =>
- q.eq('userId', user._id).eq('entity', 'wallets').gt('deletedAt', since))
- .take(REALTIME_DELTA_LIMIT)
- return {
- deletedIds: tombstones.map(t => t.entityId),
- docs,
- serverTime,
- truncated,
- }
- },
-})
-
-export const create = mutation({
- args: {
- color: v.string(),
- creditLimit: v.optional(v.number()),
- currency: v.string(),
- desc: v.optional(v.string()),
- isArchived: v.optional(v.boolean()),
- isExcludeInTotal: v.optional(v.boolean()),
- isWithdrawal: v.optional(v.boolean()),
- name: v.string(),
- order: v.number(),
- type: walletTypeValidator,
- },
- handler: async (ctx, args) => {
- const user = await requireAuthUser(ctx)
- if (!args.name.trim())
- throw new Error('Name is required')
- if (!args.color.trim())
- throw new Error('Color is required')
- if (!args.currency.trim())
- throw new Error('Currency is required')
- validateStringLength(args.name, 100, 'Name')
- validateStringLength(args.color, 50, 'Color')
- validateStringLength(args.currency, 10, 'Currency')
- validateStringLength(args.desc, 500, 'Description')
- validateNumberRange(args.creditLimit, 0, CREDIT_LIMIT_MAX, 'Credit limit')
- return await ctx.db.insert('wallets', {
- ...args,
- isArchived: args.isArchived ?? false,
- isExcludeInTotal: args.isExcludeInTotal ?? false,
- isWithdrawal: args.isWithdrawal ?? false,
- updatedAt: Date.now(),
- userId: user._id,
- })
- },
-})
-
-export const update = mutation({
- args: {
- color: v.optional(v.string()),
- creditLimit: v.optional(v.number()),
- currency: v.optional(v.string()),
- desc: v.optional(v.string()),
- id: v.id('wallets'),
- isArchived: v.optional(v.boolean()),
- isExcludeInTotal: v.optional(v.boolean()),
- isWithdrawal: v.optional(v.boolean()),
- name: v.optional(v.string()),
- order: v.optional(v.number()),
- type: v.optional(walletTypeValidator),
- },
- handler: async (ctx, { id, ...args }) => {
- const user = await requireAuthUser(ctx)
- if (args.name !== undefined && !args.name.trim())
- throw new Error('Name is required')
- if (args.color !== undefined && !args.color.trim())
- throw new Error('Color is required')
- if (args.currency !== undefined && !args.currency.trim())
- throw new Error('Currency is required')
- validateStringLength(args.name, 100, 'Name')
- validateStringLength(args.color, 50, 'Color')
- validateStringLength(args.currency, 10, 'Currency')
- validateStringLength(args.desc, 500, 'Description')
- validateNumberRange(args.creditLimit, 0, CREDIT_LIMIT_MAX, 'Credit limit')
- await getOwnEntity(ctx, id, user._id)
- await ctx.db.patch(id, { ...args, updatedAt: Date.now() })
- },
-})
-
-export const updateOrder = mutation({
- args: {
- orders: v.array(v.object({
- id: v.id('wallets'),
- order: v.number(),
- })),
- },
- handler: async (ctx, { orders }) => {
- const user = await requireAuthUser(ctx)
- for (const { id, order } of orders) {
- await getOwnEntity(ctx, id, user._id)
- await ctx.db.patch(id, { order, updatedAt: Date.now() })
- }
- },
-})
-
-export const removeTrnsByWalletPage = internalMutation({
- args: {
- cursor: v.union(v.string(), v.null()),
- indexName: v.union(
- v.literal('by_user_wallet'),
- v.literal('by_user_expenseWallet'),
- v.literal('by_user_incomeWallet'),
- ),
- userId: v.string(),
- walletId: v.id('wallets'),
- },
- handler: async (ctx, { cursor, indexName, userId, walletId }) => {
- const page = await ctx.db
- .query('trns')
- .withIndex(indexName, q => q.eq('userId', userId).eq(
- indexName === 'by_user_wallet' ? 'walletId' : indexName === 'by_user_expenseWallet' ? 'expenseWalletId' : 'incomeWalletId',
- walletId,
- ))
- .paginate({ cursor, numItems: 500 })
-
- const deletedIds: string[] = []
- for (const trn of page.page) {
- await ctx.db.delete(trn._id)
- deletedIds.push(trn._id)
- }
-
- if (deletedIds.length) {
- await toggleTrnsHash(ctx, userId, deletedIds)
- await emitTombstones(ctx, userId, 'trns', deletedIds)
- }
-
- return { continueCursor: page.continueCursor, isDone: page.isDone }
- },
-})
-
-export const removeWalletFinalize = internalMutation({
- args: {
- userId: v.string(),
- walletId: v.id('wallets'),
- },
- handler: async (ctx, { userId, walletId }) => {
- const wallet = await ctx.db.get(walletId)
- if (wallet && wallet.userId === userId) {
- await ctx.db.delete(walletId)
- await emitTombstone(ctx, userId, 'wallets', walletId)
- }
- },
-})
-
-export const remove = action({
- args: { id: v.id('wallets') },
- handler: async (ctx, { id }) => {
- const user = await ctx.runQuery(internal.user.getCurrentUser)
- if (!user)
- throw new Error('Unauthorized')
-
- const indexes = ['by_user_wallet', 'by_user_expenseWallet', 'by_user_incomeWallet'] as const
- for (const indexName of indexes) {
- let cursor: string | null = null
- let isDone = false
- while (!isDone) {
- const result: { continueCursor: string, isDone: boolean } = await ctx.runMutation(internal.wallets.removeTrnsByWalletPage, {
- cursor,
- indexName,
- userId: user._id,
- walletId: id,
- })
- isDone = result.isDone
- cursor = result.continueCursor
- }
- }
-
- await ctx.runMutation(internal.wallets.removeWalletFinalize, {
- userId: user._id,
- walletId: id,
- })
- },
-})
diff --git a/app/services/convex/api.test.ts b/app/services/convex/api.test.ts
deleted file mode 100644
index 9f24dbfe..00000000
--- a/app/services/convex/api.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { convexWalletsToMap } from '~~/services/convex/api'
-
-describe('convexWalletsToMap (arrayToMap)', () => {
- it('strips _id, _creationTime, userId and uses _id as key', () => {
- const docs = [
- { _creationTime: 123, _id: 'w1', color: '#0f0', currency: 'USD', name: 'Cash', userId: 'u1' },
- { _creationTime: 456, _id: 'w2', color: '#f00', currency: 'EUR', name: 'Card', userId: 'u1' },
- ]
-
- const result = convexWalletsToMap(docs as any)
-
- expect(result).toEqual({
- w1: { color: '#0f0', currency: 'USD', name: 'Cash' },
- w2: { color: '#f00', currency: 'EUR', name: 'Card' },
- })
- })
-
- it('returns empty object for empty array', () => {
- expect(convexWalletsToMap([])).toEqual({})
- })
-})
diff --git a/app/services/convex/api.ts b/app/services/convex/api.ts
deleted file mode 100644
index c846d8de..00000000
--- a/app/services/convex/api.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { Categories, CategoryItem } from '~/components/categories/types'
-import type { TrnItem, Trns } from '~/components/trns/types'
-import type { WalletItem, Wallets } from '~/components/wallets/types'
-
-type ConvexDoc = {
- [key: string]: unknown
- _creationTime: number
- _id: string
- userId: string
-}
-
-function arrayToMap<T>(docs: ConvexDoc[]): Record<string, T> {
- const map: Record<string, T> = {}
- for (const doc of docs) {
- const { _creationTime, _id, userId, ...rest } = doc
- map[_id] = rest as T
- }
- return map
-}
-
-export function convexWalletsToMap(wallets: ConvexDoc[]): Wallets {
- return arrayToMap<WalletItem>(wallets)
-}
-
-export function convexCategoriesToMap(categories: ConvexDoc[]): Categories {
- return arrayToMap<CategoryItem>(categories) as Categories
-}
-
-export function convexTrnsToMap(trns: ConvexDoc[]): Trns {
- return arrayToMap<TrnItem>(trns)
-}
diff --git a/app/services/convex/client.ts b/app/services/convex/client.ts
deleted file mode 100644
index 43338426..00000000
--- a/app/services/convex/client.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { ConvexClient } from 'convex/browser'
-
-let clientInstance: ConvexClient | null = null
-
-export function createConvexClient(url: string): ConvexClient {
- if (!clientInstance)
- clientInstance = new ConvexClient(url)
- return clientInstance
-}
diff --git a/app/utils/fnv1a.test.ts b/app/utils/fnv1a.test.ts
deleted file mode 100644
index e39a923a..00000000
--- a/app/utils/fnv1a.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { fnv1aNum, xorIdsHash } from '~~/utils/fnv1a'
-
-describe('fnv1aNum', () => {
- it('returns consistent hash for same input (regression snapshot)', () => {
- expect(fnv1aNum('trn1')).toBe(563873362)
- expect(fnv1aNum('wallet_abc')).toBe(1520395703)
- })
-
- it('returns different hashes for different inputs', () => {
- expect(fnv1aNum('a')).not.toBe(fnv1aNum('b'))
- })
-})
-
-describe('xorIdsHash', () => {
- it('returns consistent hash (regression snapshot)', () => {
- expect(xorIdsHash(['trn1'])).toBe(fnv1aNum('trn1').toString(36))
- })
-
- it('is order-independent (critical for sync — DB order not guaranteed)', () => {
- const hash1 = xorIdsHash(['a', 'b', 'c'])
- const hash2 = xorIdsHash(['c', 'a', 'b'])
-
- expect(hash1).toBe(hash2)
- })
-
- it('returns "0" for empty array', () => {
- expect(xorIdsHash([])).toBe('0')
- })
-})
diff --git a/app/utils/fnv1a.ts b/app/utils/fnv1a.ts
deleted file mode 100644
index c0f59beb..00000000
--- a/app/utils/fnv1a.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-// Duplicate: also in convex/trnsHash.ts (Convex has its own bundler, can't share)
-export function fnv1aNum(str: string): number {
- let hash = 0x811C9DC5
- for (let i = 0; i < str.length; i++) {
- hash ^= str.charCodeAt(i)
- hash = Math.imul(hash, 0x01000193)
- }
- return hash >>> 0
-}
-
-export function xorIdsHash(ids: string[]): string {
- let hash = 0
- for (const id of ids)
- hash = (hash ^ fnv1aNum(id)) >>> 0
- return hash.toString(36)
-}
diff --git a/eslint.config.js b/eslint.config.js
index 960c1cb0..f7e0c145 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -31,8 +31,13 @@ export default [
'**/.output/**',
'**/coverage/**',
'**/dist/**',
- 'app/convex/_generated/**',
+ '**/playwright-report/**',
+ '.claude/**',
+ '.understand-anything/**',
+ 'graphify-out/**',
'app/playwright/profiles/**',
+ 'app/powersync/**',
+ 'app/supabase/config.toml',
'app/tests/e2e/.auth/**',
'app/utils/migrate/data.json',
],
@@ -77,12 +82,6 @@ export default [
vue: true,
}),
)),
- {
- files: ['app/convex/**/*.ts', 'app/scripts/**/*.mjs'],
- rules: {
- 'node/prefer-global/process': 'off',
- },
- },
{
files: ['app/app/layouts/**/*.vue'],
rules: {