Skip to content

Open source personal finance application

refactor: replace all 'as any' casts with proper types

Ilya Komichevf0fe1d2bd818
diff --git a/app/components/categories/CommandPalette.vue b/app/components/categories/CommandPalette.vue
index 4fd2db22..9f3d3542 100644
--- a/app/components/categories/CommandPalette.vue
+++ b/app/components/categories/CommandPalette.vue
@@ -1,8 +1,12 @@
<script setup lang="ts">
+import type { CommandPaletteItem } from '@nuxt/ui'
+
import type { CategoryId, CategoryItemWithId } from '~/components/categories/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+type CategoryCommandPaletteItem = CommandPaletteItem & CategoryItemWithId
+
const props = defineProps<{
activeItemId?: CategoryId
hide?: () => void
@@ -55,38 +59,39 @@ const cats = computed(() => {
return [adjustmentGroup, ...rootGroups]
})
-function onSelect(item: any) {
- emit('selected', (item as CategoryItemWithId).id)
+function onSelect(item: CategoryCommandPaletteItem) {
+ emit('selected', item.id)
if (props.hide)
props.hide()
}
</script>
<template>
+ <!-- @vue-ignore -->
<UCommandPalette
:placeholder="t('categories.search.placeholder')"
- :groups="(cats as any)"
+ :groups="cats"
labelKey="name"
@update:modelValue="onSelect"
>
<template #category="{ item: rawItem }">
<UiElement
- :isActive="(rawItem as any).id === props.activeItemId"
+ :isActive="(rawItem as CategoryCommandPaletteItem).id === props.activeItemId"
:lineWidth="1"
class="w-full grow"
insideClasses="min-h-[46px]"
>
<template #leftIcon>
<UiIconBase
- :color="(rawItem as any).color"
- :name="(rawItem as any).icon"
+ :color="(rawItem as CategoryCommandPaletteItem).color"
+ :name="(rawItem as CategoryCommandPaletteItem).icon"
invert
/>
</template>
<div class="grid grow">
<CategoriesName
- :category="(rawItem as any)"
+ :category="(rawItem as CategoryCommandPaletteItem)"
/>
</div>
</UiElement>
diff --git a/app/components/trnForm/Bottom.vue b/app/components/trnForm/Bottom.vue
index 9c13f35b..b55de6d3 100644
--- a/app/components/trnForm/Bottom.vue
+++ b/app/components/trnForm/Bottom.vue
@@ -93,7 +93,7 @@ onMounted(init)
:style="{ height: maxHeight }"
>
<TrnFormTrnsSlide
- :slider="sliderObj as any"
+ :slider="sliderObj"
:mainSlideIdx="1"
class="overflow-hidden px-2 pt-4 pb-6"
/>
diff --git a/app/components/trnForm/Calendar.vue b/app/components/trnForm/Calendar.vue
index f09e8d74..aa10797f 100644
--- a/app/components/trnForm/Calendar.vue
+++ b/app/components/trnForm/Calendar.vue
@@ -31,6 +31,6 @@ function onUpdate(date: CalendarDate) {
v-model="date"
:maxValue="maxDate"
class="p-3"
- @update:modelValue="onUpdate as any"
+ @update:modelValue="onUpdate"
/>
</template>
diff --git a/app/components/trnForm/Sidebar.vue b/app/components/trnForm/Sidebar.vue
index f82b357c..98d61e13 100644
--- a/app/components/trnForm/Sidebar.vue
+++ b/app/components/trnForm/Sidebar.vue
@@ -88,7 +88,7 @@ watch(isShow, async (v) => {
</UiTitleSection>
<TrnFormTrnsSlide
- :slider="sliderObj as any"
+ :slider="sliderObj"
:mainSlideIdx="0"
class="px-2 pb-6"
/>
diff --git a/app/components/trnForm/utils/formatData.test.ts b/app/components/trnForm/utils/formatData.test.ts
index 044bcf66..6f6b9410 100644
--- a/app/components/trnForm/utils/formatData.test.ts
+++ b/app/components/trnForm/utils/formatData.test.ts
@@ -137,15 +137,25 @@ tests.forEach((test) => {
describe(test.name, () => {
test.variants.forEach((variant) => {
it(variant.name, () => {
- const data = test.id === 'transactions'
+ const rawData = test.id === 'transactions'
? formatTransaction(variant.data.expect)
: formatTransfer(variant.data.expect)
- if (data)
- delete (data as any).updatedAt
- const res = variant.data.become
- if (res)
- delete (res as any).updatedAt
+ // Strip updatedAt (dynamic timestamp) before comparison
+ let data: Omit<Transaction, 'updatedAt'> | Omit<Transfer, 'updatedAt'> | false = rawData
+ if (rawData) {
+ const { updatedAt: _u, ...rest } = rawData
+ data = rest
+ }
+
+ let res: Omit<Transaction, 'updatedAt'> | Omit<Transfer, 'updatedAt'> | false
+ if (variant.data.become && typeof variant.data.become === 'object') {
+ const { updatedAt: _u, ...rest } = variant.data.become
+ res = rest
+ }
+ else {
+ res = false
+ }
expect(data).toEqual(res)
})
diff --git a/app/components/trns/getTrns.ts b/app/components/trns/getTrns.ts
index 68c32914..c3d73788 100644
--- a/app/components/trns/getTrns.ts
+++ b/app/components/trns/getTrns.ts
@@ -1,5 +1,7 @@
import type { TrnId, TrnsGetterProps } from '~/components/trns/types'
+import { TrnType } from '~/components/trns/types'
+
export function filterTrnsIds(props: TrnsGetterProps) {
if (!props.trnsIds && !props.trnsItems)
return []
@@ -25,8 +27,13 @@ export function filterTrnsIds(props: TrnsGetterProps) {
return false
if (until && trn.date > until)
return false
- if (walletsSet && !walletsSet.has((trn as any).walletId) && !walletsSet.has((trn as any).expenseWalletId) && !walletsSet.has((trn as any).incomeWalletId))
- return false
+ if (walletsSet) {
+ const matchesWallet = trn.type === TrnType.Transfer
+ ? walletsSet.has(trn.expenseWalletId) || walletsSet.has(trn.incomeWalletId)
+ : walletsSet.has(trn.walletId)
+ if (!matchesWallet)
+ return false
+ }
if (categoriesSet && !categoriesSet.has(trn.categoryId))
return false
return true
diff --git a/app/components/trns/useTrnsStore.test.ts b/app/components/trns/useTrnsStore.test.ts
index e4f6e8e3..e6c25f29 100644
--- a/app/components/trns/useTrnsStore.test.ts
+++ b/app/components/trns/useTrnsStore.test.ts
@@ -2,7 +2,7 @@ import localforage from 'localforage'
import { createPinia, setActivePinia } from 'pinia'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import type { TrnItem } from '~/components/trns/types'
+import type { Transaction, Transfer } from '~/components/trns/types'
// --- Entity-specific mocks ---
@@ -47,7 +47,7 @@ vi.mock('~/components/wallets/useWalletsStore', () => ({
const offlineHelpers = await import('~/components/offline/helpers')
vi.mock('~/components/offline/helpers', async (importOriginal) => {
- const actual = await importOriginal() as any
+ const actual = await importOriginal() as typeof import('~/components/offline/helpers')
return {
clearOfflineQueue: vi.fn(actual.clearOfflineQueue),
getAllOfflineOps: vi.fn(actual.getAllOfflineOps),
@@ -63,7 +63,7 @@ const { useTrnsStore } = await import('~/components/trns/useTrnsStore')
// --- Helpers ---
-function makeTrn(overrides: Partial<TrnItem> = {}): TrnItem {
+function makeTrn(overrides: Partial<Transaction> = {}): Transaction {
return {
amount: 100,
categoryId: 'food',
@@ -72,7 +72,21 @@ function makeTrn(overrides: Partial<TrnItem> = {}): TrnItem {
updatedAt: 1700000000000,
walletId: 'wallet1',
...overrides,
- } 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,
+ }
}
// --- Tests ---
@@ -98,7 +112,10 @@ describe('useTrnsStore', () => {
store.saveTrn({ id: 'trn1', values: trn })
expect(store.items).toHaveProperty('trn1')
- expect((store.items!.trn1 as any).amount).toBe(100)
+ const trn1 = store.items!.trn1!
+ expect(trn1.type).not.toBe(2)
+ if (trn1.type !== 2)
+ expect(trn1.amount).toBe(100)
})
it('saves to localforage', async () => {
@@ -371,7 +388,10 @@ describe('useTrnsStore', () => {
const store = useTrnsStore()
await store.initTrns()
- expect((store.items!.trn1 as any).amount).toBe(200)
+ 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 () => {
@@ -390,7 +410,7 @@ describe('useTrnsStore', () => {
describe('computeTrnItem', () => {
it('returns null when store not loaded', () => {
const store = useTrnsStore()
- store.items = false as any
+ store.items = null
expect(store.computeTrnItem('trn1')).toBeNull()
})
@@ -424,40 +444,31 @@ describe('useTrnsStore', () => {
expect(result).not.toBeNull()
expect(result!.id).toBe('trn1')
expect(result!.category).toEqual(expect.objectContaining({ name: 'Food' }))
- expect((result as any).wallet).toEqual(expect.objectContaining({ name: 'Cash' }))
+ 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: makeTrn({
- categoryId: 'transfer',
- expenseAmount: 100,
- expenseWalletId: 'wallet1',
- incomeAmount: 100,
- incomeWalletId: 'wallet1',
- type: 2,
- } as any),
+ trn1: makeTransfer(),
}
const result = store.computeTrnItem('trn1')
expect(result).not.toBeNull()
expect(result!.id).toBe('trn1')
- expect((result as any).expenseWallet).toEqual(expect.objectContaining({ name: 'Cash' }))
- expect((result as any).incomeWallet).toEqual(expect.objectContaining({ name: 'Cash' }))
+ 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', () => {
const store = useTrnsStore()
store.items = {
- trn1: makeTrn({
- categoryId: 'transfer',
- expenseAmount: 100,
- expenseWalletId: 'nonexistent',
- incomeAmount: 100,
- incomeWalletId: 'wallet1',
- type: 2,
- } as any),
+ trn1: makeTransfer({ expenseWalletId: 'nonexistent' }),
}
expect(store.computeTrnItem('trn1')).toBeNull()
@@ -466,14 +477,7 @@ describe('useTrnsStore', () => {
it('returns null when transfer income wallet missing', () => {
const store = useTrnsStore()
store.items = {
- trn1: makeTrn({
- categoryId: 'transfer',
- expenseAmount: 100,
- expenseWalletId: 'wallet1',
- incomeAmount: 100,
- incomeWalletId: 'nonexistent',
- type: 2,
- } as any),
+ trn1: makeTransfer({ incomeWalletId: 'nonexistent' }),
}
expect(store.computeTrnItem('trn1')).toBeNull()
diff --git a/app/components/trns/useTrnsStore.ts b/app/components/trns/useTrnsStore.ts
index 5cc48b81..bcae1583 100644
--- a/app/components/trns/useTrnsStore.ts
+++ b/app/components/trns/useTrnsStore.ts
@@ -18,6 +18,9 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'
import { createDebouncedPersist, handleMutationResult, isPersistBlocked, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'
import { createLogger } from '~/utils/logger'
+/** Shape returned by Convex paginated queries (has _id, _creationTime, userId + entity fields). */
+type ConvexTrnDoc = { [key: string]: unknown, _creationTime: number, _id: string, userId: string }
+
const logger = createLogger('trns')
async function fetchAllPages<T>(
@@ -119,8 +122,8 @@ export const useTrnsStore = defineStore('trns', () => {
async function fullSync(retried = false): Promise<void> {
const { api, client } = useConvexClientWithApi()
- const trns = await fetchAllPages<{ _id: string }>(client, api.trns.list, {})
- let data: Trns | null = trns.length ? convexTrnsToMap(trns as any[]) : null
+ const trns = await fetchAllPages<ConvexTrnDoc>(client, api.trns.list, {})
+ let data: Trns | null = trns.length ? convexTrnsToMap(trns) : null
// Verify local hash against server + get server timestamp
const hashResult = await client.query(api.trns.idsHash, {}) as { hash: string, serverTime: number } | null
@@ -155,7 +158,7 @@ export const useTrnsStore = defineStore('trns', () => {
// Fetch delta changes and current hash in parallel
const [changedTrns, hashResult] = await Promise.all([
- fetchAllPages<{ _id: string }>(client, api.trns.delta, { since: syncMeta.lastSyncedAt }),
+ fetchAllPages<ConvexTrnDoc>(client, api.trns.delta, { since: syncMeta.lastSyncedAt }),
client.query(api.trns.idsHash, {}) as Promise<{ hash: string, serverTime: number } | null>,
])
@@ -170,7 +173,7 @@ export const useTrnsStore = defineStore('trns', () => {
// Start with cached data and apply delta
let data: Trns = { ...cachedTrns }
if (changedTrns.length > 0) {
- const changedMap = convexTrnsToMap(changedTrns as any[])
+ const changedMap = convexTrnsToMap(changedTrns)
data = { ...data, ...changedMap }
}
@@ -258,23 +261,25 @@ export const useTrnsStore = defineStore('trns', () => {
const trnData = values.type === TrnType.Transfer
? {
...base,
- categoryId: 'transfer',
+ categoryId: 'transfer' as const,
expenseAmount: values.expenseAmount,
- expenseWalletId: values.expenseWalletId,
+ expenseWalletId: asConvexId<'wallets'>(values.expenseWalletId),
incomeAmount: values.incomeAmount,
- incomeWalletId: values.incomeWalletId,
+ incomeWalletId: asConvexId<'wallets'>(values.incomeWalletId),
}
: {
...base,
amount: values.amount,
- categoryId: values.categoryId,
- walletId: values.walletId,
+ categoryId: values.categoryId === 'adjustment'
+ ? 'adjustment' as const
+ : asConvexId<'categories'>(values.categoryId),
+ walletId: asConvexId<'wallets'>(values.walletId),
}
// Fire-and-forget mutation, cleanup on success
const mutation = isExisting
- ? client.mutation(api.trns.update, { id: asConvexId<'trns'>(id), ...trnData } as any)
- : client.mutation(api.trns.create, trnData as any)
+ ? client.mutation(api.trns.update, { id: asConvexId<'trns'>(id), ...trnData })
+ : client.mutation(api.trns.create, trnData)
return handleMutationResult({
action,
@@ -387,7 +392,7 @@ export const useTrnsStore = defineStore('trns', () => {
}
return {
- cancelPersist: () => (debouncedPersist as any).cancel?.(),
+ cancelPersist: () => (debouncedPersist as unknown as { cancel?: () => void }).cancel?.(),
computeTrnItem,
deleteTrn,
getRange,
diff --git a/app/components/user/useUserStore.test.ts b/app/components/user/useUserStore.test.ts
index 434df669..a258ed59 100644
--- a/app/components/user/useUserStore.test.ts
+++ b/app/components/user/useUserStore.test.ts
@@ -23,7 +23,9 @@ vi.stubGlobal('useNuxtApp', () => ({
$i18n: { setLocale: setLocaleMock },
}))
-const useSessionMock = vi.fn(() => ref({ data: null as any, isPending: false }))
+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 }))
vi.stubGlobal('useAuth', () => ({
signOut: vi.fn(),
useSession: useSessionMock,
@@ -99,7 +101,8 @@ describe('useUserStore', () => {
it('skips Convex mutation in demo mode', async () => {
const demoModule = await import('~/components/demo/useDemo')
const original = demoModule.useDemo
- ;(demoModule as any).useDemo = () => ({ ...original(), isDemo: { value: true } })
+ const demoWritable = demoModule as Record<string, typeof demoModule.useDemo>
+ demoWritable.useDemo = () => ({ ...original(), isDemo: ref('true') })
setActivePinia(createPinia())
const store = useUserStore()
@@ -108,7 +111,7 @@ describe('useUserStore', () => {
expect(store.baseCurrency).toBe('GBP')
expect(mutationMock).not.toHaveBeenCalled()
- ;(demoModule as any).useDemo = original
+ demoWritable.useDemo = original
})
})
@@ -147,7 +150,8 @@ describe('useUserStore', () => {
it('skips Convex mutation in demo mode', async () => {
const demoModule = await import('~/components/demo/useDemo')
const original = demoModule.useDemo
- ;(demoModule as any).useDemo = () => ({ ...original(), isDemo: { value: true } })
+ const demoWritable = demoModule as Record<string, typeof demoModule.useDemo>
+ demoWritable.useDemo = () => ({ ...original(), isDemo: ref('true') })
setActivePinia(createPinia())
const store = useUserStore()
@@ -157,7 +161,7 @@ describe('useUserStore', () => {
expect(setLocaleMock).toHaveBeenCalledWith('ru')
expect(mutationMock).not.toHaveBeenCalled()
- ;(demoModule as any).useDemo = original
+ demoWritable.useDemo = original
})
})
diff --git a/app/components/wallets/page/New.vue b/app/components/wallets/page/New.vue
index 225b04a8..88fff828 100644
--- a/app/components/wallets/page/New.vue
+++ b/app/components/wallets/page/New.vue
@@ -33,7 +33,7 @@ useHead({
<WalletsForm
:walletForm="walletForm"
@afterSave="() => router.replace('/dashboard')"
- @update="(id: keyof WalletItem, value: WalletItem[keyof WalletItem]) => (walletForm as any)[id] = value"
+ @update="(id: keyof WalletItem, value: WalletItem[keyof WalletItem]) => (walletForm as unknown as Record<keyof WalletItem, WalletItem[keyof WalletItem]>)[id] = value"
/>
</UiPage>
</template>
diff --git a/app/components/wallets/page/id/Edit.vue b/app/components/wallets/page/id/Edit.vue
index 4cfc0720..8e2b4a21 100644
--- a/app/components/wallets/page/id/Edit.vue
+++ b/app/components/wallets/page/id/Edit.vue
@@ -32,7 +32,7 @@ useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form
:walletId
:walletForm
@afterSave="() => router.replace(`/wallets/${walletId}`)"
- @update="(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) => (walletForm as any)[key] = value"
+ @update="(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) => (walletForm as unknown as Record<keyof WalletItem, WalletItem[keyof WalletItem]>)[key] = value"
/>
</UiPage>
</template>
diff --git a/app/components/wallets/useWalletsStore.ts b/app/components/wallets/useWalletsStore.ts
index 54c60eb4..180c9da6 100644
--- a/app/components/wallets/useWalletsStore.ts
+++ b/app/components/wallets/useWalletsStore.ts
@@ -213,7 +213,7 @@ export const useWalletsStore = defineStore('wallets', () => {
}
return {
- cancelPersist: () => (debouncedPersist as any).cancel?.(),
+ cancelPersist: () => (debouncedPersist as unknown as { cancel?: () => void }).cancel?.(),
currenciesUsed,
deleteWallet,
hasItems,
diff --git a/convex/migrate.ts b/convex/migrate.ts
index 1cdb849d..2078eaa4 100644
--- a/convex/migrate.ts
+++ b/convex/migrate.ts
@@ -1,5 +1,7 @@
import { v } from 'convex/values'
+import type { Id } from './_generated/dataModel'
+
import { components, internal } from './_generated/api'
import { internalAction, internalMutation } from './_generated/server'
import { addTrnsToHash, fnv1aNum, getOrCreateSyncMeta } from './trnsHash'
@@ -55,7 +57,8 @@ export const deleteAuthTablePage = internalMutation({
const field = model === 'user' ? '_id' : 'userId'
const result = await ctx.runMutation(components.betterAuth.adapter.deleteMany, {
input: {
- model: model as any,
+ // @ts-expect-error BetterAuth adapter expects specific model names but we iterate dynamically
+ model,
where: [{ field, operator: 'eq', value: userId }],
},
paginationOpts: { cursor: null, numItems: 500 },
@@ -117,7 +120,7 @@ export const insertCategories = internalMutation({
for (const { id, oldParentId } of inserts) {
if (oldParentId && idMap[oldParentId]) {
- await ctx.db.patch(id as any, { parentId: idMap[oldParentId] as any })
+ await ctx.db.patch(id as Id<'categories'>, { parentId: idMap[oldParentId] as unknown as Id<'categories'> })
}
}
@@ -137,7 +140,7 @@ export const insertTrnsBatch = internalMutation({
newIds.push(id)
}
await addTrnsToHash(ctx, userId, newIds)
- return (trns as any[]).length
+ return (trns as unknown[]).length
},
})
@@ -148,7 +151,11 @@ export const insertUserSettings = internalMutation({
userId: v.string(),
},
handler: async (ctx, args) => {
- await ctx.db.insert('userSettings', args as any)
+ await ctx.db.insert('userSettings', {
+ baseCurrency: args.baseCurrency,
+ locale: args.locale as 'en' | 'ru' | undefined,
+ userId: args.userId,
+ })
},
})