Open source personal finance application
test: rewrite unit and e2e tests against powersync
Ilya Komichev522c15dbefd1
diff --git a/app/app/components/categories/useCategoriesStore.test.ts b/app/app/components/categories/useCategoriesStore.test.tsindex 9c1e8540..8a51f92b 100644--- a/app/app/components/categories/useCategoriesStore.test.ts+++ b/app/app/components/categories/useCategoriesStore.test.ts@@ -1,802 +1,266 @@-import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'--import type { CategoryItem } from '~/components/categories/types'--vi.mock('~~/services/convex/api', () => ({- convexCategoriesToMap: (v: any) => v,-}))--vi.mock('~/components/categories/utils', () => ({- compareCategoriesByParentAndName: () => 0,- compareCategoryIds: () => 0,- computeChildrenDiff: (prev: string[], next: string[]) => {- const prevSet = new Set(prev)- const nextSet = new Set(next)- return {- added: next.filter(id => !prevSet.has(id)),- removed: prev.filter(id => !nextSet.has(id)),- }- },- getTransactibleCategoriesIds: () => [],-}))--const mutationMock = vi.fn<(path: string, args?: unknown) => Promise<unknown>>(() => Promise.resolve(undefined))-const actionMock = vi.fn<(path: string, args?: unknown) => Promise<unknown>>(() => Promise.resolve(undefined))-const onUpdateMock = vi.fn()--vi.stubGlobal('useConvexClientWithApi', () => ({- api: {- categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', setChildren: 'categories.setChildren', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },- },- client: {- action: actionMock,- mutation: mutationMock,- onUpdate: onUpdateMock,- },-}))--const removeTrnsFromStoreMock = vi.fn()-vi.mock('~/components/trns/useTrnsStore', () => ({- useTrnsStore: () => ({- hasItems: false,- items: {},- removeTrnsFromStore: removeTrnsFromStoreMock,- }),-}))--const offlineHelpers = await import('~/components/offline/helpers')-vi.mock('~/components/offline/helpers', async (importOriginal) => {- const actual = await importOriginal() as any- return {- clearOfflineQueue: vi.fn(actual.clearOfflineQueue),- getAllOfflineOps: vi.fn(actual.getAllOfflineOps),- getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),- pushOfflineOp: vi.fn(actual.pushOfflineOp),- removeOfflineOp: vi.fn(actual.removeOfflineOp),- removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),- removeOfflineOps: vi.fn(actual.removeOfflineOps),- updateOfflineOpData: vi.fn(actual.updateOfflineOpData),- }-})+import { beforeEach, describe, expect, it, vi } from 'vitest'-const { useCategoriesStore } = await import('~/components/categories/useCategoriesStore')+import type { Categories, CategoryItem } from '~/components/categories/types'+import type { TrnItem } from '~/components/trns/types'-function makeCategory(overrides: Partial<CategoryItem> = {}): CategoryItem {+import { useCategoriesStore } from '~/components/categories/useCategoriesStore'+import { TrnType } from '~/components/trns/types'+import { useTrnsStore } from '~/components/trns/useTrnsStore'+import { toastAddMock } from '~/test-utils/setup-store'++const h = vi.hoisted(() => {+ const watchCallbacks: ((rows: any[]) => void)[] = []return {- color: '#f00',- icon: 'mdi:food',- name: 'Food',- parentId: 0,- showInLastUsed: true,- showInQuickSelector: false,- ...overrides,+ auth: { session: { value: null }, signOut: vi.fn(), uid: { value: 'u1' }, user: { value: null } },+ deleteRow: vi.fn(),+ demo: { value: false },+ upsertRow: vi.fn(),+ upsertRows: vi.fn(),+ watchCallbacks,+ watchTable: vi.fn((_sql: string, _params: unknown[], cb: (rows: any[]) => void) => {+ watchCallbacks.push(cb)+ return { abort: vi.fn() }+ }),}-}--describe('useCategoriesStore', () => {- beforeEach(async () => {- setActivePinia(createPinia())- await localforage.clear()- vi.clearAllMocks()- mutationMock.mockReturnValue(Promise.resolve())- actionMock.mockReturnValue(Promise.resolve())- })-- afterEach(() => {- vi.restoreAllMocks()- })-- describe('saveCategory — optimistic UI', () => {- it('updates items immediately', () => {- const store = useCategoriesStore()-- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })-- expect(store.items).toHaveProperty('c1')- expect(store.items.c1!.name).toBe('Food')- })-- it('pushes to offline queue immediately', () => {- const store = useCategoriesStore()-- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })-- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'categories', id: 'c1', type: 'create' }),- )- })-- it('fires Convex create mutation for new category', () => {- const store = useCategoriesStore()+})- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })+vi.mock('~~/services/powersync/db', () => ({ watchTable: h.watchTable }))+vi.mock('~~/services/powersync/mutations', () => ({ deleteRow: h.deleteRow, upsertRow: h.upsertRow, upsertRows: h.upsertRows }))+vi.mock('~/components/demo/useDemo', () => ({ useDemo: () => ({ isDemo: h.demo }) }))+vi.mock('~/composables/useSupabase', () => ({ useSupabase: () => ({}), useSupabaseAuth: () => h.auth }))- expect(mutationMock).toHaveBeenCalledWith(- 'categories.create',- expect.objectContaining({ color: '#f00', name: 'Food' }),- )- })+function category(over: Partial<CategoryItem> = {}): CategoryItem {+ return { color: '#111', icon: 'mdi:cat', name: 'Food', parentId: 0, showInLastUsed: true, showInQuickSelector: false, ...over }+}- it('fires Convex update mutation for existing category', () => {- const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }-- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory({ name: 'Food & Drinks' }),- })-- expect(mutationMock).toHaveBeenCalledWith(- 'categories.update',- expect.objectContaining({ id: 'c1', name: 'Food & Drinks' }),- )- })+// The store re-adds the synthetic transfer/adjustment entries on every+// setCategories, so seeding with a partial map (cast to Categories) is faithful.+function cats(map: Record<string, CategoryItem>): Categories {+ return map as Categories+}- it('cleans up offline queue on mutation success', async () => {- const store = useCategoriesStore()+function categoryRow(id: string, over: Record<string, unknown> = {}) {+ return { color: '#111', icon: 'mdi:cat', id, name: id, parentId: null, showInLastUsed: 1, showInQuickSelector: 0, updatedAt: 1, ...over }+}- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })+function expense(over: Partial<TrnItem> = {}): TrnItem {+ return { amount: 100, categoryId: 'c1', date: 1700000000000, type: TrnType.Expense, updatedAt: 1, walletId: 'w1', ...over } as TrnItem+}- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('categories', 'c1')- })- })+describe('useCategoriesStore', () => {+ beforeEach(() => {+ setActivePinia(createPinia())+ h.demo.value = false+ h.watchCallbacks.length = 0+ h.watchTable.mockClear()+ h.upsertRow.mockReset().mockResolvedValue(undefined)+ h.upsertRows.mockReset().mockResolvedValue(undefined)+ h.deleteRow.mockReset().mockResolvedValue(undefined)+ toastAddMock.mockClear()+ })- it('skips transfer category', () => {+ describe('hydration via watch', () => {+ it('keeps the synthetic adjustment/transfer entries and tracks hasItems', () => {const store = useCategoriesStore()+ expect(store.hasItems).toBe(false) // only synthetic entries present+ expect(store.items.adjustment).toBeDefined()+ expect(store.items.transfer).toBeDefined()- store.saveCategory({- id: 'transfer',- isUpdateChildCategoriesColor: false,- values: makeCategory({ name: 'Transfer' }),- })+ store.initCategories()+ expect(h.watchTable.mock.calls[0]?.[0]).toBe('SELECT * FROM categories')- expect(mutationMock).not.toHaveBeenCalled()- expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()- })+ h.watchCallbacks[0]!([categoryRow('c1'), categoryRow('c2')])+ expect(store.hasItems).toBe(true)+ expect(store.items.c1).toMatchObject({ icon: 'mdi:cat' })+ expect(store.items.adjustment).toBeDefined() // synthetic re-added- it('updates child colors when isUpdateChildCategoriesColor is true', () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),- child2: makeCategory({ color: '#f00', name: 'Child 2', parentId: 'parent1' }),- parent1: makeCategory({ color: '#f00', name: 'Parent' }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: true,- values: makeCategory({ color: '#00f', name: 'Parent' }),- })-- expect(store.items.child1!.color).toBe('#00f')- expect(store.items.child2!.color).toBe('#00f')- expect(store.items.parent1!.color).toBe('#00f')+ h.watchCallbacks[0]!([])+ expect(store.hasItems).toBe(false)+ expect(store.items.transfer).toBeDefined()})- it('fires updateWithChildren mutation when updating children color', () => {+ it('flips isLoaded on the first emission and resets it on re-subscribe', () => {const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),- parent1: makeCategory({ color: '#f00', name: 'Parent' }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: true,- values: makeCategory({ color: '#00f', name: 'Parent' }),- })-- expect(mutationMock).toHaveBeenCalledWith(- 'categories.updateWithChildren',- expect.objectContaining({ childIds: ['child1'], color: '#00f', id: 'parent1' }),- )- })+ expect(store.isLoaded).toBe(false)- it('computes children correctly after parentId change', () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- c1: makeCategory({ name: 'Child', parentId: 'oldParent' }),- newParent: makeCategory({ name: 'New Parent' }),- oldParent: makeCategory({ name: 'Old Parent' }),- }-- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory({ name: 'Child', parentId: 'newParent' }),- })-- expect(store.getChildrenIds('oldParent')).toEqual([])- expect(store.getChildrenIds('newParent')).toEqual(['c1'])- })+ store.initCategories()+ expect(store.isLoaded).toBe(false) // armed but no emission yet- it('shows toast on mutation failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- mutationMock.mockReturnValue(Promise.reject(new Error('Server error')))- const store = useCategoriesStore()+ h.watchCallbacks[0]!([]) // even an empty emission counts as hydrated+ expect(store.isLoaded).toBe(true)- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })-- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error' }),- )- })+ store.initCategories() // re-subscribe (e.g. a different user) waits again+ expect(store.isLoaded).toBe(false)})})- describe('saveCategory — create new parent with children', () => {- it('remaps children parentId from local to convex id after create resolves', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1', parentId: 'oldRoot' }),- child2: makeCategory({ name: 'Child 2' }),- oldRoot: makeCategory({ name: 'Old Root' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_xyz',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1', 'child2'],- values: makeCategory({ name: 'New Parent' }),- })-- expect(store.items.child1!.parentId).toBe('local_xyz')- expect(store.items.child2!.parentId).toBe('local_xyz')-- await vi.waitFor(() => {- expect(store.items.child1!.parentId).toBe('convex_new')- expect(store.items.child2!.parentId).toBe('convex_new')- })- })-- it('calls setChildren with convex parent id after create resolves', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_xyz',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1'],- values: makeCategory({ name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(mutationMock).toHaveBeenCalledWith(- 'categories.setChildren',- expect.objectContaining({- addIds: ['child1'],- id: 'convex_new',- removeIds: [],- }),- )- })- })-- it('filters local-id children from setChildren addIds', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1' }),- local_child: makeCategory({ name: 'Local Child' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_parent',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1', 'local_child'],- values: makeCategory({ name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(mutationMock).toHaveBeenCalledWith(- 'categories.setChildren',- expect.objectContaining({ addIds: ['child1'] }),- )- })- })-- it('passes childrenColor when isUpdateChildCategoriesColor is true', async () => {+ describe('saveCategory', () => {+ it('updates optimistically and upserts the touched row', async () => {const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#f00', name: 'Child 1' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_xyz',- isUpdateChildCategoriesColor: true,- nextChildIds: ['child1'],- values: makeCategory({ color: '#00f', name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(mutationMock).toHaveBeenCalledWith(- 'categories.setChildren',- expect.objectContaining({ childrenColor: '#00f' }),- )- })- })+ store.setCategories(cats({ c1: category() }))- it('rolls back children parentId and color when setChildren fails', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#aaa', name: 'Child 1', parentId: 'oldRoot' }),- oldRoot: makeCategory({ name: 'Old Root' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- if (path === 'categories.setChildren')- return Promise.reject(new Error('Server error'))- return Promise.resolve()- })-- store.saveCategory({- id: 'local_xyz',- isUpdateChildCategoriesColor: true,- nextChildIds: ['child1'],- values: makeCategory({ color: '#00f', name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(store.items.child1!.parentId).toBe('oldRoot')- expect(store.items.child1!.color).toBe('#aaa')- })- })+ await store.saveCategory({ id: 'c1', isUpdateChildCategoriesColor: false, values: category({ name: 'Renamed' }) })- it('skips setChildren when only local-id children selected', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- local_child: makeCategory({ name: 'Local Child' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_new')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_parent',- isUpdateChildCategoriesColor: false,- nextChildIds: ['local_child'],- values: makeCategory({ name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(mutationMock).toHaveBeenCalledWith('categories.create', expect.anything())- })- // Allow potential setChildren microtask to flush- await Promise.resolve()- expect(mutationMock).not.toHaveBeenCalledWith('categories.setChildren', expect.anything())+ expect(store.items.c1).toMatchObject({ name: 'Renamed' })+ expect(h.upsertRows).toHaveBeenCalledWith('categories', expect.arrayContaining([+ expect.objectContaining({ id: 'c1', row: expect.objectContaining({ name: 'Renamed', userId: 'u1' }) }),+ ]))})- })- describe('saveCategory — optimistic updatedAt', () => {- it('stamps updatedAt on the saved category', () => {- const before = Date.now()+ it('propagates color to kept children and upserts each touched row', async () => {const store = useCategoriesStore()+ store.setCategories(cats({ c1: category({ color: '#aaa' }), c2: category({ color: '#bbb', parentId: 'c1' }) }))- store.saveCategory({- id: 'c1',- isUpdateChildCategoriesColor: false,- values: makeCategory(),- })-- const after = Date.now()- const updatedAt = store.items.c1!.updatedAt- expect(updatedAt).toBeTypeOf('number')- expect(updatedAt!).toBeGreaterThanOrEqual(before)- expect(updatedAt!).toBeLessThanOrEqual(after)- })+ await store.saveCategory({ id: 'c1', isUpdateChildCategoriesColor: true, values: category({ color: '#fff' }) })- it('stamps updatedAt on color-propagated children', () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1', updatedAt: 1 }),- parent1: makeCategory({ color: '#f00', name: 'Parent', updatedAt: 1 }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: true,- values: makeCategory({ color: '#00f', name: 'Parent' }),- })-- expect(store.items.child1!.updatedAt!).toBeGreaterThan(1)+ expect(store.items.c1?.color).toBe('#fff')+ expect(store.items.c2?.color).toBe('#fff') // propagated to child+ const upsertedIds = h.upsertRows.mock.calls[0]![1].map((r: { id: string }) => r.id)+ expect(upsertedIds).toEqual(expect.arrayContaining(['c1', 'c2']))})- it('stamps updatedAt on reparented children', () => {+ it('rolls back and toasts when the write fails', async () => {const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1', parentId: 0, updatedAt: 1 }),- parent1: makeCategory({ name: 'Parent', updatedAt: 1 }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1'],- values: makeCategory({ name: 'Parent' }),- })-- expect(store.items.child1!.parentId).toBe('parent1')- expect(store.items.child1!.updatedAt!).toBeGreaterThan(1)- })+ store.setCategories(cats({ c1: category() }))+ const prev = store.items+ h.upsertRows.mockReset().mockRejectedValueOnce(new Error('boom'))- it('applyRealtimePatch ignores stale doc with older updatedAt after in-flight clears', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- c1: makeCategory({ name: 'Optimistic Name', updatedAt: 5000 }),- }-- // Skip in-flight protection: only updatedAt comparison is in play.- store.applyRealtimePatch({- deletedIds: [],- docs: [{- _creationTime: 0,- _id: 'c1',- color: '#f00',- icon: 'mdi:food',- name: 'Stale Server Name',- parentId: 0,- showInLastUsed: true,- showInQuickSelector: false,- updatedAt: 4000,- userId: 'u1',- }],- serverTime: Date.now(),- truncated: false,- })-- expect(store.items.c1!.name).toBe('Optimistic Name')- })- })+ await store.saveCategory({ id: 'c1', isUpdateChildCategoriesColor: false, values: category({ name: 'Renamed' }) })- describe('saveCategory — offline queue corrections (Phase 3)', () => {- it('3b: patches queued child update op parentId after parent remap', async () => {- const store = useCategoriesStore()- store.items = { ...store.items, child1: makeCategory({ name: 'Child 1' }) }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_p1')- return Promise.resolve()- })-- store.saveCategory({- id: 'local_p1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1'],- values: makeCategory({ name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(- 'categories',- 'child1',- { parentId: 'convex_p1' },- )- })+ // setCategories always re-wraps with the synthetic entries, so the rollback+ // restores content (not the exact reference).+ expect(store.items).toEqual(prev)+ expect(store.items.c1?.name).toBe('Food')+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('3c: queues per-kept-child color op for offline survival', () => {+ it('is a no-op for the synthetic transfer/adjustment ids', async () => {const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),- parent1: makeCategory({ color: '#f00', name: 'Parent' }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: true,- values: makeCategory({ color: '#00f', name: 'Parent' }),- })-- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({- data: expect.objectContaining({ color: '#00f' }),- entity: 'categories',- id: 'child1',- type: 'update',- }),- )- })+ store.setCategories(cats({ c1: category() }))- it('3d: setChildren rollback drains per-child reparent ops (existing parent)', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1', parentId: 0 }),- parent1: makeCategory({ name: 'Parent' }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.setChildren')- return Promise.reject(new Error('Server error'))- return Promise.resolve()- })-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1'],- values: makeCategory({ name: 'Parent' }),- })-- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOps).toHaveBeenCalledWith(- 'categories',- expect.arrayContaining(['child1']),- )- })- expect(store.items.child1!.parentId).toBe(0)- })+ await store.saveCategory({ id: 'transfer', isUpdateChildCategoriesColor: false, values: category() })+ await store.saveCategory({ id: 'adjustment', isUpdateChildCategoriesColor: false, values: category() })- it('3b/3d: existing-parent setChildren filters local-id children out of server call', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- local_child: makeCategory({ name: 'Local Child', parentId: 0 }),- parent1: makeCategory({ name: 'Parent' }),- server_child: makeCategory({ name: 'Server Child', parentId: 0 }),- }-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['server_child', 'local_child'],- values: makeCategory({ name: 'Parent' }),- })-- await vi.waitFor(() => {- expect(mutationMock).toHaveBeenCalledWith(- 'categories.setChildren',- expect.objectContaining({ addIds: ['server_child'] }),- )- })+ expect(h.upsertRows).not.toHaveBeenCalled()})- it('3d: existing-parent setChildren rollback patches local-child queued op parentId', async () => {+ it('does not touch PowerSync in demo mode', async () => {+ h.demo.value = trueconst store = useCategoriesStore()- store.items = {- ...store.items,- local_child: makeCategory({ name: 'Local Child', parentId: 0 }),- parent1: makeCategory({ name: 'Parent' }),- server_child: makeCategory({ name: 'Server Child', parentId: 0 }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.setChildren')- return Promise.reject(new Error('Server error'))- return Promise.resolve()- })-- store.saveCategory({- id: 'parent1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['server_child', 'local_child'],- values: makeCategory({ name: 'Parent' }),- })-- await vi.waitFor(() => {- expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(- 'categories',- 'local_child',- { parentId: 0 },- )- })- const removeCalls = (offlineHelpers.removeOfflineOps as any).mock.calls- const flatRemoved = removeCalls.flatMap((c: any[]) => c[1])- expect(flatRemoved).not.toContain('local_child')- })+ store.setCategories(cats({ c1: category() }))- it('3d: setChildren rollback in new-parent branch drains non-local + patches local children', async () => {- const store = useCategoriesStore()- store.items = {- ...store.items,- child1: makeCategory({ name: 'Child 1', parentId: 0 }),- local_child2: makeCategory({ name: 'Local Child', parentId: 0 }),- }-- mutationMock.mockImplementation((path: string) => {- if (path === 'categories.create')- return Promise.resolve('convex_p1')- if (path === 'categories.setChildren')- return Promise.reject(new Error('Server error'))- return Promise.resolve()- })-- store.saveCategory({- id: 'local_p1',- isUpdateChildCategoriesColor: false,- nextChildIds: ['child1', 'local_child2'],- values: makeCategory({ name: 'New Parent' }),- })-- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOps).toHaveBeenCalledWith(- 'categories',- expect.arrayContaining(['child1']),- )- })- // Non-local child purged, local child kept (its create op stays — patched to prev parentId).- const removeCalls = (offlineHelpers.removeOfflineOps as any).mock.calls- const flatRemoved = removeCalls.flatMap((c: any[]) => c[1])- expect(flatRemoved).not.toContain('local_child2')- expect(offlineHelpers.updateOfflineOpData).toHaveBeenCalledWith(- 'categories',- 'local_child2',- { parentId: 0 },- )+ await store.saveCategory({ id: 'c1', isUpdateChildCategoriesColor: false, values: category({ name: 'X' }) })+ expect(store.items.c1?.name).toBe('X')+ expect(h.upsertRows).not.toHaveBeenCalled()})})- describe('deleteCategory — optimistic UI', () => {- it('removes item from store immediately', () => {- const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory(), c2: makeCategory({ name: 'Transport' }) }-- store.deleteCategory('c1')-- expect(store.items).not.toHaveProperty('c1')- expect(store.items).toHaveProperty('c2')- // transfer should always remain- expect(store.items).toHaveProperty('transfer')- })-- it('pushes to offline queue', () => {+ describe('deleteCategory', () => {+ it('cascades: removes the category and its trns, deleting both in the DB', async () => {+ const trnsStore = useTrnsStore()+ trnsStore.setTrns({ t1: expense(), t2: expense({ categoryId: 'c2' }) })const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }+ store.setCategories(cats({ c1: category() }))- store.deleteCategory('c1')+ await store.deleteCategory('c1', ['t1'])- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'categories', id: 'c1', type: 'delete' }),- )+ expect(store.items.c1).toBeUndefined()+ expect(trnsStore.items?.t1).toBeUndefined()+ expect(trnsStore.items?.t2).toBeDefined()+ expect(h.deleteRow).toHaveBeenCalledWith('categories', 'c1')+ expect(h.deleteRow).toHaveBeenCalledWith('trns', 't1')})- it('only pushes category delete op (backend cascades trns)', () => {+ it('restores the category and cascaded trns when the write fails', async () => {+ const trnsStore = useTrnsStore()+ const seededTrns = { t1: expense() }+ trnsStore.setTrns(seededTrns)const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }+ store.setCategories(cats({ c1: category() }))+ const prev = store.items+ h.deleteRow.mockReset().mockRejectedValueOnce(new Error('boom'))- store.deleteCategory('c1', ['trn1', 'trn2'])+ await store.deleteCategory('c1', ['t1'])- // Only category delete op — no explicit trns delete ops- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledTimes(1)- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'categories', id: 'c1', type: 'delete' }),- )+ expect(store.items).toEqual(prev) // re-wrapped with synthetic entries+ expect(store.items.c1).toBeDefined()+ expect(trnsStore.items).toBe(seededTrns)+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('removes trns from store immediately (optimistic)', () => {+ it('is a no-op for the synthetic adjustment id', async () => {const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }-- store.deleteCategory('c1', ['trn1', 'trn2'])+ store.setCategories(cats({ c1: category() }))- expect(removeTrnsFromStoreMock).toHaveBeenCalledWith(['trn1', 'trn2'])+ await store.deleteCategory('adjustment')+ expect(h.deleteRow).not.toHaveBeenCalled()})+ })- it('fires Convex remove mutation', () => {+ describe('children-map (hasChildren / getChildrenIds)', () => {+ it('returns a root\'s children, sorted by name', () => {const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }-- store.deleteCategory('c1')+ store.setCategories(cats({+ c1: category({ name: 'Root' }),+ c2: category({ name: 'Banana', parentId: 'c1' }),+ c3: category({ name: 'Apple', parentId: 'c1' }),+ }))- expect(actionMock).toHaveBeenCalledWith('categories.remove', { id: 'c1' })+ expect(store.hasChildren('c1')).toBe(true)+ expect(store.getChildrenIds('c1')).toEqual(['c3', 'c2']) // Apple before Banana})- it('cleans up offline queue on mutation success', async () => {+ it('reports no children for a leaf, a childless root, or an unknown id', () => {const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }-- store.deleteCategory('c1')+ store.setCategories(cats({+ c1: category({ name: 'Root' }),+ c2: category({ name: 'Child', parentId: 'c1' }),+ c9: category({ name: 'Lonely' }),+ }))- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('categories', 'c1')- })+ expect(store.hasChildren('c2')).toBe(false) // a child is never a parent (parentId !== 0 guard)+ expect(store.getChildrenIds('c2')).toEqual([])+ expect(store.hasChildren('c9')).toBe(false) // root with no children+ expect(store.hasChildren('nope')).toBe(false)+ expect(store.getChildrenIds('nope')).toEqual([])})- it('skips transfer category', () => {+ it('never treats synthetic transfer/adjustment as children', () => {const store = useCategoriesStore()+ store.setCategories(cats({ c1: category(), c2: category({ parentId: 'c1' }) }))- store.deleteCategory('transfer')-- expect(actionMock).not.toHaveBeenCalled()- expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()+ // synthetic entries have parentId 0, so they group under no real parent+ expect(store.getChildrenIds('transfer')).toEqual([])+ expect(store.getChildrenIds('adjustment')).toEqual([])+ expect(store.getChildrenIds('c1')).not.toContain('transfer')+ expect(store.getChildrenIds('c1')).not.toContain('adjustment')})- it('shows toast on failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- actionMock.mockReturnValue(Promise.reject(new Error('Server error')))+ it('recomputes when a child is added or removed', () => {const store = useCategoriesStore()- store.items = { ...store.items, c1: makeCategory() }+ store.setCategories(cats({ c1: category({ name: 'Root' }) }))+ expect(store.hasChildren('c1')).toBe(false)- store.deleteCategory('c1')+ store.setCategories(cats({+ c1: category({ name: 'Root' }),+ c2: category({ name: 'Child', parentId: 'c1' }),+ }))+ expect(store.hasChildren('c1')).toBe(true)+ expect(store.getChildrenIds('c1')).toEqual(['c2'])- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error' }),- )- })+ store.setCategories(cats({ c1: category({ name: 'Root' }) }))+ expect(store.hasChildren('c1')).toBe(false)+ expect(store.getChildrenIds('c1')).toEqual([])})- it('parent has no deleted child in getChildrenIds', () => {+ it('returns a fresh array that callers cannot mutate', () => {const store = useCategoriesStore()- store.items = {- ...store.items,- c1: makeCategory({ name: 'Child 1', parentId: 'parent1' }),- c2: makeCategory({ name: 'Child 2', parentId: 'parent1' }),- parent1: makeCategory({ name: 'Parent' }),- }-- store.deleteCategory('c1')+ store.setCategories(cats({ c1: category(), c2: category({ parentId: 'c1' }) }))- expect(store.getChildrenIds('parent1')).toEqual(['c2'])+ const first = store.getChildrenIds('c1')+ first.push('mutated')+ expect(store.getChildrenIds('c1')).toEqual(['c2']) // cache untouched})})})diff --git a/app/app/components/stat/chart/useCategorySeriesBuilder.test.ts b/app/app/components/stat/chart/useCategorySeriesBuilder.test.tsnew file mode 100644index 00000000..00e5e441--- /dev/null+++ b/app/app/components/stat/chart/useCategorySeriesBuilder.test.ts@@ -0,0 +1,180 @@+import { describe, expect, it } from 'vitest'++import type { Categories, CategoryId } from '~/components/categories/types'+import type { IntervalData } from '~/components/stat/types'+import type { TrnId, TrnItem } from '~/components/trns/types'++import {+ aggregateCategoryTotals,+ buildCategoriesPieData,+ buildCategoriesSeries,+ OTHER_SLICE_ID,+} from '~/components/stat/chart/useCategorySeriesBuilder'++// Each trn maps 1:1 to a category with a fixed expense amount.+const amounts: Record<TrnId, number> = {+ t01: 100,+ t02: 90,+ t03: 80,+ t04: 70,+ t05: 60,+ t06: 50,+ t07: 40,+ t08: 30,+ t09: 20,+ t10: 10,+ tTransfer: 999,+}++const trnsItems: Record<TrnId, Pick<TrnItem, 'categoryId'>> = {+ t01: { categoryId: 'c01' },+ t02: { categoryId: 'c02' },+ t03: { categoryId: 'c03' },+ t04: { categoryId: 'c04' },+ t05: { categoryId: 'c05' },+ t06: { categoryId: 'c06' },+ t07: { categoryId: 'c07' },+ t08: { categoryId: 'c08' },+ t09: { categoryId: 'c09' },+ t10: { categoryId: 'c10' },+ tTransfer: { categoryId: 'transfer' },+}++const categoriesItems: Categories = Object.fromEntries(+ Array.from({ length: 10 }, (_, i) => {+ const id = `c${String(i + 1).padStart(2, '0')}`+ return [id, { color: `#00000${i}`, name: `Cat ${i + 1}` }]+ }),+) as unknown as Categories++function computeTotalForTrnsIds(ids: TrnId[]) {+ const expense = ids.reduce((acc, id) => acc + (amounts[id] ?? 0), 0)+ return { expense, income: 0, sum: -expense }+}++/** All non-transfer trns inside a single interval. */+function singleInterval(trnIds: TrnId[]): IntervalData[] {+ return [{+ range: { end: 1, start: 0 },+ total: {+ adjustment: 0,+ expense: 0,+ expenseTransfers: 0,+ income: 0,+ incomeTransfers: 0,+ sum: 0,+ sumTransfers: 0,+ },+ trnsIds: trnIds,+ }]+}++const baseParams = {+ categoriesItems,+ computeTotalForTrnsIds,+ isGrouped: false,+ trnsItems,+ type: 'expense' as const,+}++const allTrnIds: TrnId[] = Object.keys(amounts)++describe('aggregateCategoryTotals', () => {+ it('sorts categories by total descending and excludes transfers', () => {+ const { categoryTotals, orderedCategoryIds } = aggregateCategoryTotals({+ ...baseParams,+ intervals: singleInterval(allTrnIds),+ })++ expect(orderedCategoryIds).toEqual([+ 'c01',+ 'c02',+ 'c03',+ 'c04',+ 'c05',+ 'c06',+ 'c07',+ 'c08',+ 'c09',+ 'c10',+ ])+ expect(orderedCategoryIds).not.toContain('transfer')+ expect(categoryTotals.c01).toBe(100)+ expect(categoryTotals.transfer).toBeUndefined()+ })+})++describe('buildCategoriesPieData', () => {+ it('keeps top-N slices and rolls the rest into a single Other slice', () => {+ const pie = buildCategoriesPieData({+ ...baseParams,+ intervals: singleInterval(allTrnIds),+ topN: 8,+ }, 'Other')++ expect(pie).toHaveLength(9)+ expect(pie.slice(0, 8).map(s => s.id)).toEqual([+ 'c01',+ 'c02',+ 'c03',+ 'c04',+ 'c05',+ 'c06',+ 'c07',+ 'c08',+ ])++ const other = pie.at(-1)!+ expect(other.id).toBe(OTHER_SLICE_ID)+ expect(other.isOther).toBe(true)+ expect(other.name).toBe('Other')+ expect(other.value).toBe(30) // c09 (20) + c10 (10)+ })++ it('omits the Other slice when categories fit within top-N', () => {+ const pie = buildCategoriesPieData({+ ...baseParams,+ intervals: singleInterval(['t01', 't02', 't03']),+ topN: 8,+ }, 'Other')++ expect(pie).toHaveLength(3)+ expect(pie.some(s => s.isOther)).toBe(false)+ })++ it('uses the category color and name for each slice', () => {+ const pie = buildCategoriesPieData({+ ...baseParams,+ intervals: singleInterval(['t01']),+ topN: 8,+ }, 'Other')++ expect(pie[0]).toMatchObject({ color: '#000000', id: 'c01', name: 'Cat 1', value: 100 })+ })++ it('matches the bar series totals (single source of truth)', () => {+ const intervals = singleInterval(allTrnIds)++ const series = buildCategoriesSeries({ ...baseParams, chartType: 'bar', intervals })+ const barTotal = series.reduce(+ (acc, s) => acc + s.data.reduce((a, v) => a + v, 0),+ 0,+ )++ const pie = buildCategoriesPieData({ ...baseParams, intervals, topN: 8 }, 'Other')+ const pieTotal = pie.reduce((acc, s) => acc + s.value, 0)++ expect(pieTotal).toBe(barTotal)+ })++ it('respects the category filter', () => {+ const pie = buildCategoriesPieData({+ ...baseParams,+ filterCategoriesIds: ['c01', 'c02'] as CategoryId[],+ intervals: singleInterval(allTrnIds),+ topN: 8,+ }, 'Other')++ expect(pie.map(s => s.id)).toEqual(['c01', 'c02'])+ })+})diff --git a/app/app/components/stat/statConfig.test.ts b/app/app/components/stat/statConfig.test.tsindex 5d675c26..3764f1bd 100644--- a/app/app/components/stat/statConfig.test.ts+++ b/app/app/components/stat/statConfig.test.ts@@ -48,6 +48,7 @@ const defaultConfig: MiniItemConfig = {wallets: {count: 6,isShow: false,+ isShowIcon: true,},}diff --git a/app/app/components/trns/reconcile.test.ts b/app/app/components/trns/reconcile.test.tsnew file mode 100644index 00000000..5f80b966--- /dev/null+++ b/app/app/components/trns/reconcile.test.ts@@ -0,0 +1,79 @@+import type { Row } from '~~/services/powersync/transforms'++import { describe, expect, it } from 'vitest'++import { reconcileTrns, rowsToTrns } from '~/components/trns/reconcile'++function expenseRow(id: string, updatedAt: number | null, amount = 100): Row {+ return {+ amount,+ categoryId: 'food',+ date: 1700000000000,+ id,+ type: 0,+ updatedAt,+ walletId: 'cash',+ }+}++describe('rowsToTrns', () => {+ it('returns null for an empty snapshot', () => {+ expect(rowsToTrns([])).toBeNull()+ })++ it('builds a map keyed by id', () => {+ const map = rowsToTrns([expenseRow('a', 1), expenseRow('b', 2)])+ expect(Object.keys(map ?? {})).toEqual(['a', 'b'])+ expect(map?.a).toMatchObject({ amount: 100 })+ })+})++describe('reconcileTrns', () => {+ it('suppresses the echo: returns the same reference when nothing changed', () => {+ const rows = [expenseRow('a', 1), expenseRow('b', 2)]+ const prev = rowsToTrns(rows)!+ // A fresh, content-identical snapshot (e.g. the watch echo of our own write).+ const next = reconcileTrns(prev, [expenseRow('a', 1), expenseRow('b', 2)])+ expect(next).toBe(prev)+ })++ it('reuses unchanged item objects and only rebuilds changed rows', () => {+ const prev = rowsToTrns([expenseRow('a', 1), expenseRow('b', 2)])!+ const next = reconcileTrns(prev, [expenseRow('a', 1), expenseRow('b', 3, 999)])++ expect(next).not.toBe(prev)+ expect(next?.a).toBe(prev.a) // unchanged -> same reference, no rowToTrn+ expect(next?.b).not.toBe(prev.b) // changed -> rebuilt+ expect(next?.b).toMatchObject({ amount: 999, updatedAt: 3 })+ })++ it('handles an added row, reusing existing ones', () => {+ const prev = rowsToTrns([expenseRow('a', 1)])!+ const next = reconcileTrns(prev, [expenseRow('a', 1), expenseRow('b', 2)])++ expect(next).not.toBe(prev)+ expect(next?.a).toBe(prev.a)+ expect(Object.keys(next ?? {})).toEqual(['a', 'b'])+ })++ it('handles a removed row', () => {+ const prev = rowsToTrns([expenseRow('a', 1), expenseRow('b', 2)])!+ const next = reconcileTrns(prev, [expenseRow('a', 1)])++ expect(next).not.toBe(prev)+ expect(next?.a).toBe(prev.a)+ expect(next?.b).toBeUndefined()+ })++ it('returns null when all rows are removed', () => {+ const prev = rowsToTrns([expenseRow('a', 1)])!+ expect(reconcileTrns(prev, [])).toBeNull()+ })++ it('suppresses rows with a null updatedAt (read deterministically as 0)', () => {+ const prev = rowsToTrns([expenseRow('a', null)])!+ // null updatedAt reads back as a stable 0 (transforms.ts), so it matches.+ const next = reconcileTrns(prev, [expenseRow('a', null)])+ expect(next).toBe(prev)+ })+})diff --git a/app/app/components/trns/useTrnsStore.test.ts b/app/app/components/trns/useTrnsStore.test.tsindex a72e0e1e..098a5dad 100644--- a/app/app/components/trns/useTrnsStore.test.ts+++ b/app/app/components/trns/useTrnsStore.test.ts@@ -1,571 +1,179 @@-import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'--import type { Transaction, Transfer } from '~/components/trns/types'--import { isTransfer } from '~/components/trns/types'--// --- Entity-specific mocks -----vi.mock('~~/services/convex/api', () => ({- convexTrnsToMap: (arr: any[]) => {- const map: Record<string, any> = {}- for (const item of arr) {- const { _id, ...rest } = item- map[_id] = rest- }- return map- },-}))--const mutationMock = vi.fn(() => Promise.resolve())-const queryMock = vi.fn<(...args: any[]) => Promise<any>>(() => Promise.resolve(null))-const onUpdateMock = vi.fn()--vi.stubGlobal('useConvexClientWithApi', () => ({- api: {- trns: { create: 'trns.create', delta: 'trns.delta', ensureSyncMeta: 'trns.ensureSyncMeta', idsHash: 'trns.idsHash', list: 'trns.list', remove: 'trns.remove', update: 'trns.update' },- },- client: {- mutation: mutationMock,- onUpdate: onUpdateMock,- query: queryMock,- },-}))--vi.mock('~/components/categories/useCategoriesStore', () => ({- useCategoriesStore: () => ({- getTransactibleIds: (ids: any) => ids,- items: { food: { color: '#f00', icon: 'mdi:food', name: 'Food', parentId: 0, showInLastUsed: true, showInQuickSelector: true }, transfer: { color: '#000', icon: 'mdi:repeat', name: 'Transfer', parentId: 0, showInLastUsed: false, showInQuickSelector: false } },- }),-}))--vi.mock('~/components/wallets/useWalletsStore', () => ({- useWalletsStore: () => ({- items: { wallet1: { color: '#0f0', currency: 'USD', desc: '', isArchived: false, isExcludeInTotal: false, isWithdrawal: false, name: 'Cash', order: 0, type: 'cash', updatedAt: 0 } },- }),-}))--const offlineHelpers = await import('~/components/offline/helpers')-vi.mock('~/components/offline/helpers', async (importOriginal) => {- const actual = await importOriginal() as typeof import('~/components/offline/helpers')+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { TrnItem } from '~/components/trns/types'++import { TrnType } from '~/components/trns/types'+import { useTrnsStore } from '~/components/trns/useTrnsStore'+import { toastAddMock } from '~/test-utils/setup-store'++// Mock the PowerSync data layer so the store talks to a controllable fake:+// `watchTable` captures its callback (to drive hydration), the mutations record+// calls and let us force rejections (to test optimistic rollback), `useDemo`+// flips real/demo mode, and `useSupabaseAuth` supplies a stable uid.+const h = vi.hoisted(() => {+ const watchCallbacks: ((rows: any[]) => void)[] = []return {- clearOfflineQueue: vi.fn(actual.clearOfflineQueue),- getAllOfflineOps: vi.fn(actual.getAllOfflineOps),- getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),- pushOfflineOp: vi.fn(actual.pushOfflineOp),- removeOfflineOp: vi.fn(actual.removeOfflineOp),- removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),- removeOfflineOps: vi.fn(actual.removeOfflineOps),+ auth: { session: { value: null }, signOut: vi.fn(), uid: { value: 'u1' }, user: { value: null } },+ deleteRow: vi.fn(),+ demo: { value: false },+ upsertRow: vi.fn(),+ upsertRows: vi.fn(),+ watchCallbacks,+ watchTable: vi.fn((_sql: string, _params: unknown[], cb: (rows: any[]) => void) => {+ watchCallbacks.push(cb)+ return { abort: vi.fn() }+ }),}})-const { useTrnsStore } = await import('~/components/trns/useTrnsStore')+vi.mock('~~/services/powersync/db', () => ({ watchTable: h.watchTable }))+vi.mock('~~/services/powersync/mutations', () => ({ deleteRow: h.deleteRow, upsertRow: h.upsertRow, upsertRows: h.upsertRows }))+vi.mock('~/components/demo/useDemo', () => ({ useDemo: () => ({ isDemo: h.demo }) }))+vi.mock('~/composables/useSupabase', () => ({ useSupabase: () => ({}), useSupabaseAuth: () => h.auth }))-// --- Helpers ---+const tick = () => new Promise<void>(resolve => setTimeout(resolve, 0))-function makeTrn(overrides: Partial<Transaction> = {}): Transaction {- return {- amount: 100,- categoryId: 'food',- date: 1700000000000,- type: 0,- updatedAt: 1700000000000,- walletId: 'wallet1',- ...overrides,- }+function expense(over: Partial<TrnItem> = {}): TrnItem {+ return { amount: 100, categoryId: 'food', date: 1700000000000, type: TrnType.Expense, updatedAt: 1, walletId: 'cash', ...over } as TrnItem}-function makeTransfer(overrides: Partial<Transfer> = {}): Transfer {- return {- categoryId: 'transfer',- date: 1700000000000,- expenseAmount: 100,- expenseWalletId: 'wallet1',- incomeAmount: 100,- incomeWalletId: 'wallet1',- type: 2,- updatedAt: 1700000000000,- ...overrides,- }+function expenseRow(id: string, updatedAt: number, amount = 100) {+ return { amount, categoryId: 'food', date: 1700000000000, id, type: 0, updatedAt, walletId: 'cash' }}-// --- Tests ----describe('useTrnsStore', () => {- beforeEach(async () => {+ beforeEach(() => {setActivePinia(createPinia())- await localforage.clear()- vi.clearAllMocks()- mutationMock.mockReturnValue(Promise.resolve())- })-- afterEach(() => {- vi.restoreAllMocks()- })-- describe('saveTrn — optimistic UI', () => {- it('updates items immediately', () => {- const store = useTrnsStore()- store.items = {}-- const trn = makeTrn()- store.saveTrn({ id: 'trn1', values: trn })-- expect(store.items).toHaveProperty('trn1')- const trn1 = store.items!.trn1!- expect(trn1.type).not.toBe(2)- if (trn1.type !== 2)- expect(trn1.amount).toBe(100)- })-- it('pushes to offline queue immediately', () => {- const store = useTrnsStore()- store.items = {}-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'trns', id: 'trn1', type: 'create' }),- )- })-- it('fires Convex create mutation for new trn', () => {- const store = useTrnsStore()- store.items = {}-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- expect(mutationMock).toHaveBeenCalledWith(- 'trns.create',- expect.objectContaining({ amount: 100, type: 0 }),- )- })-- it('fires Convex update mutation for existing trn', () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn() }-- store.saveTrn({ id: 'trn1', values: makeTrn({ amount: 200 }) })-- expect(mutationMock).toHaveBeenCalledWith(- 'trns.update',- expect.objectContaining({ amount: 200, id: 'trn1' }),- )- })-- it('cleans up offline queue on mutation success', async () => {- const store = useTrnsStore()- store.items = {}-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('trns', 'trn1')- })- })-- it('keeps offline queue when mutation fails', async () => {- mutationMock.mockReturnValue(new Promise(() => {}))-- const store = useTrnsStore()- store.items = {}-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- await new Promise(r => setTimeout(r, 10))-- expect(offlineHelpers.removeOfflineOp).not.toHaveBeenCalled()- })-- it('adds updatedAt timestamp', () => {- const store = useTrnsStore()- store.items = {}- const before = Date.now()-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- expect(store.items!.trn1!.updatedAt).toBeGreaterThanOrEqual(before)- })-- it('shows toast on mutation failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- mutationMock.mockReturnValue(Promise.reject(new Error('network')))-- const store = useTrnsStore()- store.items = {}-- store.saveTrn({ id: 'trn1', values: makeTrn() })-- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error', description: 'trns.errors.saveFailed' }),- )- })- })+ h.demo.value = false+ h.watchCallbacks.length = 0+ h.watchTable.mockClear()+ h.upsertRow.mockReset().mockResolvedValue(undefined)+ h.deleteRow.mockReset().mockResolvedValue(undefined)+ toastAddMock.mockClear()})- describe('deleteTrn — optimistic UI', () => {- it('removes item from store immediately', () => {+ describe('hydration via watch', () => {+ it('subscribes to the trns table and builds items from row snapshots', () => {const store = useTrnsStore()- store.items = { trn1: makeTrn(), trn2: makeTrn() }+ store.initTrns()- store.deleteTrn('trn1')+ expect(h.watchTable).toHaveBeenCalledTimes(1)+ expect(h.watchTable.mock.calls[0]?.[0]).toBe('SELECT * FROM trns')- expect(store.items).not.toHaveProperty('trn1')- expect(store.items).toHaveProperty('trn2')- })+ const emit = h.watchCallbacks[0]!+ emit([expenseRow('a', 1), expenseRow('b', 2)])- it('pushes to offline queue', () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn() }-- store.deleteTrn('trn1')-- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'trns', id: 'trn1', type: 'delete' }),- )+ expect(Object.keys(store.items ?? {})).toEqual(['a', 'b'])+ expect(store.items?.a).toMatchObject({ amount: 100, categoryId: 'food', type: 0 })})- it('fires Convex remove mutation', () => {+ it('sets items to null when the snapshot empties', () => {const store = useTrnsStore()- store.items = { trn1: makeTrn() }+ store.initTrns()+ const emit = h.watchCallbacks[0]!- store.deleteTrn('trn1')+ emit([expenseRow('a', 1)])+ expect(store.items?.a).toBeDefined()- expect(mutationMock).toHaveBeenCalledWith('trns.remove', { id: 'trn1' })+ emit([])+ expect(store.items).toBeNull()})- it('cleans up offline queue on mutation success', async () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn() }-- store.deleteTrn('trn1')-- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('trns', 'trn1')- })+ it('does not subscribe in demo mode', () => {+ h.demo.value = true+ useTrnsStore().initTrns()+ expect(h.watchTable).not.toHaveBeenCalled()})- it('shows toast on mutation failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- mutationMock.mockReturnValue(Promise.reject(new Error('network')))-+ it('flips isLoaded on the first emission and resets it on re-subscribe', () => {const store = useTrnsStore()- store.items = { trn1: makeTrn() }+ expect(store.isLoaded).toBe(false)- store.deleteTrn('trn1')+ store.initTrns()+ expect(store.isLoaded).toBe(false) // armed but no emission yet- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error', description: 'trns.errors.deleteFailed' }),- )- })- })- })+ h.watchCallbacks[0]!([]) // even an empty emission counts as hydrated+ expect(store.isLoaded).toBe(true)- describe('removeTrnsFromStore', () => {- it('removes trns from store without mutations or queue', () => {- const store = useTrnsStore()- store.items = {- trn1: makeTrn(),- trn2: makeTrn(),- trn3: makeTrn(),- }-- store.removeTrnsFromStore(['trn1', 'trn3'])-- expect(store.items).not.toHaveProperty('trn1')- expect(store.items).toHaveProperty('trn2')- expect(store.items).not.toHaveProperty('trn3')- expect(mutationMock).not.toHaveBeenCalled()- expect(offlineHelpers.pushOfflineOp).not.toHaveBeenCalled()+ store.initTrns() // re-subscribe (e.g. a different user) waits again+ expect(store.isLoaded).toBe(false)})})- describe('initTrns — sync flow', () => {- it('performs full sync when no cached data', async () => {- queryMock.mockImplementation((queryName: string) => {- if (queryName === 'trns.list')- return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })- return Promise.resolve(null)- })-+ describe('saveTrn', () => {+ it('applies the optimistic update synchronously and upserts the row', async () => {const store = useTrnsStore()- await store.initTrns()-- expect(store.items).toHaveProperty('trn1')- const syncMeta = await localforage.getItem<any>('finapp.trns.syncMeta')- expect(syncMeta).toHaveProperty('idsHash')- expect(syncMeta.idsHash).toBeTruthy()- expect(syncMeta).not.toHaveProperty('serverIds')- })-- it('performs full sync with multiple pages', async () => {- let callCount = 0- queryMock.mockImplementation((queryName: string) => {- if (queryName === 'trns.list') {- callCount++- if (callCount === 1) {- return Promise.resolve({ continueCursor: 'cursor1', isDone: false, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })- }- return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn2', amount: 200, categoryId: 'food', date: 1700000001000, type: 0, updatedAt: 1700000001000, walletId: 'wallet1' }] })- }- return Promise.resolve(null)- })+ store.saveTrn({ id: 't1', values: expense() })- const store = useTrnsStore()- await store.initTrns()+ expect(store.items?.t1).toMatchObject({ amount: 100, categoryId: 'food' })+ expect(store.items?.t1?.updatedAt).toEqual(expect.any(Number))- expect(store.items).toHaveProperty('trn1')- expect(store.items).toHaveProperty('trn2')+ await tick()+ expect(h.upsertRow).toHaveBeenCalledWith('trns', 't1', expect.objectContaining({ amount: 100, userId: 'u1' }))})- it('performs delta sync with hash match (no deletion check)', async () => {- const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')- const hash = computeHash(['trn1'])- await localforage.setItem('finapp.trns', { trn1: makeTrn() })- await localforage.setItem('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })-- queryMock.mockImplementation((queryName: string) => {- if (queryName === 'trns.delta')- return Promise.resolve({ continueCursor: '', isDone: true, page: [] })- if (queryName === 'trns.idsHash')- return Promise.resolve({ hash, serverTime: 1700000002000 })- return Promise.resolve(null)- })-+ it('rolls back to the previous items and toasts when the write fails', async () => {const store = useTrnsStore()- await store.initTrns()-- expect(store.items).toHaveProperty('trn1')- })-- it('performs delta sync with hash mismatch (falls back to fullSync)', async () => {- await localforage.setItem('finapp.trns', { trn1: makeTrn(), trn2: makeTrn() })- await localforage.setItem('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })+ const prev = store.items // null on a fresh store+ h.upsertRow.mockReset().mockRejectedValueOnce(new Error('boom'))- queryMock.mockImplementation((queryName: string) => {- if (queryName === 'trns.delta')- return Promise.resolve({ continueCursor: '', isDone: true, page: [] })- if (queryName === 'trns.idsHash')- return Promise.resolve({ hash: 'new_hash', serverTime: 1700000002000 })- if (queryName === 'trns.list')- return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 100, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000000000, walletId: 'wallet1' }] })- return Promise.resolve(null)- })-- const store = useTrnsStore()- await store.initTrns()+ store.saveTrn({ id: 't1', values: expense() })+ expect(store.items?.t1).toBeDefined() // optimistic write landed first- expect(store.items).toHaveProperty('trn1')- expect(store.items).not.toHaveProperty('trn2')+ await tick()+ expect(store.items).toBe(prev) // restored to the exact previous reference+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('applies delta changes and updates hash', async () => {- const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')- const hash = computeHash(['trn1'])- await localforage.setItem('finapp.trns', { trn1: makeTrn({ amount: 100 }) })- await localforage.setItem('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })-- queryMock.mockImplementation((queryName: string) => {- if (queryName === 'trns.delta')- return Promise.resolve({ continueCursor: '', isDone: true, page: [{ _id: 'trn1', amount: 200, categoryId: 'food', date: 1700000000000, type: 0, updatedAt: 1700000001000, walletId: 'wallet1' }] })- if (queryName === 'trns.idsHash')- return Promise.resolve({ hash, serverTime: 1700000002000 })- return Promise.resolve(null)- })-+ it('does not touch PowerSync in demo mode', async () => {+ h.demo.value = trueconst store = useTrnsStore()- await store.initTrns()+ store.saveTrn({ id: 't1', values: expense() })- const trn1 = store.items!.trn1!- expect(trn1.type).not.toBe(2)- if (trn1.type !== 2)- expect(trn1.amount).toBe(200)- })-- it('clears store when user has no trns (idsHash returns null)', async () => {- await localforage.setItem('finapp.trns', { trn1: makeTrn() })- await localforage.setItem('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })-- queryMock.mockImplementation(() => Promise.resolve(null))-- const store = useTrnsStore()- await store.initTrns()-- expect(store.items).toBeNull()+ expect(store.items?.t1).toBeDefined()+ await tick()+ expect(h.upsertRow).not.toHaveBeenCalled()})})- describe('computeTrnItem', () => {- it('returns null when store not loaded', () => {- const store = useTrnsStore()- store.items = null-- expect(store.computeTrnItem('trn1')).toBeNull()- })-- it('returns null when trn not found', () => {- const store = useTrnsStore()- store.items = {}-- expect(store.computeTrnItem('nonexistent')).toBeNull()- })-- it('returns null when category not found', () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn({ categoryId: 'nonexistent' }) }-- expect(store.computeTrnItem('trn1')).toBeNull()- })-- it('returns null when wallet not found', () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn({ walletId: 'nonexistent' }) }-- expect(store.computeTrnItem('trn1')).toBeNull()- })-- it('returns full item for regular transaction', () => {- const store = useTrnsStore()- store.items = { trn1: makeTrn() }-- const result = store.computeTrnItem('trn1')- expect(result).not.toBeNull()- expect(result!.id).toBe('trn1')- expect(result!.category).toEqual(expect.objectContaining({ name: 'Food' }))- expect(result!.type).not.toBe(2)- if (result!.type !== 2)- expect(result!.wallet).toEqual(expect.objectContaining({ name: 'Cash' }))- })-- it('returns full item for transfer', () => {- const store = useTrnsStore()- store.items = {- trn1: makeTransfer(),- }-- const result = store.computeTrnItem('trn1')- expect(result).not.toBeNull()- expect(result!.id).toBe('trn1')- expect(result!.type).toBe(2)- if (result!.type === 2) {- expect(result!.expenseWallet).toEqual(expect.objectContaining({ name: 'Cash' }))- expect(result!.incomeWallet).toEqual(expect.objectContaining({ name: 'Cash' }))- }- })-- it('returns null when transfer expense wallet missing', () => {+ describe('deleteTrn', () => {+ it('removes the trn optimistically and deletes the row', async () => {const store = useTrnsStore()- store.items = {- trn1: makeTransfer({ expenseWalletId: 'nonexistent' }),- }+ store.setTrns({ t1: expense(), t2: expense() })- expect(store.computeTrnItem('trn1')).toBeNull()- })-- it('returns null when transfer income wallet missing', () => {- const store = useTrnsStore()- store.items = {- trn1: makeTransfer({ incomeWalletId: 'nonexistent' }),- }-- expect(store.computeTrnItem('trn1')).toBeNull()- })- })-- describe('applyRealtimePatch', () => {- it('adds new docs from delta', async () => {- const store = useTrnsStore()- store.items = {}-- await store.applyRealtimePatch({- deletedIds: [],- docs: [{- _creationTime: 0,- _id: 't1',- amount: 100,- categoryId: 'food',- date: 1,- type: 0,- updatedAt: 10,- userId: 'u',- walletId: 'wallet1',- }],- serverTime: 100,- truncated: false,- })-- expect(store.items?.t1).toMatchObject({ amount: 100, updatedAt: 10 })- })+ store.deleteTrn('t1')+ expect(store.items?.t1).toBeUndefined()+ expect(store.items?.t2).toBeDefined()- it('skips docs with stale updatedAt', async () => {- const store = useTrnsStore()- store.items = { t1: makeTrn({ amount: 200, updatedAt: 50 }) }-- await store.applyRealtimePatch({- deletedIds: [],- docs: [{- _creationTime: 0,- _id: 't1',- amount: 999,- categoryId: 'food',- date: 1,- type: 0,- updatedAt: 20,- userId: 'u',- walletId: 'wallet1',- }],- serverTime: 100,- truncated: false,- })-- const t1 = store.items?.t1- expect(isTransfer(t1) ? undefined : t1?.amount).toBe(200)+ await tick()+ expect(h.deleteRow).toHaveBeenCalledWith('trns', 't1')})- it('removes docs in deletedIds', async () => {+ it('restores the deleted trn and toasts when the write fails', async () => {const store = useTrnsStore()- store.items = { t1: makeTrn(), t2: makeTrn() }+ const seeded = { t1: expense() }+ store.setTrns(seeded)+ const prev = store.items+ h.deleteRow.mockReset().mockRejectedValueOnce(new Error('boom'))- await store.applyRealtimePatch({- deletedIds: ['t1'],- docs: [],- serverTime: 100,- truncated: false,- })+ store.deleteTrn('t1')+ expect(store.items?.t1).toBeUndefined() // optimistic removal- expect(store.items?.t1).toBeUndefined()- expect(store.items?.t2).toBeDefined()+ await tick()+ expect(store.items).toBe(prev)+ expect(store.items?.t1).toBeDefined()+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('skips docs whose id is in inFlightOps (self-echo)', async () => {- const { trackInFlight, untrackInFlight } = await import('~/composables/useStoreSync')+ it('does not touch PowerSync in demo mode', async () => {+ h.demo.value = trueconst store = useTrnsStore()- store.items = {}-- trackInFlight('t1')- await store.applyRealtimePatch({- deletedIds: [],- docs: [{- _creationTime: 0,- _id: 't1',- amount: 100,- categoryId: 'food',- date: 1,- type: 0,- updatedAt: 10,- userId: 'u',- walletId: 'wallet1',- }],- serverTime: 100,- truncated: false,- })- untrackInFlight('t1')+ store.setTrns({ t1: expense() })- expect(store.items?.t1).toBeUndefined()+ store.deleteTrn('t1')+ await tick()+ expect(h.deleteRow).not.toHaveBeenCalled()})})})diff --git a/app/app/components/user/useUserStore.test.ts b/app/app/components/user/useUserStore.test.tsindex 62488ae4..804ac555 100644--- a/app/app/components/user/useUserStore.test.ts+++ b/app/app/components/user/useUserStore.test.ts@@ -1,378 +1,68 @@import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { ref } from 'vue'--// --- Entity-specific mocks -----const mutationMock = vi.fn(() => Promise.resolve())-const queryMock = vi.fn((): Promise<any> => Promise.resolve(null))--const actionMock = vi.fn(() => Promise.resolve())--vi.stubGlobal('useConvexClientWithApi', () => ({- api: {- user: { get: 'user.get', removeAllUserData: 'user.removeAllUserData', upsert: 'user.upsert' },- },- client: {- action: actionMock,- mutation: mutationMock,- query: queryMock,- },-}))--const setLocaleMock = vi.fn()-vi.stubGlobal('useNuxtApp', () => ({- $i18n: { setLocale: setLocaleMock },-}))--vi.stubGlobal('useOnline', () => ref(true))--type SessionUser = { email: string, id: string, image: string | null, name: string }-type SessionData = { data: { user: SessionUser } | null, isPending: boolean }-const useSessionMock = vi.fn(() => ref<SessionData>({ data: null, isPending: false }))-const authSignOutMock = vi.fn(() => Promise.resolve())-vi.stubGlobal('useAuth', () => ({- signOut: authSignOutMock,- useSession: useSessionMock,-}))--const setTrnsMock = vi.fn()-const setCategoriesMock = vi.fn()-const setWalletsMock = vi.fn()-const trnFormResetMock = vi.fn()--vi.mock('~/components/categories/useCategoriesStore', () => ({- useCategoriesStore: () => ({- setCategories: (...args: unknown[]) => setCategoriesMock(...args),- }),-}))--vi.mock('~/components/trns/useTrnsStore', () => ({- useTrnsStore: () => ({- setTrns: (...args: unknown[]) => setTrnsMock(...args),- }),-}))--vi.mock('~/components/wallets/useWalletsStore', () => ({- useWalletsStore: () => ({- setWallets: (...args: unknown[]) => setWalletsMock(...args),- }),-}))--vi.mock('~/components/trnForm/useTrnsFormStore', () => ({- useTrnsFormStore: () => ({- $reset: (...args: unknown[]) => trnFormResetMock(...args),- }),+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { STORAGE_KEYS } from '~/components/offline/storageKeys'+import { useUserStore } from '~/components/user/useUserStore'++const h = vi.hoisted(() => ({+ auth: { session: { value: null }, signOut: vi.fn(), uid: { value: 'u1' }, user: { value: null } },+ deleteRow: vi.fn(),+ demo: { value: false },+ disconnectPowerSync: vi.fn(async () => true),+ upsertRow: vi.fn(),+ upsertRows: vi.fn(),+ usePowerSyncDb: vi.fn(() => ({ execute: vi.fn() })),+ watchTable: vi.fn(() => ({ abort: vi.fn() })),}))-const clearAuthCookieMock = vi.fn()-const setSessionInitializedMock = vi.fn()-vi.mock('~/composables/useAuthCookie', () => ({- clearAuthCookie: (...args: unknown[]) => clearAuthCookieMock(...args),- setSessionInitialized: (...args: unknown[]) => setSessionInitializedMock(...args),-}))+vi.mock('localforage', () => ({ default: { clear: vi.fn(), getItem: vi.fn(), removeItem: vi.fn(), setItem: vi.fn() } }))+vi.mock('~~/services/powersync/db', () => ({ disconnectPowerSync: h.disconnectPowerSync, usePowerSyncDb: h.usePowerSyncDb, watchTable: h.watchTable }))+vi.mock('~~/services/powersync/mutations', () => ({ deleteRow: h.deleteRow, upsertRow: h.upsertRow, upsertRows: h.upsertRows }))+vi.mock('~/components/demo/useDemo', () => ({ useDemo: () => ({ isDemo: h.demo }) }))+vi.mock('~/composables/useSupabase', () => ({ useSupabase: () => ({}), useSupabaseAuth: () => h.auth }))-const blockPersistMock = vi.fn()-vi.mock('~/composables/useStoreSync', async (importOriginal) => {- const actual = await importOriginal<typeof import('~/composables/useStoreSync')>()- return {- ...actual,- blockPersist: (...args: unknown[]) => blockPersistMock(...args),- }-})--const clearOfflineQueueMock = vi.fn(() => Promise.resolve())-const setOfflineQueueUserIdMock = vi.fn()-vi.mock('~/components/offline/helpers', () => ({- clearOfflineQueue: (...args: any[]) => (clearOfflineQueueMock as any)(...args),- getOfflineOpsByEntity: vi.fn(() => Promise.resolve([])),- pushOfflineOp: vi.fn(() => Promise.resolve()),- setOfflineQueueUserId: (...args: any[]) => (setOfflineQueueUserIdMock as any)(...args),-}))+const setItem = vi.mocked(localforage.setItem)-const useCookieMock = vi.fn(() => ({ value: null }))-vi.stubGlobal('useCookie', useCookieMock)--const { useUserStore } = await import('~/components/user/useUserStore')--// --- Tests ---+const sampleUser = { displayName: 'Ilya', email: '[email protected]', photoURL: null, uid: 'u1' }describe('useUserStore', () => {- beforeEach(async () => {+ beforeEach(() => {setActivePinia(createPinia())- await localforage.clear()- vi.clearAllMocks()- })-- afterEach(() => {- vi.restoreAllMocks()- })-- describe('setUserBaseCurrency', () => {- it('updates baseCurrency ref', () => {- const store = useUserStore()- store.setUserBaseCurrency('EUR')- expect(store.baseCurrency).toBe('EUR')- })-- it('persists to localforage', async () => {- const store = useUserStore()- store.setUserBaseCurrency('EUR')-- const saved = await localforage.getItem<any>('finapp.userSettings')- expect(saved).toEqual({ baseCurrency: 'EUR', locale: 'en' })- })- })-- describe('saveUserBaseCurrency', () => {- it('updates ref and calls Convex mutation', () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'user1', image: null, name: 'Test' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- store.saveUserBaseCurrency('JPY')-- expect(store.baseCurrency).toBe('JPY')- expect(mutationMock).toHaveBeenCalledWith(- 'user.upsert',- { baseCurrency: 'JPY' },- )- })-- it('skips Convex mutation in demo mode', async () => {- const demoModule = await import('~/components/demo/useDemo')- const original = demoModule.useDemo- const demoWritable = demoModule as Record<string, typeof demoModule.useDemo>- demoWritable.useDemo = () => ({ ...original(), isDemo: ref('true') })-- setActivePinia(createPinia())- const store = useUserStore()- store.saveUserBaseCurrency('GBP')-- expect(store.baseCurrency).toBe('GBP')- expect(mutationMock).not.toHaveBeenCalled()-- demoWritable.useDemo = original- })- })-- describe('setUserLocale', () => {- it('updates locale ref and calls setLocale', () => {- const store = useUserStore()- store.setUserLocale('ru')-- expect(store.locale).toBe('ru')- expect(setLocaleMock).toHaveBeenCalledWith('ru')- })-- it('persists to localforage', async () => {- const store = useUserStore()- store.setUserLocale('ru')-- const saved = await localforage.getItem<any>('finapp.userSettings')- expect(saved).toEqual({ baseCurrency: 'USD', locale: 'ru' })- })+ h.demo.value = false+ setItem.mockClear()})- describe('saveUserLocale', () => {- it('calls Convex mutation when not in demo mode', () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'user1', image: null, name: 'Test' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- store.saveUserLocale('ru')-- expect(store.locale).toBe('ru')- expect(mutationMock).toHaveBeenCalledWith(- 'user.upsert',- { locale: 'ru' },- )+ describe('setUser localforage gating (real mode is the source of truth)', () => {+ it('does NOT persist the user to localforage in real mode', () => {+ useUserStore().setUser(sampleUser)+ expect(setItem).not.toHaveBeenCalled()})- it('skips Convex mutation in demo mode', async () => {- const demoModule = await import('~/components/demo/useDemo')- const original = demoModule.useDemo- const demoWritable = demoModule as Record<string, typeof demoModule.useDemo>- demoWritable.useDemo = () => ({ ...original(), isDemo: ref('true') })-- setActivePinia(createPinia())- const store = useUserStore()- store.saveUserLocale('ru')-- expect(store.locale).toBe('ru')- expect(setLocaleMock).toHaveBeenCalledWith('ru')- expect(mutationMock).not.toHaveBeenCalled()-- demoWritable.useDemo = original+ it('persists the user to localforage in demo mode', () => {+ h.demo.value = true+ useUserStore().setUser(sampleUser)+ expect(setItem).toHaveBeenCalledWith(STORAGE_KEYS.user, expect.objectContaining({ email: '[email protected]', uid: 'u1' }))})})- describe('initUserSettings', () => {- it('sets baseCurrency and locale from Convex', async () => {- queryMock.mockResolvedValue({ baseCurrency: 'EUR', locale: 'ru' })-- const store = useUserStore()- await store.initUserSettings()-- expect(store.baseCurrency).toBe('EUR')- expect(store.locale).toBe('ru')- expect(setLocaleMock).toHaveBeenCalledWith('ru')+ describe('persistUserSettings localforage gating', () => {+ it('does NOT persist settings to localforage in real mode', () => {+ useUserStore().setUserBaseCurrency('EUR')+ expect(setItem).not.toHaveBeenCalled()})- it('defaults to USD when baseCurrency is empty', async () => {- queryMock.mockResolvedValue({ baseCurrency: '', locale: null })-- const store = useUserStore()- await store.initUserSettings()-- expect(store.baseCurrency).toBe('USD')- })-- it('does nothing when settings is null', async () => {- queryMock.mockResolvedValue(null)-- const store = useUserStore()- await store.initUserSettings()-- expect(store.baseCurrency).toBe('USD')- expect(store.locale).toBe('en')- })-- it('skips locale when not set in settings', async () => {- queryMock.mockResolvedValue({ baseCurrency: 'GBP' })-- const store = useUserStore()- await store.initUserSettings()-- expect(store.baseCurrency).toBe('GBP')- expect(store.locale).toBe('en')- expect(setLocaleMock).not.toHaveBeenCalled()- })- })-- describe('persistUserSettings', () => {- it('saves both baseCurrency and locale together', async () => {+ it('persists settings to localforage in demo mode', () => {+ h.demo.value = trueconst store = useUserStore()store.setUserBaseCurrency('EUR')- store.setUserLocale('ru')-- const saved = await localforage.getItem<any>('finapp.userSettings')- expect(saved).toEqual({ baseCurrency: 'EUR', locale: 'ru' })- })- })-- describe('signOut', () => {- beforeEach(() => {- // Mock window.location- Object.defineProperty(window, 'location', {- configurable: true,- value: { href: '/' },- writable: true,- })- })-- it('blocks persist to prevent race conditions', async () => {- const store = useUserStore()- await store.signOut()-- expect(blockPersistMock).toHaveBeenCalled()- })-- it('resets all stores', async () => {- const store = useUserStore()- await store.signOut()-- expect(setTrnsMock).toHaveBeenCalledWith(null)- expect(setCategoriesMock).toHaveBeenCalledWith(null)- expect(setWalletsMock).toHaveBeenCalledWith(null)- expect(trnFormResetMock).toHaveBeenCalled()- })-- it('clears auth state', async () => {- const store = useUserStore()- await store.signOut()-- expect(clearAuthCookieMock).toHaveBeenCalled()- expect(setSessionInitializedMock).toHaveBeenCalledWith(false)- })-- it('clears localforage', async () => {- await localforage.setItem('finapp.wallets', 'testValue')- const store = useUserStore()- await store.signOut()-- const value = await localforage.getItem('finapp.wallets')- expect(value).toBeNull()- })-- it('calls authClient.signOut', async () => {- const store = useUserStore()- await store.signOut()-- expect(authSignOutMock).toHaveBeenCalled()- })-- it('redirects to /login', async () => {- const store = useUserStore()- await store.signOut()-- expect(window.location.href).toBe('/login')- })-- it('resets isSigningOut after completion', async () => {- const store = useUserStore()- await store.signOut()-- expect(store.isSigningOut).toBe(false)- })-- it('resets isSigningOut on error', async () => {- authSignOutMock.mockRejectedValueOnce(new Error('network'))- const store = useUserStore()- await store.signOut()-- expect(store.isSigningOut).toBe(false)+ expect(store.baseCurrency).toBe('EUR')+ expect(setItem).toHaveBeenCalledWith(STORAGE_KEYS.userSettings, expect.objectContaining({ baseCurrency: 'EUR' }))})})- describe('removeAllUserData', () => {- it('blocks persist', async () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'u1', image: null, name: 'A' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- await store.removeAllUserData()-- expect(blockPersistMock).toHaveBeenCalled()- })-- it('resets all stores', async () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'u1', image: null, name: 'A' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- await store.removeAllUserData()-- expect(setTrnsMock).toHaveBeenCalledWith(null)- expect(setCategoriesMock).toHaveBeenCalledWith(null)- expect(setWalletsMock).toHaveBeenCalledWith(null)- expect(trnFormResetMock).toHaveBeenCalled()- })-- it('clears offline queue and restores userId', async () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'u1', image: null, name: 'A' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- await store.removeAllUserData()-- expect(clearOfflineQueueMock).toHaveBeenCalled()- expect(setOfflineQueueUserIdMock).toHaveBeenCalledWith('u1')- })-- it('calls Convex removeAllUserData action', async () => {- useSessionMock.mockReturnValue(ref({ data: { user: { email: '[email protected]', id: 'u1', image: null, name: 'A' } }, isPending: false }))- setActivePinia(createPinia())- const store = useUserStore()- await store.removeAllUserData()-- expect(actionMock).toHaveBeenCalledWith('user.removeAllUserData', {})- })+ it('no longer carries the removed offline-queue keys in STORAGE_KEYS', () => {+ expect(Object.values(STORAGE_KEYS)).not.toContain('finapp.offlineQueue')+ expect(Object.keys(STORAGE_KEYS)).not.toContain('offlineQueue')})})diff --git a/app/app/components/wallets/useWalletsStore.test.ts b/app/app/components/wallets/useWalletsStore.test.tsindex d3bf48ff..92e51ec5 100644--- a/app/app/components/wallets/useWalletsStore.test.ts+++ b/app/app/components/wallets/useWalletsStore.test.ts@@ -1,335 +1,205 @@-import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { TrnItem } from '~/components/trns/types'import type { WalletItem } from '~/components/wallets/types'-// --- Entity-specific mocks -----vi.mock('~~/services/convex/api', () => ({- convexWalletsToMap: (v: any) => v,-}))--vi.mock('~~/utils/simple', () => ({- uniqueElementsBy: () => [],-}))--const mutationMock = vi.fn(() => Promise.resolve())-const actionMock = vi.fn(() => Promise.resolve())-const onUpdateMock = vi.fn()--vi.stubGlobal('useConvexClientWithApi', () => ({- api: {- wallets: { create: 'wallets.create', list: 'wallets.list', remove: 'wallets.remove', update: 'wallets.update', updateOrder: 'wallets.updateOrder' },- },- client: {- action: actionMock,- mutation: mutationMock,- onUpdate: onUpdateMock,- },-}))--const removeTrnsFromStoreMock = vi.fn()-vi.mock('~/components/trns/useTrnsStore', () => ({- useTrnsStore: () => ({- getStoreTrnsIds: () => [],- items: {},- removeTrnsFromStore: removeTrnsFromStoreMock,- }),-}))--vi.mock('~/components/currencies/useCurrenciesStore', () => ({- useCurrenciesStore: () => ({- base: 'USD',- rates: {},- }),-}))--vi.mock('~/components/user/useUserStore', () => ({- useUserStore: () => ({- baseCurrency: 'USD',- saveUserBaseCurrency: vi.fn(),- }),-}))--const offlineHelpers = await import('~/components/offline/helpers')-vi.mock('~/components/offline/helpers', async (importOriginal) => {- const actual = await importOriginal() as any+import { TrnType } from '~/components/trns/types'+import { useTrnsStore } from '~/components/trns/useTrnsStore'+import { useWalletsStore } from '~/components/wallets/useWalletsStore'+import { toastAddMock } from '~/test-utils/setup-store'++const h = vi.hoisted(() => {+ const watchCallbacks: ((rows: any[]) => void)[] = []return {- clearOfflineQueue: vi.fn(actual.clearOfflineQueue),- getAllOfflineOps: vi.fn(actual.getAllOfflineOps),- getOfflineOpsByEntity: vi.fn(actual.getOfflineOpsByEntity),- pushOfflineOp: vi.fn(actual.pushOfflineOp),- removeOfflineOp: vi.fn(actual.removeOfflineOp),- removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),- removeOfflineOps: vi.fn(actual.removeOfflineOps),+ auth: { session: { value: null }, signOut: vi.fn(), uid: { value: 'u1' }, user: { value: null } },+ deleteRow: vi.fn(),+ demo: { value: false },+ upsertRow: vi.fn(),+ upsertRows: vi.fn(),+ watchCallbacks,+ watchTable: vi.fn((_sql: string, _params: unknown[], cb: (rows: any[]) => void) => {+ watchCallbacks.push(cb)+ return { abort: vi.fn() }+ }),}})-const { useWalletsStore } = await import('~/components/wallets/useWalletsStore')+vi.mock('~~/services/powersync/db', () => ({ watchTable: h.watchTable }))+vi.mock('~~/services/powersync/mutations', () => ({ deleteRow: h.deleteRow, upsertRow: h.upsertRow, upsertRows: h.upsertRows }))+vi.mock('~/components/demo/useDemo', () => ({ useDemo: () => ({ isDemo: h.demo }) }))+vi.mock('~/composables/useSupabase', () => ({ useSupabase: () => ({}), useSupabaseAuth: () => h.auth }))-// --- Helpers ---+const tick = () => new Promise<void>(resolve => setTimeout(resolve, 0))-function makeWallet(overrides: Partial<WalletItem> = {}): WalletItem {- return {- color: '#0f0',- currency: 'USD',- desc: '',- isArchived: false,- isExcludeInTotal: false,- isWithdrawal: false,- name: 'Cash',- order: 0,- type: 'cash',- updatedAt: 1700000000000,- ...overrides,- } as WalletItem+function wallet(over: Partial<WalletItem> = {}): WalletItem {+ return { color: '#fff', currency: 'USD', desc: '', isArchived: false, isExcludeInTotal: false, isWithdrawal: false, name: 'Cash', order: 0, type: 'cash', updatedAt: 1, ...over } as WalletItem}-// --- Tests ---+function walletRow(id: string, order = 0) {+ return { color: '#fff', currency: 'USD', desc: '', id, isArchived: 0, isExcludeInTotal: 0, isWithdrawal: 0, name: id, order, type: 'cash', updatedAt: 1 }+}++function expense(over: Partial<TrnItem> = {}): TrnItem {+ return { amount: 100, categoryId: 'food', date: 1700000000000, type: TrnType.Expense, updatedAt: 1, walletId: 'w1', ...over } as TrnItem+}describe('useWalletsStore', () => {- beforeEach(async () => {+ beforeEach(() => {setActivePinia(createPinia())- await localforage.clear()- vi.clearAllMocks()- mutationMock.mockReturnValue(Promise.resolve())- actionMock.mockReturnValue(Promise.resolve())- })-- afterEach(() => {- vi.restoreAllMocks()+ h.demo.value = false+ h.watchCallbacks.length = 0+ h.watchTable.mockClear()+ h.upsertRow.mockReset().mockResolvedValue(undefined)+ h.upsertRows.mockReset().mockResolvedValue(undefined)+ h.deleteRow.mockReset().mockResolvedValue(undefined)+ toastAddMock.mockClear()})- describe('saveWallet — optimistic UI', () => {- it('updates items immediately', () => {+ describe('hydration via watch', () => {+ it('subscribes to the wallets table and maps row snapshots', () => {const store = useWalletsStore()- store.items = {}-- store.saveWallet({ id: 'w1', values: makeWallet() })-- expect(store.items).toHaveProperty('w1')- expect(store.items!.w1!.name).toBe('Cash')- })-- it('pushes to offline queue immediately', () => {- const store = useWalletsStore()- store.items = {}-- store.saveWallet({ id: 'w1', values: makeWallet() })-- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'wallets', id: 'w1', type: 'create' }),- )- })-- it('fires Convex create mutation for new wallet', () => {- const store = useWalletsStore()- store.items = {}-- store.saveWallet({ id: 'w1', values: makeWallet() })-- expect(mutationMock).toHaveBeenCalledWith(- 'wallets.create',- expect.objectContaining({ currency: 'USD', name: 'Cash' }),- )- })-- it('fires Convex update mutation for existing wallet', () => {- const store = useWalletsStore()- store.items = { w1: makeWallet() }-- store.saveWallet({ id: 'w1', values: makeWallet({ name: 'Updated Cash' }) })-- expect(mutationMock).toHaveBeenCalledWith(- 'wallets.update',- expect.objectContaining({ id: 'w1', name: 'Updated Cash' }),- )- })+ store.initWallets()- it('cleans up offline queue on mutation success', async () => {- const store = useWalletsStore()- store.items = {}+ expect(h.watchTable).toHaveBeenCalledTimes(1)+ expect(h.watchTable.mock.calls[0]?.[0]).toBe('SELECT * FROM wallets')- store.saveWallet({ id: 'w1', values: makeWallet() })+ h.watchCallbacks[0]!([walletRow('a', 0), walletRow('b', 1)])+ expect(Object.keys(store.items ?? {})).toEqual(['a', 'b'])+ expect(store.items?.a).toMatchObject({ currency: 'USD', type: 'cash' })- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('wallets', 'w1')- })+ h.watchCallbacks[0]!([])+ expect(store.items).toBeNull()})- it('keeps offline queue when mutation pending', async () => {- mutationMock.mockReturnValue(new Promise(() => {}))-+ it('flips isLoaded on the first emission and resets it on re-subscribe', () => {const store = useWalletsStore()- store.items = {}+ expect(store.isLoaded).toBe(false)- store.saveWallet({ id: 'w1', values: makeWallet() })+ store.initWallets()+ expect(store.isLoaded).toBe(false) // armed but no emission yet- await new Promise(r => setTimeout(r, 10))+ h.watchCallbacks[0]!([]) // even an empty emission counts as hydrated+ expect(store.isLoaded).toBe(true)- expect(offlineHelpers.removeOfflineOp).not.toHaveBeenCalled()- })-- it('shows toast on mutation failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- mutationMock.mockReturnValue(Promise.reject(new Error('network')))-- const store = useWalletsStore()- store.items = {}-- store.saveWallet({ id: 'w1', values: makeWallet() })-- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error', description: 'wallets.errors.saveFailed' }),- )- })+ store.initWallets() // re-subscribe (e.g. a different user) waits again+ expect(store.isLoaded).toBe(false)})})- describe('deleteWallet — optimistic UI', () => {- it('removes item from store immediately', () => {+ describe('saveWallet', () => {+ it('assigns the next order to a new wallet and upserts it', async () => {const store = useWalletsStore()- store.items = { w1: makeWallet(), w2: makeWallet({ name: 'Card' }) }+ store.setWallets({ w1: wallet({ order: 0 }) })- store.deleteWallet('w1')+ store.saveWallet({ id: 'w2', values: wallet({ name: 'Card' }) })+ expect(store.items?.w2).toMatchObject({ name: 'Card', order: 1 }) // maxOrder + 1- expect(store.items).not.toHaveProperty('w1')- expect(store.items).toHaveProperty('w2')+ await tick()+ expect(h.upsertRow).toHaveBeenCalledWith('wallets', 'w2', expect.objectContaining({ order: 1, userId: 'u1' }))})- it('pushes to offline queue', () => {+ it('rolls back and toasts when the write fails', async () => {const store = useWalletsStore()- store.items = { w1: makeWallet() }+ store.setWallets({ w1: wallet({ order: 0 }) })+ const prev = store.items+ h.upsertRow.mockReset().mockRejectedValueOnce(new Error('boom'))- store.deleteWallet('w1')+ store.saveWallet({ id: 'w2', values: wallet() })+ expect(store.items?.w2).toBeDefined()- expect(offlineHelpers.pushOfflineOp).toHaveBeenCalledWith(- expect.objectContaining({ entity: 'wallets', id: 'w1', type: 'delete' }),- )+ await tick()+ expect(store.items).toBe(prev)+ expect(store.items?.w2).toBeUndefined()+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('fires Convex remove mutation', () => {+ it('does not touch PowerSync in demo mode', async () => {+ h.demo.value = trueconst store = useWalletsStore()- store.items = { w1: makeWallet() }-- store.deleteWallet('w1')+ store.setWallets({ w1: wallet() })+ store.saveWallet({ id: 'w2', values: wallet() })- expect(actionMock).toHaveBeenCalledWith('wallets.remove', { id: 'w1' })- })-- it('cleans up offline queue on mutation success', async () => {- const store = useWalletsStore()- store.items = { w1: makeWallet() }-- store.deleteWallet('w1')-- await vi.waitFor(() => {- expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('wallets', 'w1')- })+ await tick()+ expect(h.upsertRow).not.toHaveBeenCalled()})+ })- it('removes trns from store immediately (optimistic)', () => {+ describe('saveWalletsOrder', () => {+ it('reorders optimistically and upserts every wallet', async () => {const store = useWalletsStore()- store.items = { w1: makeWallet() }+ store.setWallets({ a: wallet({ order: 0 }), b: wallet({ order: 1 }) })- store.deleteWallet('w1', ['trn1', 'trn2'])+ store.saveWalletsOrder(['b', 'a'])+ expect(store.items?.b?.order).toBe(0)+ expect(store.items?.a?.order).toBe(1)- expect(removeTrnsFromStoreMock).toHaveBeenCalledWith(['trn1', 'trn2'])+ await tick()+ expect(h.upsertRows).toHaveBeenCalledTimes(1)+ const rows = h.upsertRows.mock.calls[0]?.[1] as { id: string }[]+ expect(rows.map(r => r.id)).toEqual(['b', 'a'])})- it('shows toast on failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- actionMock.mockReturnValue(Promise.reject(new Error('network')))+ it('restores the previous order and toasts when the write fails', async () => {const store = useWalletsStore()- store.items = { w1: makeWallet() }+ store.setWallets({ a: wallet({ order: 0 }), b: wallet({ order: 1 }) })+ const prev = store.items+ h.upsertRows.mockReset().mockRejectedValueOnce(new Error('boom'))- store.deleteWallet('w1')+ store.saveWalletsOrder(['b', 'a'])+ await tick()- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error', description: 'wallets.errors.deleteFailed' }),- )- })+ expect(store.items).toBe(prev)+ expect(toastAddMock).toHaveBeenCalledTimes(1)})})- describe('saveWalletsOrder', () => {- it('updates order in store optimistically', () => {- const store = useWalletsStore()- store.items = {- w1: makeWallet({ name: 'First', order: 0 }),- w2: makeWallet({ name: 'Second', order: 1 }),- }-- // Reorder: w2 first, w1 second- mutationMock.mockReturnValue(new Promise(() => {})) // never resolves- store.saveWalletsOrder(['w2', 'w1'])-- expect(store.items!.w2!.order).toBe(0)- expect(store.items!.w1!.order).toBe(1)- })-- it('fires atomic updateOrder mutation', () => {+ describe('deleteWallet', () => {+ it('cascades: removes the wallet and its trns, deleting both in the DB', async () => {+ const trnsStore = useTrnsStore()+ trnsStore.setTrns({ t1: expense(), t2: expense({ walletId: 'w2' }) })const store = useWalletsStore()- store.items = {- w1: makeWallet({ name: 'First', order: 0 }),- w2: makeWallet({ name: 'Second', order: 1 }),- }-- store.saveWalletsOrder(['w2', 'w1'])-- expect(mutationMock).toHaveBeenCalledWith('wallets.updateOrder', {- orders: [- { id: 'w2', order: 0 },- { id: 'w1', order: 1 },- ],- })- })+ store.setWallets({ w1: wallet() })- it('shows toast on failure', async () => {- const { toastAddMock } = await import('~/test-utils/setup-store')- mutationMock.mockReturnValue(Promise.reject(new Error('network')))+ await store.deleteWallet('w1', ['t1'])- const store = useWalletsStore()- store.items = {- w1: makeWallet({ order: 0 }),- w2: makeWallet({ order: 1 }),- }-- store.saveWalletsOrder(['w2', 'w1'])- await vi.waitFor(() => {- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error', description: 'wallets.errors.orderFailed' }),- )- })+ expect(store.items?.w1).toBeUndefined()+ expect(trnsStore.items?.t1).toBeUndefined()+ expect(trnsStore.items?.t2).toBeDefined()+ expect(h.deleteRow).toHaveBeenCalledWith('wallets', 'w1')+ expect(h.deleteRow).toHaveBeenCalledWith('trns', 't1')})- })- describe('saveWallet — new wallet order', () => {- it('sets order to max+1 for new wallets', () => {+ it('restores the wallet and cascaded trns when the write fails', async () => {+ const trnsStore = useTrnsStore()+ const seededTrns = { t1: expense() }+ trnsStore.setTrns(seededTrns)const store = useWalletsStore()- store.items = {- w1: makeWallet({ order: 0 }),- w2: makeWallet({ order: 3 }),- }+ store.setWallets({ w1: wallet() })+ const prevWallets = store.items+ h.deleteRow.mockReset().mockRejectedValueOnce(new Error('boom'))- store.saveWallet({ id: 'w3', values: makeWallet({ order: 0 }) })+ await store.deleteWallet('w1', ['t1'])- expect(store.items!.w3!.order).toBe(4)+ expect(store.items).toBe(prevWallets)+ expect(store.items?.w1).toBeDefined()+ expect(trnsStore.items).toBe(seededTrns)+ expect(trnsStore.items?.t1).toBeDefined()+ expect(toastAddMock).toHaveBeenCalledTimes(1)})- it('does not change order for existing wallets', () => {+ it('does not touch PowerSync in demo mode', async () => {+ h.demo.value = true+ const trnsStore = useTrnsStore()+ trnsStore.setTrns({ t1: expense() })const store = useWalletsStore()- store.items = {- w1: makeWallet({ order: 0 }),- w2: makeWallet({ order: 3 }),- }+ store.setWallets({ w1: wallet() })- store.saveWallet({ id: 'w1', values: makeWallet({ order: 5 }) })+ await store.deleteWallet('w1', ['t1'])- expect(store.items!.w1!.order).toBe(5)+ expect(store.items?.w1).toBeUndefined()+ expect(trnsStore.items?.t1).toBeUndefined()+ expect(h.deleteRow).not.toHaveBeenCalled()})})})diff --git a/app/app/composables/useAuthSession.test.ts b/app/app/composables/useAuthSession.test.tsnew file mode 100644index 00000000..1c8bb971--- /dev/null+++ b/app/app/composables/useAuthSession.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { AUTH_STORAGE_KEY, getPersistedSession, getPersistedUid, hasPersistedSession } from '~/composables/useAuthSession'++let store: Record<string, string>++function makeSession(uid = 'user-123', expiresAt: number | undefined = 9999999999) {+ return JSON.stringify({+ access_token: 'a',+ expires_at: expiresAt,+ refresh_token: 'r',+ user: { email: '[email protected]', id: uid },+ })+}++describe('useAuthSession', () => {+ beforeEach(() => {+ store = {}+ vi.stubGlobal('localStorage', {+ getItem: (k: string) => store[k] ?? null,+ removeItem: (k: string) => { delete store[k] },+ setItem: (k: string, v: string) => { store[k] = v },+ })+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ describe('getPersistedSession', () => {+ it('reads the pinned storage key', () => {+ expect(AUTH_STORAGE_KEY).toBe('finapp.auth')+ store[AUTH_STORAGE_KEY] = makeSession('u1', 1700000000)+ expect(getPersistedUid()).toBe('u1')+ })++ it('parses a valid v2 session (uid + expiresAt)', () => {+ store[AUTH_STORAGE_KEY] = makeSession('u1', 1700000000)+ expect(getPersistedSession()).toEqual({ expiresAt: 1700000000, uid: 'u1' })+ })++ it('passes an expired token optimistically (refresh corrects it)', () => {+ store[AUTH_STORAGE_KEY] = makeSession('u1', 1) // long past+ expect(hasPersistedSession()).toBe(true)+ expect(getPersistedUid()).toBe('u1')+ })++ it('unwraps a legacy { currentSession } shape', () => {+ store[AUTH_STORAGE_KEY] = JSON.stringify({ currentSession: { expires_at: 5, user: { id: 'legacy' } }, expiresAt: 5 })+ expect(getPersistedSession()).toEqual({ expiresAt: 5, uid: 'legacy' })+ })++ it('returns null for a missing token', () => {+ expect(getPersistedSession()).toBeNull()+ expect(hasPersistedSession()).toBe(false)+ expect(getPersistedUid()).toBeNull()+ })++ it('returns null for malformed JSON', () => {+ store[AUTH_STORAGE_KEY] = '{ not json'+ expect(hasPersistedSession()).toBe(false)+ })++ it('returns null when the token has no user id', () => {+ store[AUTH_STORAGE_KEY] = JSON.stringify({ access_token: 'a', user: {} })+ expect(hasPersistedSession()).toBe(false)+ })++ it('returns null (does not throw) when localStorage access throws', () => {+ vi.stubGlobal('localStorage', {+ getItem: () => { throw new Error('blocked') },+ })+ expect(getPersistedSession()).toBeNull()+ })+ })+})diff --git a/app/app/composables/useStoreSync.test.ts b/app/app/composables/useStoreSync.test.tsindex 33f7463e..3c8dd101 100644--- a/app/app/composables/useStoreSync.test.ts+++ b/app/app/composables/useStoreSync.test.ts@@ -1,300 +1,64 @@import localforage from 'localforage'-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { OfflineOp } from '~/components/offline/types'+import {+ blockPersist,+ createDebouncedPersist,+ isPersistBlocked,+ showErrorToast,+ unblockPersist,+} from '~/composables/useStoreSync'+import { toastAddMock } from '~/test-utils/setup-store'-const getOfflineOpsByEntityMock = vi.fn<() => Promise<OfflineOp[]>>().mockResolvedValue([])-const pushOfflineOpMock = vi.fn()-const removeOfflineOpMock = vi.fn().mockResolvedValue(undefined)-const removeOfflineOpsMock = vi.fn().mockResolvedValue(undefined)+vi.mock('localforage', () => ({ default: { setItem: vi.fn() } }))-vi.mock('~/components/offline/helpers', () => ({- getOfflineOpsByEntity: (...args: unknown[]) => getOfflineOpsByEntityMock(...args as []),- pushOfflineOp: (...args: unknown[]) => pushOfflineOpMock(...args as []),- removeOfflineOp: (...args: unknown[]) => removeOfflineOpMock(...args as []),- removeOfflineOps: (...args: unknown[]) => removeOfflineOpsMock(...args as []),-}))+const setItem = vi.mocked(localforage.setItem)-let isReplayingValue = false-vi.mock('~/components/offline/replay', () => ({- isReplaying: () => isReplayingValue,-}))--beforeEach(async () => {- vi.clearAllMocks()- isReplayingValue = false- await localforage.clear()-})--describe('mergeOfflineOps', () => {- it('applies pending updates and deletes on top of server data', async () => {- const { mergeOfflineOps } = await import('~/composables/useStoreSync')-- getOfflineOpsByEntityMock.mockResolvedValueOnce([- { data: { name: 'Updated' }, entity: 'wallets', id: 'w1', timestamp: 1, type: 'update' },- { entity: 'wallets', id: 'w2', timestamp: 2, type: 'delete' },- ] satisfies OfflineOp[])-- const serverData = {- w1: { color: '#fff', name: 'Original' },- w2: { color: '#000', name: 'ToDelete' },- w3: { color: '#aaa', name: 'Untouched' },- }-- const result = await mergeOfflineOps(serverData, 'wallets')-- expect(result.w1).toEqual({ name: 'Updated' })- expect(result).not.toHaveProperty('w2')- expect(result.w3).toEqual({ color: '#aaa', name: 'Untouched' })- })-- it('returns data as-is when queue is empty', async () => {- const { mergeOfflineOps } = await import('~/composables/useStoreSync')-- getOfflineOpsByEntityMock.mockResolvedValueOnce([])-- const serverData = { w1: { name: 'Cash' } }- const result = await mergeOfflineOps(serverData, 'wallets')-- expect(result).toEqual(serverData)- })-- it('removes stale local_ IDs not in pending queue', async () => {- const { mergeOfflineOps } = await import('~/composables/useStoreSync')-- getOfflineOpsByEntityMock.mockResolvedValueOnce([- { data: { name: 'New' }, entity: 'wallets', id: 'local_fresh', timestamp: 1, type: 'create' },- ] satisfies OfflineOp[])-- const data = {- local_fresh: { name: 'New' },- local_stale: { name: 'Ghost' },- server1: { name: 'Real' },- }-- const result = await mergeOfflineOps(data, 'wallets')-- expect(result).toHaveProperty('local_fresh')- expect(result).not.toHaveProperty('local_stale')- expect(result).toHaveProperty('server1')- })-})--describe('handleMutationResult', () => {- it('remaps local_id → convexId on successful create', async () => {- const { handleMutationResult, unblockPersist } = await import('~/composables/useStoreSync')+describe('createDebouncedPersist', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ setItem.mockClear()unblockPersist()-- const items = shallowRef<Record<string, any> | null>({- existing: { name: 'Card' },- local_abc: { name: 'Cash' },- })-- const remap = await handleMutationResult({- action: 'create',- entity: 'wallets',- errorMessage: 'wallets.saveError',- id: 'local_abc',- items,- mutation: Promise.resolve('convex_w1'),- })-- expect(items.value).not.toHaveProperty('local_abc')- expect(items.value).toHaveProperty('convex_w1')- expect(items.value!.convex_w1).toEqual({ name: 'Cash' })- expect(items.value).toHaveProperty('existing')- expect(remap).toEqual({ convexId: 'convex_w1', localId: 'local_abc' })- expect(await localforage.getItem('finapp.wallets')).toEqual(items.value)})-- it('skips persist when persistBlocked', async () => {- const { blockPersist, handleMutationResult } = await import('~/composables/useStoreSync')- blockPersist()-- const items = shallowRef<Record<string, any> | null>({- local_abc: { name: 'Cash' },- })-- await handleMutationResult({- action: 'create',- entity: 'wallets',- errorMessage: 'wallets.saveError',- id: 'local_abc',- items,- mutation: Promise.resolve('convex_w1'),- })-- expect(items.value).toHaveProperty('convex_w1')- expect(await localforage.getItem('finapp.wallets')).toBeNull()-- const { unblockPersist } = await import('~/composables/useStoreSync')+ afterEach(() => {+ vi.useRealTimers()unblockPersist()})- it('shows error toast on mutation failure and does NOT remove offline op', async () => {- const { handleMutationResult, unblockPersist } = await import('~/composables/useStoreSync')- const { toastAddMock } = await import('~/test-utils/setup-store')- unblockPersist()-- await handleMutationResult({- action: 'update',- entity: 'wallets',- errorMessage: 'wallets.saveError',- id: 'w1',- mutation: Promise.reject(new Error('network')),- })+ it('debounces and writes the latest value to localforage', () => {+ const persist = createDebouncedPersist<{ n: number }>('finapp.test')+ persist({ n: 1 })+ persist({ n: 2 })+ expect(setItem).not.toHaveBeenCalled() // still within the debounce window- expect(toastAddMock).toHaveBeenCalledWith(- expect.objectContaining({ color: 'error' }),- )- expect(removeOfflineOpMock).not.toHaveBeenCalled()+ vi.advanceTimersByTime(300)+ expect(setItem).toHaveBeenCalledTimes(1)+ expect(setItem).toHaveBeenCalledWith('finapp.test', { n: 2 })})- it('removes offline op on successful update (no remap)', async () => {- const { handleMutationResult, unblockPersist } = await import('~/composables/useStoreSync')- unblockPersist()-- const result = await handleMutationResult({- action: 'update',- entity: 'wallets',- errorMessage: 'wallets.saveError',- id: 'w1',- mutation: Promise.resolve(undefined),- })-- expect(removeOfflineOpMock).toHaveBeenCalledWith('wallets', 'w1')- expect(result).toBeUndefined()- })-})--describe('pushSaveOp', () => {- it('does nothing in demo mode', async () => {- const { pushSaveOp } = await import('~/composables/useStoreSync')-- const result = pushSaveOp({- entity: 'wallets',- id: 'w1',- isDemo: true,- isExisting: false,- values: { name: 'Cash' },- })-- expect(result).toBe(false)- expect(pushOfflineOpMock).not.toHaveBeenCalled()- })-- it('does not push to queue during replay', async () => {- const { pushSaveOp } = await import('~/composables/useStoreSync')-- isReplayingValue = true-- const result = pushSaveOp({- entity: 'wallets',- id: 'w1',- isDemo: false,- isExisting: false,- values: { name: 'Cash' },- })-- expect(result).toBe(true)- expect(pushOfflineOpMock).not.toHaveBeenCalled()- })-- it('pushes create op for new entities', async () => {- const { pushSaveOp } = await import('~/composables/useStoreSync')-- pushSaveOp({- entity: 'wallets',- id: 'local_abc',- isDemo: false,- isExisting: false,- values: { name: 'Cash' },- })-- expect(pushOfflineOpMock).toHaveBeenCalledWith({- data: { name: 'Cash' },- entity: 'wallets',- id: 'local_abc',- type: 'create',- })- })-- it('pushes update op for existing entities', async () => {- const { pushSaveOp } = await import('~/composables/useStoreSync')-- pushSaveOp({- entity: 'wallets',- id: 'w1',- isDemo: false,- isExisting: true,- values: { name: 'Updated' },- })-- expect(pushOfflineOpMock).toHaveBeenCalledWith({- data: { name: 'Updated' },- entity: 'wallets',- id: 'w1',- type: 'update',- })- })-})--describe('pushDeleteOp', () => {- it('does nothing in demo mode', async () => {- const { pushDeleteOp } = await import('~/composables/useStoreSync')+ it('skips the write while persistence is blocked (sign-out cleanup)', () => {+ blockPersist()+ expect(isPersistBlocked()).toBe(true)- const result = pushDeleteOp({ entity: 'wallets', id: 'w1', isDemo: true })+ const persist = createDebouncedPersist<number>('finapp.test')+ persist(1)+ vi.advanceTimersByTime(300)- expect(result).toBe(false)- expect(pushOfflineOpMock).not.toHaveBeenCalled()+ expect(setItem).not.toHaveBeenCalled()})})-describe('inFlightOps tracking', () => {- it('trackInFlight adds id and isInFlight returns true', async () => {- const { isInFlight, trackInFlight, untrackInFlight } = await import('~/composables/useStoreSync')-- trackInFlight('w1')- expect(isInFlight('w1')).toBe(true)- untrackInFlight('w1')- expect(isInFlight('w1')).toBe(false)+describe('showErrorToast', () => {+ beforeEach(() => {+ toastAddMock.mockClear()})- it('handleMutationResult tracks id during mutation and untracks after resolve', async () => {- const { handleMutationResult, isInFlight } = await import('~/composables/useStoreSync')-- let resolveMutation: (v: unknown) => void- const mutation = new Promise((r) => {- resolveMutation = r- })+ it('adds an error toast carrying the (translated) i18n key', () => {+ showErrorToast('sync.errors.uploadRejected')- const promise = handleMutationResult({- action: 'update',- entity: 'wallets',- errorMessage: 'x',- id: 'w-tracked',- mutation,- })-- expect(isInFlight('w-tracked')).toBe(true)- resolveMutation!(undefined)- await promise- expect(isInFlight('w-tracked')).toBe(false)- })-- it('handleMutationResult untracks id after rejection', async () => {- const { handleMutationResult, isInFlight } = await import('~/composables/useStoreSync')-- const mutation = Promise.reject(new Error('fail'))-- await handleMutationResult({- action: 'update',- entity: 'wallets',- errorMessage: 'x',- id: 'w-fail',- mutation,- })-- expect(isInFlight('w-fail')).toBe(false)+ expect(toastAddMock).toHaveBeenCalledTimes(1)+ expect(toastAddMock).toHaveBeenCalledWith(+ expect.objectContaining({ color: 'error', description: 'sync.errors.uploadRejected' }),+ )})})diff --git a/app/app/middleware/auth.global.test.ts b/app/app/middleware/auth.global.test.tsindex ed6f959c..cd8d2f86 100644--- a/app/app/middleware/auth.global.test.ts+++ b/app/app/middleware/auth.global.test.ts@@ -1,53 +1,21 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'-const {- clearAuthCookieMock,- getSessionMock,- hasAuthCookieMock,- isDemoRef,- isSessionInitializedMock,- navigateToMock,- setAuthCookieMock,- setSessionInitializedMock,-} = vi.hoisted(() => {- let _sessionInitialized = false- const isSessionInitializedMock = vi.fn(() => _sessionInitialized)- const setSessionInitializedMock = vi.fn((value: boolean) => {- _sessionInitialized = value- })-- return {- clearAuthCookieMock: vi.fn(),- getSessionMock: vi.fn(),- hasAuthCookieMock: vi.fn(() => false),- isDemoRef: { value: false },- isSessionInitializedMock,- navigateToMock: vi.fn(),- setAuthCookieMock: vi.fn(),- setSessionInitializedMock,- }-})+const { hasPersistedSessionMock, isDemoRef, navigateToMock } = vi.hoisted(() => ({+ hasPersistedSessionMock: vi.fn(() => false),+ isDemoRef: { value: false },+ navigateToMock: vi.fn(),+}))vi.mock('~/components/demo/useDemo', () => ({useDemo: () => ({ isDemo: isDemoRef }),}))-vi.mock('~/composables/useAuthCookie', () => ({- clearAuthCookie: clearAuthCookieMock,- hasAuthCookie: hasAuthCookieMock,- isSessionInitialized: isSessionInitializedMock,- setAuthCookie: setAuthCookieMock,- setSessionInitialized: setSessionInitializedMock,-}))--vi.mock('~/utils/logger', () => ({- createLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+vi.mock('~/composables/useAuthSession', () => ({+ hasPersistedSession: hasPersistedSessionMock,}))vi.stubGlobal('defineNuxtRouteMiddleware', (fn: any) => fn)vi.stubGlobal('navigateTo', navigateToMock)-vi.stubGlobal('navigator', { onLine: true })-vi.stubGlobal('useAuth', () => ({ getSession: getSessionMock }))vi.stubGlobal('getSafeRedirectPath', (value: unknown) => {if (typeof value === 'string' && value.startsWith('/') && !value.startsWith('//'))return value@@ -59,11 +27,7 @@ function createRoute(path: string, query: Record<string, string> = {}) {return { fullPath: qs ? `${path}?${qs}` : path, path, query }}-async function flushPromises() {- await new Promise(resolve => setTimeout(resolve, 0))-}--type MiddlewareFn = (to: ReturnType<typeof createRoute>) => Promise<unknown>+type MiddlewareFn = (to: ReturnType<typeof createRoute>) => unknownlet middleware: MiddlewareFn@@ -78,40 +42,8 @@ async function loadMiddleware(): Promise<MiddlewareFn> {describe('auth.global middleware', () => {beforeEach(() => {vi.clearAllMocks()- setSessionInitializedMock(false)isDemoRef.value = false- hasAuthCookieMock.mockReturnValue(false)- })-- describe('oTT handling', () => {- it('redirects OTT from arbitrary path to /auth/callback', async () => {- const middleware = await loadMiddleware()- await middleware(createRoute('/dashboard', { ott: 'abc123' }))-- expect(navigateToMock).toHaveBeenCalledWith(- { path: '/auth/callback', query: { ott: 'abc123' } },- { replace: true },- )- })-- it('does not redirect OTT already on /auth/callback', async () => {- const middleware = await loadMiddleware()- const result = await middleware(createRoute('/auth/callback', { ott: 'abc123' }))-- expect(navigateToMock).not.toHaveBeenCalled()- expect(result).toBeUndefined()- })- })-- describe('/auth/callback passthrough', () => {- it('skips all auth checks', async () => {- const middleware = await loadMiddleware()- const result = await middleware(createRoute('/auth/callback'))-- expect(navigateToMock).not.toHaveBeenCalled()- expect(hasAuthCookieMock).not.toHaveBeenCalled()- expect(result).toBeUndefined()- })+ hasPersistedSessionMock.mockReturnValue(false)})describe('demo mode', () => {@@ -121,128 +53,54 @@ describe('auth.global middleware', () => {it('redirects /login to the redirect query path', async () => {const middleware = await loadMiddleware()- await middleware(createRoute('/login', { redirect: '/settings' }))-+ middleware(createRoute('/login', { redirect: '/settings' }))expect(navigateToMock).toHaveBeenCalledWith('/settings')})it('redirects /login to /dashboard without redirect param', async () => {const middleware = await loadMiddleware()- await middleware(createRoute('/login'))-+ middleware(createRoute('/login'))expect(navigateToMock).toHaveBeenCalledWith('/dashboard')})it('passes through non-login routes', async () => {const middleware = await loadMiddleware()- const result = await middleware(createRoute('/dashboard'))-+ const result = middleware(createRoute('/dashboard'))expect(navigateToMock).not.toHaveBeenCalled()expect(result).toBeUndefined()})})- describe('client: with auth cookie', () => {+ describe('with persisted session', () => {beforeEach(() => {- hasAuthCookieMock.mockReturnValue(true)- getSessionMock.mockResolvedValue({ data: { user: { id: 'u1' } } })+ hasPersistedSessionMock.mockReturnValue(true)})it('passes through protected routes', async () => {const middleware = await loadMiddleware()- const result = await middleware(createRoute('/dashboard'))-+ const result = middleware(createRoute('/dashboard'))expect(result).toBeUndefined()expect(navigateToMock).not.toHaveBeenCalled()})- it('triggers background getSession on first visit', async () => {- const middleware = await loadMiddleware()- await middleware(createRoute('/dashboard'))-- expect(getSessionMock).toHaveBeenCalledOnce()- })-- it('skips getSession on subsequent visits (sessionInitialized)', async () => {- const middleware = await loadMiddleware()- await middleware(createRoute('/dashboard'))- await middleware(createRoute('/settings'))-- expect(getSessionMock).toHaveBeenCalledOnce()- })-it('redirects /login to /dashboard', async () => {const middleware = await loadMiddleware()- await middleware(createRoute('/login'))-+ middleware(createRoute('/login'))expect(navigateToMock).toHaveBeenCalledWith('/dashboard')})-- it('clears cookie and redirects when background session expired', async () => {- getSessionMock.mockResolvedValue({ data: { user: null } })- const middleware = await loadMiddleware()- await middleware(createRoute('/dashboard'))- await flushPromises()-- expect(clearAuthCookieMock).toHaveBeenCalled()- expect(navigateToMock).toHaveBeenCalledWith('/login')- })-- it('resets sessionInitialized on expired session so re-login can reinitialize', async () => {- getSessionMock.mockResolvedValueOnce({ data: { user: null } })- const middleware = await loadMiddleware()-- await middleware(createRoute('/dashboard'))- await flushPromises()- expect(clearAuthCookieMock).toHaveBeenCalled()- expect(getSessionMock).toHaveBeenCalledOnce()-- getSessionMock.mockResolvedValue({ data: { user: { id: 'u2' } } })- await middleware(createRoute('/settings'))-- expect(getSessionMock).toHaveBeenCalledTimes(2)- })-- it('resets sessionInitialized on background getSession error', async () => {- getSessionMock.mockRejectedValueOnce(new Error('network'))- const middleware = await loadMiddleware()-- await middleware(createRoute('/dashboard'))- await flushPromises()- expect(getSessionMock).toHaveBeenCalledOnce()-- getSessionMock.mockResolvedValue({ data: { user: { id: 'u1' } } })- await middleware(createRoute('/settings'))-- expect(getSessionMock).toHaveBeenCalledTimes(2)- })})- describe('client: no auth cookie', () => {- it('passes through /login without verification', async () => {+ describe('no persisted session', () => {+ it('passes through /login', async () => {const middleware = await loadMiddleware()- const result = await middleware(createRoute('/login'))-+ const result = middleware(createRoute('/login'))expect(navigateToMock).not.toHaveBeenCalled()- expect(getSessionMock).not.toHaveBeenCalled()expect(result).toBeUndefined()})- it('sets cookie and continues when session is valid', async () => {- getSessionMock.mockResolvedValue({ data: { user: { id: 'user-42' } } })+ it('redirects to /login with redirect param for a protected route', async () => {const middleware = await loadMiddleware()- const result = await middleware(createRoute('/dashboard'))-- expect(setAuthCookieMock).toHaveBeenCalledWith('user-42')- expect(navigateToMock).not.toHaveBeenCalled()- expect(result).toBeUndefined()- })-- it('redirects to /login with redirect param when no session', async () => {- getSessionMock.mockResolvedValue({ data: { user: null } })- const middleware = await loadMiddleware()- await middleware(createRoute('/settings'))-+ middleware(createRoute('/settings'))expect(navigateToMock).toHaveBeenCalledWith({path: '/login',query: { redirect: '/settings' },@@ -250,72 +108,12 @@ describe('auth.global middleware', () => {})it('omits redirect param for root path', async () => {- getSessionMock.mockResolvedValue({ data: { user: null } })const middleware = await loadMiddleware()- await middleware(createRoute('/'))-+ middleware(createRoute('/'))expect(navigateToMock).toHaveBeenCalledWith({path: '/login',query: undefined,})})-- it('redirects to /login when getSession throws', async () => {- getSessionMock.mockRejectedValue(new Error('network error'))- const middleware = await loadMiddleware()- await middleware(createRoute('/settings'))-- expect(navigateToMock).toHaveBeenCalledWith({- path: '/login',- query: { redirect: '/settings' },- })- })- })-- describe('offline', () => {- beforeEach(() => {- vi.stubGlobal('navigator', { onLine: false })- })-- afterEach(() => {- vi.stubGlobal('navigator', { onLine: true })- })-- it('skips getSession when offline with cached cookie', async () => {- hasAuthCookieMock.mockReturnValue(true)- const middleware = await loadMiddleware()- const result = await middleware(createRoute('/dashboard'))-- expect(getSessionMock).not.toHaveBeenCalled()- expect(navigateToMock).not.toHaveBeenCalled()- expect(result).toBeUndefined()- })-- it('redirects /login to /dashboard when offline with cached cookie', async () => {- hasAuthCookieMock.mockReturnValue(true)- const middleware = await loadMiddleware()- await middleware(createRoute('/login'))-- expect(navigateToMock).toHaveBeenCalledWith('/dashboard')- })-- it('redirects to /login when offline without cached cookie', async () => {- const middleware = await loadMiddleware()- await middleware(createRoute('/settings'))-- expect(getSessionMock).not.toHaveBeenCalled()- expect(navigateToMock).toHaveBeenCalledWith({- path: '/login',- query: { redirect: '/settings' },- })- })-- it('passes through /login when offline without cached cookie', async () => {- const middleware = await loadMiddleware()- const result = await middleware(createRoute('/login'))-- expect(navigateToMock).not.toHaveBeenCalled()- expect(result).toBeUndefined()- })})})diff --git a/app/app/test-utils/setup-store.ts b/app/app/test-utils/setup-store.tsindex d1154a5e..e40f796f 100644--- a/app/app/test-utils/setup-store.ts+++ b/app/app/test-utils/setup-store.ts@@ -5,20 +5,22 @@* Stubs Nuxt/Vue/VueUse auto-imports, mocks common modules,* and exports shared state for assertions.*- * Entity-specific mocks (Convex routes, cross-store deps) stay inline in each test file.+ * Entity-specific mocks (cross-store deps) stay inline in each test file.*/import { defineStore } from 'pinia'import { vi } from 'vitest'-import { computed, reactive, ref, shallowRef, watch } from 'vue'+import { computed, reactive, ref, shallowRef, toRaw, watch } from 'vue'vi.stubGlobal('computed', computed)vi.stubGlobal('reactive', reactive)vi.stubGlobal('ref', ref)vi.stubGlobal('shallowRef', shallowRef)+vi.stubGlobal('toRaw', toRaw)vi.stubGlobal('watch', watch)vi.stubGlobal('defineStore', defineStore)vi.stubGlobal('useDebounceFn', (fn: (...args: any[]) => any) => fn)+vi.stubGlobal('perf', () => {})export const toastAddMock = vi.fn()@@ -27,25 +29,10 @@ vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))-vi.stubGlobal('asConvexId', (id: string) => id)-vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))-vi.stubGlobal('cleanupFrontendIds', <T>(data: Record<string, T>, pendingUpdates: Record<string, T>) => {- const result = { ...data }- for (const id of Object.keys(result)) {- if (id.startsWith('local_') && !pendingUpdates[id])- delete result[id]- }- return result-})-vi.mock('~/components/demo/useDemo', () => ({useDemo: () => ({ isDemo: { value: false } }),}))-vi.mock('~/components/offline/replay', () => ({- isReplaying: () => false,-}))-vi.mock('~/assets/js/emo', () => ({errorEmo: [':('],random: (items: any[]) => items[0],diff --git a/app/services/powersync/connector.test.ts b/app/services/powersync/connector.test.tsnew file mode 100644index 00000000..0d266818--- /dev/null+++ b/app/services/powersync/connector.test.ts@@ -0,0 +1,119 @@+import type { SupabaseClient } from '@supabase/supabase-js'++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { setUploadErrorHandler, SupabaseConnector } from '~~/services/powersync/connector'++vi.mock('@powersync/web', () => ({+ UpdateType: { DELETE: 'DELETE', PATCH: 'PATCH', PUT: 'PUT' },+}))++function makeClient(result: { error: unknown }): SupabaseClient {+ const resolve = () => Promise.resolve(result)+ const builder = {+ delete: () => ({ eq: resolve }),+ update: () => ({ eq: resolve }),+ upsert: resolve,+ }+ return { from: () => builder } as unknown as SupabaseClient+}++// Returns the given results in order, one per applied op (each PUT/PATCH/DELETE+// consumes one result), so multi-op transactions can fail on a specific op.+function makeClientSeq(results: { error: unknown }[]): SupabaseClient {+ let i = 0+ const next = () => Promise.resolve(results[i++] ?? { error: null })+ const builder = {+ delete: () => ({ eq: next }),+ update: () => ({ eq: next }),+ upsert: next,+ }+ return { from: () => builder } as unknown as SupabaseClient+}++function makeDb(crud: unknown[]) {+ const complete = vi.fn(async () => {})+ const database = {+ getNextCrudTransaction: vi.fn(async () => (crud.length ? { complete, crud } : null)),+ }+ return { complete, database: database as any }+}++const putOp = { id: 'trn1', op: 'PUT', opData: { amount: 1 }, table: 'trns' }++describe('uploadData', () => {+ beforeEach(() => {+ setUploadErrorHandler(null)+ vi.spyOn(console, 'error').mockImplementation(() => {})+ })+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('completes the transaction on success without calling the error handler', async () => {+ const onError = vi.fn()+ setUploadErrorHandler(onError)+ const { complete, database } = makeDb([putOp])+ const connector = new SupabaseConnector(makeClient({ error: null }), 'http://ps')++ await connector.uploadData(database)++ expect(complete).toHaveBeenCalledTimes(1)+ expect(onError).not.toHaveBeenCalled()+ })++ it('discards a fatal error (RLS), completing the transaction and surfacing it', async () => {+ const onError = vi.fn()+ setUploadErrorHandler(onError)+ const { complete, database } = makeDb([putOp])+ const connector = new SupabaseConnector(+ makeClient({ error: { code: '42501', message: 'rls' } }),+ 'http://ps',+ )++ await connector.uploadData(database)++ expect(complete).toHaveBeenCalledTimes(1) // discarded, queue not blocked+ expect(onError).toHaveBeenCalledTimes(1)+ expect(onError.mock.calls[0]?.[1]).toEqual([putOp]) // diverged ops+ })++ it('surfaces only the failing op and those after it (slice from failedIndex)', async () => {+ const onError = vi.fn()+ setUploadErrorHandler(onError)+ const patchOp = { id: 'trn2', op: 'PATCH', opData: { amount: 2 }, table: 'trns' }+ const { complete, database } = makeDb([putOp, patchOp])+ // First op (PUT) succeeds and commits to the server; second op (PATCH) fails.+ const connector = new SupabaseConnector(+ makeClientSeq([{ error: null }, { error: { code: '23514', message: 'check' } }]),+ 'http://ps',+ )++ await connector.uploadData(database)++ expect(complete).toHaveBeenCalledTimes(1)+ expect(onError).toHaveBeenCalledTimes(1)+ // The already-committed PUT is excluded; only the failing PATCH diverges.+ expect(onError.mock.calls[0]?.[1]).toEqual([patchOp])+ })++ it('rethrows a retryable error without completing or surfacing', async () => {+ const onError = vi.fn()+ setUploadErrorHandler(onError)+ const { complete, database } = makeDb([putOp])+ const connector = new SupabaseConnector(+ makeClient({ error: { code: '08006', message: 'connection failure' } }),+ 'http://ps',+ )++ await expect(connector.uploadData(database)).rejects.toBeDefined()++ expect(complete).not.toHaveBeenCalled() // PowerSync will retry+ expect(onError).not.toHaveBeenCalled()+ })++ it('is a no-op when there is no pending transaction', async () => {+ const { database } = makeDb([])+ const connector = new SupabaseConnector(makeClient({ error: null }), 'http://ps')+ await expect(connector.uploadData(database)).resolves.toBeUndefined()+ })+})diff --git a/app/services/powersync/uploadReconcile.test.ts b/app/services/powersync/uploadReconcile.test.tsnew file mode 100644index 00000000..f42875f0--- /dev/null+++ b/app/services/powersync/uploadReconcile.test.ts@@ -0,0 +1,48 @@+import type { CrudEntry } from '@powersync/web'++import { describe, expect, it, vi } from 'vitest'++import { planDivergence } from '~~/services/powersync/uploadReconcile'++vi.mock('@powersync/web', () => ({+ UpdateType: { DELETE: 'DELETE', PATCH: 'PATCH', PUT: 'PUT' },+}))++function op(over: Partial<CrudEntry>): CrudEntry {+ return { id: 'a', op: 'PUT', opData: {}, table: 'trns', ...over } as unknown as CrudEntry+}++describe('planDivergence', () => {+ it('returns a no-op plan for empty input', () => {+ expect(planDivergence([])).toEqual({ needsReload: false, toRevert: [] })+ })++ it('reverts every row when all diverged ops are PUT', () => {+ const ops = [+ op({ id: 'a', op: 'PUT', table: 'trns' }),+ op({ id: 'b', op: 'PUT', table: 'wallets' }),+ ]+ expect(planDivergence(ops)).toEqual({+ needsReload: false,+ toRevert: [{ id: 'a', table: 'trns' }, { id: 'b', table: 'wallets' }],+ })+ })++ it('requires reload (reverting nothing) when a PATCH diverged', () => {+ const ops = [op({ id: 'a', op: 'PATCH', table: 'trns' })]+ expect(planDivergence(ops)).toEqual({ needsReload: true, toRevert: [] })+ })++ it('requires reload (reverting nothing) when a DELETE diverged', () => {+ const ops = [op({ id: 'a', op: 'DELETE', table: 'trns' })]+ expect(planDivergence(ops)).toEqual({ needsReload: true, toRevert: [] })+ })++ it('requires reload for a mixed PUT + PATCH batch (any non-PUT wins)', () => {+ const ops = [+ op({ id: 'a', op: 'PUT', table: 'trns' }),+ op({ id: 'b', op: 'PATCH', table: 'trns' }),+ ]+ expect(planDivergence(ops)).toEqual({ needsReload: true, toRevert: [] })+ })+})diff --git a/app/tests/e2e/auth.setup.ts b/app/tests/e2e/auth.setup.tsindex b464c579..d5caa7f1 100644--- a/app/tests/e2e/auth.setup.ts+++ b/app/tests/e2e/auth.setup.ts@@ -1,4 +1,4 @@-import { test as setup } from '@playwright/test'+import { expect, test as setup } from '@playwright/test'import path from 'node:path'import process from 'node:process'import { fileURLToPath } from 'node:url'@@ -6,28 +6,41 @@ import { fileURLToPath } from 'node:url'const dirname = path.dirname(fileURLToPath(import.meta.url))const authFile = path.join(dirname, '.auth', 'user.json')-setup('authenticate', async ({ context, page }) => {+// Defaults match the fixed user created by `pnpm test:e2e:db:seed`+// (scripts/seed-e2e-user.mjs). Local-dev only. Override via env if needed.+const email = process.env.E2E_USER_EMAIL ?? '[email protected]'+const password = process.env.E2E_USER_PASSWORD ?? 'e2e-finapp-test-pw'++setup('authenticate', async ({ page }) => {setup.setTimeout(5 * 60_000)- // Mask common automation tells before any page script runs.- // Combined with launchOptions (no --enable-automation) this gets through Google's- // basic "browser is not secure" check.- await context.addInitScript(() => {- Object.defineProperty(navigator, 'webdriver', { get: () => undefined })- Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] })- Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] })- })+ const appUrl = /\/(dashboard|categories|wallets|stat|settings)/- console.log(- '\n=== Auth setup ===\n'- + 'A browser window will open. Sign in with your real Google account.\n'- + `The session will be saved to ${path.relative(process.cwd(), authFile)} once you reach the app.\n`,- )+ if (email && password) {+ // Automated. Retry the whole goto -> fill -> submit because a cold dev server+ // can full-reload mid-flight (Vite re-optimizes deps like motion-v on first+ // visit and pushes a reload), which interrupts navigation or wipes the form.+ // Once the deps are bundled a retry lands cleanly. type-based selectors are+ // i18n-agnostic.+ await expect(async () => {+ await page.goto('/login', { waitUntil: 'domcontentloaded' })+ await page.locator('input[type="email"]').fill(email)+ await page.locator('input[type="password"]').fill(password)+ await page.locator('button[type="submit"]').click()+ await page.waitForURL(appUrl, { timeout: 15_000 })+ }).toPass({ timeout: 4 * 60_000 })+ }+ else {+ // Manual fallback: no credentials provided - sign in by hand in the window.+ console.log(+ '\n=== Auth setup ===\n'+ + 'A browser window will open. Sign in with your Supabase email and password.\n'+ + `The session will be saved to ${path.relative(process.cwd(), authFile)} once you reach the app.\n`,+ )+ await page.goto('/login')+ await page.waitForURL(appUrl, { timeout: 5 * 60_000 })+ }- await page.goto('/login')- await page.waitForURL(/\/(dashboard|categories|wallets|stat|settings)/, {- timeout: 5 * 60_000,- })await page.context().storageState({ path: authFile })console.log(`Saved auth state to ${authFile}`)diff --git a/app/tests/e2e/categories-children-real.spec.ts b/app/tests/e2e/categories-children-real.spec.tsindex 81084b08..9704d2e6 100644--- a/app/tests/e2e/categories-children-real.spec.ts+++ b/app/tests/e2e/categories-children-real.spec.ts@@ -15,7 +15,7 @@ const T = {confirm: /^(Delete|Удалить)$/,parentCategory: /^(Parent category|Родительская категория)$/,save: /^(Save|Сохранить)$/,- search: /(Search categories|Поиск категорий)/i,+ search: /(Search|Поиск)/i,selectedAny: /(\d+ selected|Выбрано:?\s*\d+)/i,}@@ -46,9 +46,10 @@ function candidateRows(page: Page) {}async function getCandidateName(row: ReturnType<Page['locator']>) {- // Each candidate row has nested divs: [checkbox, icon, [name, currently-in]].- // Grab the first .truncate (the name) only.- const nameEl = row.locator('div.truncate').first()+ // Row = [checkbox, icon, CategoriesName]. The name is a `span.truncate`; an+ // optional `div.truncate` (parent name) only renders for non-root candidates,+ // so match any `.truncate` and take the first (the name always comes first).+ const nameEl = row.locator('.truncate').first()const text = (await nameEl.textContent()) ?? ''return text.trim()}@@ -66,14 +67,21 @@ async function selectFirstNCandidates(page: Page, n: number): Promise<string[]>return picked}+// Bottom-anchored buttons (in bottom sheets / confirm dialogs) get covered by the+// Nuxt devtools container, which spans the viewport bottom in the dev server.+// `force: true` still does a coordinate click and lands on the devtools overlay,+// so use `dispatchEvent('click')` - it fires the handler directly on the element,+// independent of what overlaps it.+async function clickButton(page: Page, name: RegExp) {+ await page.getByRole('button', { name }).first().dispatchEvent('click')+}+async function applyModal(page: Page) {- // Bottom-anchored buttons sometimes get covered by the Nuxt devtools toolbar- // in the headed dev server. Force-click bypasses the actionability check.- await page.getByRole('button', { name: T.apply }).click({ force: true })+ await clickButton(page, T.apply)}async function saveCategory(page: Page) {- await page.getByRole('button', { name: T.save }).click({ force: true })+ await clickButton(page, T.save)}/**@@ -126,13 +134,13 @@ async function selectedNamesInModal(page: Page): Promise<string[]> {test.describe.configure({ timeout: 120_000 })-test.describe('Categories children — real backend', () => {+test.describe('Categories children - real backend', () => {test.use({ actionTimeout: 15_000, navigationTimeout: 30_000 })test.beforeEach(async ({ context, page }) => {if (!existsSync(authFile))test.skip(true, `Run 'pnpm test:e2e:auth' first to save real-user auth state.`)- // Hide Nuxt devtools toolbar/frame — it intercepts clicks on bottom-anchored+ // Hide Nuxt devtools toolbar/frame - it intercepts clicks on bottom-anchored// buttons (Apply / Save) inside bottom sheets.await context.addInitScript(() => {const css = `@@ -273,7 +281,7 @@ test.describe('Categories children — real backend', () => {const confirmBtn = page.getByRole('button', { name: T.confirm }).first()await expect(confirmBtn).toBeVisible({ timeout: 5_000 })- await confirmBtn.click()+ await confirmBtn.dispatchEvent('click')await saveCategory(page)await page.waitForURL((url) => {@@ -311,7 +319,7 @@ test.describe('Categories children — real backend', () => {const cancelBtn = page.getByRole('button', { name: T.cancel }).first()await expect(cancelBtn).toBeVisible({ timeout: 5_000 })- await cancelBtn.click()+ await cancelBtn.dispatchEvent('click')// Children modal stays open; selection should revert to the original set.await page.waitForTimeout(500)@@ -364,13 +372,13 @@ test.describe('Categories children — real backend', () => {await expect(page.getByText(T.childCategories).first()).toBeVisible()await page.getByText(T.parentCategory).first().click()- // Bottom sheet shows "Without parent" chip + parent candidates list.- // Click the first non-"Without parent" link inside the open sheet.+ // Bottom sheet shows a "Without parent" chip + the parent candidates list.+ // Candidates render as clickable category rows (plain divs with @click, not+ // links), so pick a seeded category by name (the click bubbles to the row).const sheet = page.locator('.bottomSheetContent').last()- const candidateLinks = sheet.locator('a, [role="link"]')- const count = await candidateLinks.count()- expect(count).toBeGreaterThan(0)- await candidateLinks.first().click()+ const candidate = sheet.getByText(/^E2E Category \d+$/).first()+ await expect(candidate).toBeVisible({ timeout: 10_000 })+ await candidate.click()await expect(page.getByText(T.childCategories)).toHaveCount(0)})diff --git a/app/vitest.config.ts b/app/vitest.config.tsindex 549e1926..ae275be3 100644--- a/app/vitest.config.ts+++ b/app/vitest.config.ts@@ -30,15 +30,6 @@ export default defineConfig({setupFiles: ['./app/test-utils/setup-store.ts'],},},- {- resolve: { alias },- test: {- environment: 'edge-runtime',- include: ['convex/**/*.test.ts'],- name: 'convex',- setupFiles: ['./convex/test_utils/setup.helper.ts'],- },- },],},})