Skip to content

Open source personal finance application

refactor: offline queue — OfflineEntityType enum, extract replay helpers with Zod validation

Ilya Komichev28cbac577062
diff --git a/app/components/offline/helpers.test.ts b/app/components/offline/helpers.test.ts
index 3c459074..16adaca1 100644
--- a/app/components/offline/helpers.test.ts
+++ b/app/components/offline/helpers.test.ts
@@ -8,6 +8,7 @@ import {
removeOfflineOp,
removeOfflineOpByType,
} from '~/components/offline/helpers'
+import { OfflineEntityType } from '~/components/offline/types'
// Mock localforage
const store = new Map<string, any>()
@@ -36,17 +37,17 @@ afterEach(() => {
describe('pushOfflineOp', () => {
it('adds operation to empty queue', async () => {
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ 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: 'trns', id: 'trn1', type: 'create' })
+ 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: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ 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)
@@ -54,8 +55,8 @@ describe('pushOfflineOp', () => {
describe('collapsing rules', () => {
it('create + update → create with merged data', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { name: 'Cash Updated' }, entity: 'wallets', id: 'w1', type: 'update' })
+ 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)
@@ -64,16 +65,16 @@ describe('pushOfflineOp', () => {
})
it('create + delete → both removed', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
+ 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: 'wallets', id: 'w1', type: 'update' })
- await pushOfflineOp({ data: { name: 'New' }, entity: 'wallets', id: 'w1', type: 'update' })
+ 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)
@@ -82,8 +83,8 @@ describe('pushOfflineOp', () => {
})
it('update + delete → replace with delete', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'update' })
- await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
+ 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)
@@ -91,8 +92,8 @@ describe('pushOfflineOp', () => {
})
it('delete + any → ignores new operation', async () => {
- await pushOfflineOp({ entity: 'wallets', id: 'w1', type: 'delete' })
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ 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)
@@ -103,20 +104,20 @@ describe('pushOfflineOp', () => {
describe('removeOfflineOp', () => {
it('removes all operations for entity+id', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ 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('wallets', 'w1')
+ await removeOfflineOp(OfflineEntityType.Wallets, 'w1')
const queue = await getAllOfflineOps()
expect(queue).toHaveLength(1)
- expect(queue[0]!.entity).toBe('trns')
+ expect(queue[0]!.entity).toBe(OfflineEntityType.Trns)
})
it('does nothing when not found', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await removeOfflineOp('wallets', 'w999')
+ await removeOfflineOp(OfflineEntityType.Wallets, 'w999')
const queue = await getAllOfflineOps()
expect(queue).toHaveLength(1)
@@ -125,9 +126,9 @@ describe('removeOfflineOp', () => {
describe('removeOfflineOpByType', () => {
it('removes specific operation by type', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
+ await pushOfflineOp({ data: { name: 'Cash' }, entity: OfflineEntityType.Wallets, id: 'w1', type: 'create' })
- await removeOfflineOpByType('wallets', 'w1', 'create')
+ await removeOfflineOpByType(OfflineEntityType.Wallets, 'w1', 'create')
const queue = await getAllOfflineOps()
expect(queue).toHaveLength(0)
@@ -136,27 +137,27 @@ describe('removeOfflineOpByType', () => {
describe('getOfflineOpsByEntity', () => {
it('filters by entity', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
- await pushOfflineOp({ data: { name: 'Food' }, entity: 'categories', id: 'c1', type: 'create' })
+ 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('wallets')
+ const walletOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
expect(walletOps).toHaveLength(1)
- expect(walletOps[0]!.entity).toBe('wallets')
+ expect(walletOps[0]!.entity).toBe(OfflineEntityType.Wallets)
})
it('returns empty array when no matching ops', async () => {
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ await pushOfflineOp({ data: { amount: 100 }, entity: OfflineEntityType.Trns, id: 'trn1', type: 'create' })
- const walletOps = await getOfflineOpsByEntity('wallets')
+ const walletOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
expect(walletOps).toHaveLength(0)
})
})
describe('clearOfflineQueue', () => {
it('removes all operations', async () => {
- await pushOfflineOp({ data: { name: 'Cash' }, entity: 'wallets', id: 'w1', type: 'create' })
- await pushOfflineOp({ data: { amount: 100 }, entity: 'trns', id: 'trn1', type: 'create' })
+ 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()
@@ -167,11 +168,11 @@ describe('clearOfflineQueue', () => {
describe('cross-entity isolation', () => {
it('different entities have separate operations', async () => {
- await pushOfflineOp({ data: { a: 1 }, entity: 'trns', id: 'id1', type: 'create' })
- await pushOfflineOp({ data: { b: 2 }, entity: 'wallets', id: 'id1', type: 'create' })
+ 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('trns')
- const walletsOps = await getOfflineOpsByEntity('wallets')
+ const trnsOps = await getOfflineOpsByEntity(OfflineEntityType.Trns)
+ const walletsOps = await getOfflineOpsByEntity(OfflineEntityType.Wallets)
expect(trnsOps).toHaveLength(1)
expect(trnsOps[0]!.data).toEqual({ a: 1 })
@@ -180,13 +181,13 @@ describe('cross-entity isolation', () => {
})
it('collapsing only applies within same entity+id', async () => {
- await pushOfflineOp({ data: { a: 1 }, entity: 'trns', id: 'id1', type: 'create' })
- await pushOfflineOp({ data: { b: 2 }, entity: 'wallets', id: 'id1', type: 'create' })
- await pushOfflineOp({ entity: 'trns', id: 'id1', type: 'delete' })
+ 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()
// trns create+delete collapsed to nothing, wallets create remains
expect(queue).toHaveLength(1)
- expect(queue[0]!.entity).toBe('wallets')
+ expect(queue[0]!.entity).toBe(OfflineEntityType.Wallets)
})
})
diff --git a/app/components/offline/replay.ts b/app/components/offline/replay.ts
index 49a51f8e..c046f82d 100644
--- a/app/components/offline/replay.ts
+++ b/app/components/offline/replay.ts
@@ -1,15 +1,10 @@
-import type { CategoryItem } from '~/components/categories/types'
-import type { CurrencyCode } from '~/components/currencies/types'
-import type { LocaleSlug } from '~/components/locale/types'
-import type { TrnItem } from '~/components/trns/types'
-import type { WalletItem } from '~/components/wallets/types'
-
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { clearOfflineQueue, getAllOfflineOps, getQueueUserId, removeOfflineOp, setOfflineQueueUserId, setQueueUserId } from '~/components/offline/helpers'
-import { extractRemaps, groupOpsByEntity, isTrnOrphaned, remapTrnIds, splitCategoryOps } from '~/components/offline/replayHelpers'
+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')
@@ -20,13 +15,6 @@ export function isReplaying(): boolean {
return _isReplaying
}
-async function collectRemaps(promises: (Promise<unknown> | void | undefined)[], remapIds: Map<string, string>) {
- const results = await Promise.all(promises.map(p => p ?? Promise.resolve()))
- for (const { convexId, localId } of extractRemaps(results)) {
- remapIds.set(localId, convexId)
- }
-}
-
export async function replayOfflineQueue(): Promise<void> {
if (_isReplaying)
return
@@ -80,98 +68,51 @@ export async function replayOfflineQueue(): Promise<void> {
_isReplaying = true
const remapIds = new Map<string, string>()
- let orphanCount = 0
try {
// Phase 1: Replay wallets
- if (walletOps.length > 0) {
+ if (walletOps.length > 0)
logger.log(`phase 1: ${walletOps.length} wallet ops`)
- const promises = walletOps.map((op) => {
- if (op.type === 'delete')
- return walletsStore.deleteWallet(op.id)
- return walletsStore.saveWallet({ id: op.id, values: op.data as unknown as WalletItem })
- })
- await collectRemaps(promises, remapIds)
- }
+ 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) {
- const { childOps, parentOps } = splitCategoryOps(categoryOps)
-
- // Phase 2a: Parent categories
- if (parentOps.length > 0) {
- logger.log(`phase 2a: ${parentOps.length} parent category ops`)
- const promises = parentOps.map((op) => {
- if (op.type === 'delete')
- return categoriesStore.deleteCategory(op.id)
- return categoriesStore.saveCategory({
- id: op.id,
- isUpdateChildCategoriesColor: false,
- values: op.data as unknown as CategoryItem,
- })
- })
- await collectRemaps(promises, remapIds)
- }
-
- // Phase 2b: Child categories (remap parentId if needed)
- if (childOps.length > 0) {
- logger.log(`phase 2b: ${childOps.length} child category ops`)
- const promises = childOps.map((op) => {
- const data = op.data as unknown as CategoryItem
- const remappedParentId = remapIds.get(String(data.parentId)) ?? data.parentId
- const values = remappedParentId !== data.parentId
- ? { ...data, parentId: remappedParentId }
- : data
- return categoriesStore.saveCategory({
- id: op.id,
- isUpdateChildCategoriesColor: false,
- values: values as CategoryItem,
- })
- })
- await collectRemaps(promises, remapIds)
- }
- }
+ 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) {
+ if (trnOps.length > 0)
logger.log(`phase 3: ${trnOps.length} trn ops`)
- for (const op of trnOps) {
- if (op.type === 'delete') {
- trnsStore.deleteTrn(op.id)
- continue
- }
-
- const data = op.data as unknown as TrnItem
- const remapped = remapTrnIds(data, remapIds)
-
- if (isTrnOrphaned(remapped, walletsStore.items ?? {}, categoriesStore.items)) {
- orphanCount++
- logger.log(`skip (orphaned): ${op.entity}/${op.id}`)
- await removeOfflineOp(op.entity, op.id)
- continue
- }
-
- trnsStore.saveTrn({ id: op.id, values: remapped })
- }
- }
-
- // Phase 4: Settings
- for (const op of settingsOps) {
- if (op.data?.baseCurrency)
- userStore.saveUserBaseCurrency(op.data.baseCurrency as CurrencyCode)
- if (op.data?.locale)
- userStore.saveUserLocale(op.data.locale as LocaleSlug)
+ 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),
+ })
+
+ if (orphanCount > 0) {
+ const { showWarningToast } = await import('~/composables/useStoreSync')
+ showWarningToast('trns.errors.orphanedSkipped', { count: orphanCount })
}
}
finally {
_isReplaying = false
}
- if (orphanCount > 0) {
- const { showWarningToast } = await import('~/composables/useStoreSync')
- showWarningToast('trns.errors.orphanedSkipped', { count: orphanCount })
- }
-
if (remapIds.size > 0)
logger.log(`replay complete: ${remapIds.size} IDs remapped`)
else
diff --git a/app/components/offline/replayHelpers.test.ts b/app/components/offline/replayHelpers.test.ts
index 7af8ebd6..666bea92 100644
--- a/app/components/offline/replayHelpers.test.ts
+++ b/app/components/offline/replayHelpers.test.ts
@@ -1,11 +1,16 @@
-import { describe, expect, it } from 'vitest'
+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 { extractRemaps, groupOpsByEntity, isTrnOrphaned, remapTrnIds, splitCategoryOps } from './replayHelpers'
+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 }
@@ -124,12 +129,12 @@ describe('isTrnOrphaned', () => {
describe('groupOpsByEntity', () => {
it('groups operations by entity type', () => {
const ops = [
- makeOp('wallets', 'w1'),
- makeOp('trns', 't1'),
- makeOp('categories', 'c1'),
- makeOp('wallets', 'w2'),
- makeOp('userSettings', 's1'),
- makeOp('trns', 't2'),
+ 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)
@@ -148,7 +153,7 @@ describe('groupOpsByEntity', () => {
})
it('preserves op references', () => {
- const op = makeOp('trns', 't1')
+ const op = makeOp(OfflineEntityType.Trns, 't1')
const result = groupOpsByEntity([op])
expect(result.trnOps[0]).toBe(op)
})
@@ -159,9 +164,9 @@ describe('groupOpsByEntity', () => {
describe('splitCategoryOps', () => {
it('splits parent and child categories', () => {
const ops = [
- makeOp('categories', 'c1', 'create', { name: 'Food', parentId: 0 }),
- makeOp('categories', 'c2', 'create', { name: 'Groceries', parentId: 'c1' }),
- makeOp('categories', 'c3', 'create', { name: 'Transport', parentId: 0 }),
+ 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)
@@ -172,8 +177,8 @@ describe('splitCategoryOps', () => {
it('puts delete ops in parentOps', () => {
const ops = [
- makeOp('categories', 'c1', 'delete'),
- makeOp('categories', 'c2', 'create', { name: 'Child', parentId: 'c1' }),
+ makeOp(OfflineEntityType.Categories, 'c1', 'delete'),
+ makeOp(OfflineEntityType.Categories, 'c2', 'create', { name: 'Child', parentId: 'c1' }),
]
const result = splitCategoryOps(ops)
@@ -184,7 +189,7 @@ describe('splitCategoryOps', () => {
it('treats no parentId as root', () => {
const ops = [
- makeOp('categories', 'c1', 'create', { name: 'Root' }),
+ makeOp(OfflineEntityType.Categories, 'c1', 'create', { name: 'Root' }),
]
const result = splitCategoryOps(ops)
@@ -229,3 +234,370 @@ describe('extractRemaps', () => {
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/components/offline/replayHelpers.ts b/app/components/offline/replayHelpers.ts
index 21eb0553..70ec1f49 100644
--- a/app/components/offline/replayHelpers.ts
+++ b/app/components/offline/replayHelpers.ts
@@ -1,8 +1,46 @@
+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()
-import { TrnType } from '~/components/trns/types'
+/**
+ * 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
+}
/**
* Remap local IDs in trn data using the collected remap map.
@@ -53,16 +91,16 @@ export function groupOpsByEntity(ops: OfflineOp[]): GroupedOps {
for (const op of ops) {
switch (op.entity) {
- case 'wallets':
+ case OfflineEntityType.Wallets:
walletOps.push(op)
break
- case 'categories':
+ case OfflineEntityType.Categories:
categoryOps.push(op)
break
- case 'trns':
+ case OfflineEntityType.Trns:
trnOps.push(op)
break
- case 'userSettings':
+ case OfflineEntityType.UserSettings:
settingsOps.push(op)
break
}
@@ -87,8 +125,9 @@ export function splitCategoryOps(ops: OfflineOp[]): {
parentOps.push(op)
continue
}
- const data = op.data as unknown as CategoryItem
- if (!data.parentId || data.parentId === (0 as string | 0)) {
+ const data = op.data as Record<string, unknown> | undefined
+ const parentId = data?.parentId
+ if (!parentId || parentId === 0) {
parentOps.push(op)
}
else {
@@ -100,7 +139,7 @@ export function splitCategoryOps(ops: OfflineOp[]): {
}
/**
- * Extract remap entries (localId → convexId) from resolved promise results.
+ * Extract remap entries (localId -> convexId) from resolved promise results.
*/
export function extractRemaps(results: unknown[]): Array<{ convexId: string, localId: string }> {
const remaps: Array<{ convexId: string, localId: string }> = []
@@ -110,3 +149,162 @@ export function extractRemaps(results: unknown[]): Array<{ convexId: string, loc
}
return remaps
}
+
+// --- Per-entity replay functions ---
+
+/**
+ * Collect remap entries from resolved promises into the remap map.
+ */
+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
+}
+
+/**
+ * Replay wallet operations: save or delete each wallet, collecting ID remaps.
+ */
+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
+}
+
+/**
+ * Replay category operations: parents first, then children (with parentId remapping).
+ * Collects ID remaps after each sub-phase.
+ */
+export async function replayCategoryOps(ops: OfflineOp[], remapIds: Map<string, string>, actions: CategoryActions): Promise<void> {
+ if (ops.length === 0)
+ return
+
+ const { childOps, parentOps } = splitCategoryOps(ops)
+
+ // Parents first
+ 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)
+ }
+
+ // Children second (remap parentId if needed)
+ 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>
+}
+
+/**
+ * Replay trn operations: remap wallet/category IDs, skip orphaned trns.
+ * Returns the number 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++
+ await actions.removeOfflineOp(op.entity, op.id)
+ continue
+ }
+
+ actions.saveTrn({ id: op.id, values: remapped })
+ }
+
+ return orphanCount
+}
+
+type SettingsActions = {
+ saveBaseCurrency: (currency: string) => void
+ saveLocale: (locale: string) => void
+}
+
+/**
+ * Replay user settings operations: validate and apply base currency and locale changes.
+ */
+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/components/offline/types.ts b/app/components/offline/types.ts
index 4bca87fc..80ccf7f6 100644
--- a/app/components/offline/types.ts
+++ b/app/components/offline/types.ts
@@ -1,4 +1,11 @@
-export type EntityType = 'categories' | 'trns' | 'userSettings' | 'wallets'
+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>