Open source personal finance application
feat: migrate old transfers to adjustment, add tests, dead code cleanup
Ilya Komichev6521a9a30bb4
diff --git a/app/assets/js/colors.js b/app/assets/js/colors.jsdeleted file mode 100644index d165be4f..00000000--- a/app/assets/js/colors.js+++ /dev/null@@ -1,156 +0,0 @@-export const allColors = [- [- '#ef9a9a',- '#e57373',- '#ef5350',- '#f44336',- '#e53935',- '#d32f2f',- '#c62828',- '#b71c1c',- '#f48fb1',- '#f06292',- '#ec407a',- '#e91e63',- '#d81b60',- '#c2185b',- '#ad1457',- '#880e4f',- '#ce93d8',- '#ba68c8',- '#ab47bc',- '#9c27b0',- '#8e24aa',- '#7b1fa2',- '#6a1b9a',- ],- [- '#b39ddb',- '#9575cd',- '#7e57c2',- '#673ab7',- '#5e35b1',- '#512da8',- '#4527a0',- ],- [- '#9fa8da',- '#7986cb',- '#5c6bc0',- '#3f51b5',- '#3949ab',- '#303f9f',- ],- [- '#90caf9',- '#64b5f6',- '#42a5f5',- '#2196f3',- '#1e88e5',- '#1976d2',- '#1565c0',- '#0d47a1',- '#81d4fa',- '#4fc3f7',- '#29b6f6',- '#03a9f4',- '#039be5',- '#0288d1',- '#0277bd',- '#01579b',- '#80deea',- '#4dd0e1',- '#26c6da',- '#00bcd4',- '#00acc1',- '#0097a7',- '#00838f',- '#006064',- '#80cbc4',- '#4db6ac',- '#26a69a',- '#009688',- '#00897b',- '#00796b',- '#00695c',- '#004d40',- '#81c784',- '#66bb6a',- '#4caf50',- '#43a047',- '#388e3c',- '#2e7d32',- '#1b5e20',- ],- [- '#aed581',- '#9ccc65',- '#8bc34a',- '#7cb342',- '#689f38',- '#558b2f',- '#33691e',- ],- [- '#dce775',- '#d4e157',- '#cddc39',- '#c0ca33',- '#afb42b',- '#9e9d24',- '#827717',- ],- [- '#ffeb3b',- '#fdd835',- '#fbc02d',- '#f9a825',- '#f57f17',- ],- [- '#ffe082',- '#ffd54f',- '#ffca28',- '#ffc107',- '#ffb300',- '#ffa000',- '#ff8f00',- '#ff6f00',- '#ffcc80',- '#ffb74d',- '#ffa726',- '#ff9800',- '#fb8c00',- '#f57c00',- '#ef6c00',- '#e65100',- '#ffab91',- '#ff8a65',- '#ff7043',- '#ff5722',- '#f4511e',- '#e64a19',- '#d84315',- '#bf360c',- '#bcaaa4',- '#a1887f',- '#8d6e63',- '#795548',- '#6d4c41',- '#5d4037',- ],- [- '#bdbdbd',- '#9e9e9e',- '#757575',- '#616161',- ],- [- '#b0bec5',- '#90a4ae',- '#78909c',- '#607d8b',- '#546e7a',- '#455a64',- ],-]diff --git a/app/components/amount/Amount.vue b/app/components/amount/Amount.vueindex 51b8136e..cca2ae4f 100644--- a/app/components/amount/Amount.vue+++ b/app/components/amount/Amount.vue@@ -16,7 +16,7 @@ export type AmountProps = {isShowSymbol?: booleanprecision?: numbertype?: MoneyTypeNumber- variant?: '2xs' | '3xl' | 'base' | 'xs' | 'sm' | 'xl'+ variant?: '2xs' | 'base' | 'xs' | 'sm' | 'xl'}const {@@ -48,7 +48,6 @@ const { baseCurrencyCode, getAmountInBaseRate } = useAmount()'text-2xs': variant === '2xs','text-xs': variant === 'xs','text-sm': variant === 'sm',- 'text-3xl': variant === '3xl','text-xl': variant === 'xl','text-base': variant === 'base',}"diff --git a/app/components/amount/getTotal.test.ts b/app/components/amount/getTotal.test.tsindex 2096e563..8d04a44e 100644--- a/app/components/amount/getTotal.test.ts+++ b/app/components/amount/getTotal.test.ts@@ -6,17 +6,12 @@ import { walletsItems } from '~~/mocks/wallets'import type { TrnId } from '~/components/trns/types'import { getTotal } from '~/components/amount/getTotal'-import { getTransferCategoriesIds } from '~/components/categories/utils'-import { mockCategories } from '~/components/categories/utils.test'--const transferCategoriesIds = getTransferCategoriesIds(mockCategories)describe('total of Transactions', () => {it('correct empty result and correct total structure', () => {const trnsIds: TrnId[] = []const total = getTotal({- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -40,7 +35,6 @@ describe('total of Transactions', () => {const total = getTotal({baseCurrencyCode,rates,- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -61,7 +55,6 @@ describe('total of Transactions', () => {const total = getTotal({baseCurrencyCode,rates,- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -85,7 +78,6 @@ describe('total of Transactions', () => {const total = getTotal({baseCurrencyCode,rates,- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -109,7 +101,6 @@ describe('total of Transactions', () => {const total = getTotal({baseCurrencyCode,rates,- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -123,19 +114,18 @@ describe('total of Transactions', () => {expect(total.sumTransfers).toEqual(0)})- it('total in Wallet Cash USD with Transfers', () => {+ it('total in Wallet Cash USD with Transfers and adjustments', () => {const walletsIds = ['walletCashUSD']const trnsIds = ['transactionIncomeWalletCashUSD1000','transactionExpenseWalletCashUSD400','transferExpenseWalletCashUSD10IncomeWalletRUB700','transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',- 'transferCategoryIncomeWalletCashUSD30',- 'transferCategoryIdExpenseWalletCashUSD30',+ 'adjustmentIncomeWalletCashUSD30',+ 'adjustmentExpenseWalletCashUSD30',]const total = getTotal({- transferCategoriesIds,trnsIds,trnsItems,walletsIds,@@ -145,22 +135,38 @@ describe('total of Transactions', () => {expect(total.income).toEqual(1000)expect(total.expense).toEqual(400)expect(total.sum).toEqual(600)- expect(total.incomeTransfers).toEqual(70)- expect(total.expenseTransfers).toEqual(40)+ expect(total.incomeTransfers).toEqual(40)+ expect(total.expenseTransfers).toEqual(10)expect(total.sumTransfers).toEqual(30)+ expect(total.adjustment).toEqual(0)})- it('total of Transfers when no Wallets provided', () => {+ it('adjustment income adds to adjustment, expense subtracts', () => {+ const trnsIds = [+ 'adjustmentIncomeWalletCashUSD200',+ 'adjustmentExpenseWalletCashUSD50',+ ]++ const total = getTotal({+ trnsIds,+ trnsItems,+ walletsItems,+ })++ expect(total.adjustment).toEqual(150)+ expect(total.income).toEqual(0)+ expect(total.expense).toEqual(0)+ expect(total.sum).toEqual(0)+ })++ it('total of Transfers when no Wallets filter provided', () => {const trnsIds = ['transactionIncomeWalletCashUSD1000','transactionExpenseWalletCashUSD400','transferExpenseWalletCreditUSD40IncomeWalletCashUSD40',- 'transferCategoryIncomeWalletCashUSD30',- 'transferCategoryIdExpenseWalletCashUSD30',]const total = getTotal({- transferCategoriesIds,trnsIds,trnsItems,walletsItems,@@ -169,8 +175,8 @@ describe('total of Transactions', () => {expect(total.income).toEqual(1000)expect(total.expense).toEqual(400)expect(total.sum).toEqual(600)- expect(total.incomeTransfers).toEqual(70)- expect(total.expenseTransfers).toEqual(70)+ expect(total.incomeTransfers).toEqual(40)+ expect(total.expenseTransfers).toEqual(40)expect(total.sumTransfers).toEqual(0)})})diff --git a/app/components/amount/getTotal.ts b/app/components/amount/getTotal.tsindex 99ab57f4..edde0266 100644--- a/app/components/amount/getTotal.ts+++ b/app/components/amount/getTotal.ts@@ -1,4 +1,3 @@-import type { CategoryId } from '~/components/categories/types'import type { CurrencyCode, Rates } from '~/components/currencies/types'import type { TrnId, TrnItem } from '~/components/trns/types'import type { WalletId, WalletItem } from '~/components/wallets/types'@@ -28,15 +27,12 @@ export function getAmountInRate({type TotalProps = {baseCurrencyCode?: stringrates?: Rates- transferCategoriesIds?: CategoryId[]trnsIds?: TrnId[]trnsItems: Record<TrnId, TrnItem>walletsIds?: WalletId[]walletsItems: Record<WalletId, WalletItem>}-export type DateString = string-export type TotalReturns = {adjustment: numberexpense: number@@ -48,7 +44,7 @@ export type TotalReturns = {}export function getTotal(props: TotalProps): TotalReturns {- const { baseCurrencyCode, rates, transferCategoriesIds, trnsIds, trnsItems, walletsIds, walletsItems } = props+ const { baseCurrencyCode, rates, trnsIds, trnsItems, walletsIds, walletsItems } = propsfunction getAmount(amount: number, currencyCode: CurrencyCode) {return getAmountInRate({@@ -75,31 +71,20 @@ export function getTotal(props: TotalProps): TotalReturns {// Adjustment: affects wallet balance but not income/expense statisticsif (trn.categoryId === 'adjustment') {const wallet = walletsItems[trn.walletId]- adjustment += getAmount(trn.amount, wallet?.currency || 'USD')+ const amount = getAmount(trn.amount, wallet?.currency || 'USD')+ adjustment += trn.type === TrnType.Income ? amount : -amountcontinue}- const isTransferCategory = transferCategoriesIds?.includes(trn.categoryId || '')const wallet = walletsItems[trn.walletId]const sum = getAmount(trn.amount, wallet?.currency || 'USD')- // Income- if (trn.type === TrnType.Income) {- if (isTransferCategory)- incomeTransfers += sum- else- income += sum- }-- // Expense- if (trn.type === TrnType.Expense) {- if (isTransferCategory)- expenseTransfers += sum- else- expense += sum- }+ if (trn.type === TrnType.Income)+ income += sum+ else+ expense += sum}- // Transfer v2+ // Transferelse if (trn.type === TrnType.Transfer && 'incomeWalletId' in trn) {const incomeWallet = walletsItems[trn.incomeWalletId]const expenseWallet = walletsItems[trn.expenseWalletId]diff --git a/app/components/amount/useAmount.ts b/app/components/amount/useAmount.tsindex 7fb84d4a..eec816f0 100644--- a/app/components/amount/useAmount.ts+++ b/app/components/amount/useAmount.ts@@ -4,7 +4,6 @@ import type { TrnId } from '~/components/trns/types'import { getAmountInRate, getTotal } from '~/components/amount/getTotal'import { formatAmount } from '~/components/amount/utils'-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { useWalletsStore } from '~/components/wallets/useWalletsStore'@@ -12,7 +11,6 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'export function useAmount() {const currenciesStore = useCurrenciesStore()const walletsStore = useWalletsStore()- const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()function getAmountInBaseRate({ amount, currencyCode, noFormat }: {@@ -42,7 +40,6 @@ export function useAmount() {return getTotal({baseCurrencyCode: currenciesStore.base,rates: currenciesStore.rates,- transferCategoriesIds: categoriesStore.transferCategoriesIds,trnsIds,trnsItems: trnsStore.items ?? {},walletsIds: Object.keys(walletsStore.items ?? {}),@@ -52,7 +49,6 @@ export function useAmount() {return {baseCurrencyCode,- formatAmount,getAmountInBaseRate,getTotalOfTrnsIds,}diff --git a/app/components/bottomSheet/BottomSheet.vue b/app/components/bottomSheet/BottomSheet.vueindex a22a600a..75b0ff33 100644--- a/app/components/bottomSheet/BottomSheet.vue+++ b/app/components/bottomSheet/BottomSheet.vue@@ -4,7 +4,6 @@ import { useBottomSheetDrag } from './useBottomSheetDrag'const props = defineProps<{drugClassesCustom?: stringdrugStyle?: Record<string, string>- isHideOverflow?: booleanisShow?: boolean}>()@@ -14,7 +13,6 @@ const emit = defineEmits<{// Settingsconst settings = {- debug: true,pixelOffsetToStartClosing: 20,pixelsNeedToDrugForClose: 60,}@@ -23,7 +21,6 @@ const settings = {const drug = ref<HTMLElement | null>(null)const containerRef = ref<HTMLElement | null>(null)const handlerRef = ref<HTMLElement | null>(null)-const contentInside = ref<HTMLElement | null>(null)const { height: drugHeight } = useElementSize(drug)const { height: windowHeight } = useWindowSize()@@ -40,7 +37,6 @@ const {wrapClasses,} = useBottomSheetDrag({containerRef,- contentInside,drug,drugStyle: toRef(() => props.drugStyle),emit,@@ -98,12 +94,11 @@ const drugClasses = computed(() => [<template><divref="containerRef"- :class="[wrapClasses, { 'pointer-events-none': isHideOverflow }]"+ :class="wrapClasses"class="fixed inset-0 z-50 size-full overflow-hidden select-none"><!-- Overlay --><div- v-if="!isHideOverflow":class="overflowClasses":style="overlayStyles"class="absolute inset-0 z-10 size-full bg-(--overlay)"diff --git a/app/components/bottomSheet/BottomSheetOrDropdown.vue b/app/components/bottomSheet/BottomSheetOrDropdown.vueindex 6d045677..b30cfa91 100644--- a/app/components/bottomSheet/BottomSheetOrDropdown.vue+++ b/app/components/bottomSheet/BottomSheetOrDropdown.vue@@ -4,7 +4,6 @@ const props = defineProps<{drugClassesCustom?: stringisOpen?: booleanisShowCloseBtn?: boolean- placement?: stringtitle?: string}>()@@ -25,9 +24,6 @@ const open = ref(false)<UPopoverv-if="isLaptop"v-model:open="open"- :popper="{- placement: props.placement ?? 'bottom-start',- }":content="{align: 'center',side: 'bottom',diff --git a/app/components/bottomSheet/useBottomSheetDrag.ts b/app/components/bottomSheet/useBottomSheetDrag.tsindex eb3af84f..8e2fc2d0 100644--- a/app/components/bottomSheet/useBottomSheetDrag.ts+++ b/app/components/bottomSheet/useBottomSheetDrag.ts@@ -8,13 +8,11 @@ const INIT_DELAY_MS = 10type UseBottomSheetDragParams = {containerRef: Ref<HTMLElement | null>- contentInside: Ref<HTMLElement | null>drug: Ref<HTMLElement | null>drugStyle: Ref<Record<string, string> | undefined>emit: (event: 'closed') => voidhandlerRef: Ref<HTMLElement | null>settings: {- debug: booleanpixelOffsetToStartClosing: numberpixelsNeedToDrugForClose: number}@@ -22,7 +20,6 @@ type UseBottomSheetDragParams = {export function useBottomSheetDrag({containerRef,- contentInside,drug,drugStyle,emit,@@ -83,17 +80,6 @@ export function useBottomSheetDrag({)})- /**- * Debug- */- const debug = ref({- diffHeight: computed(() => diffHeight.value),- diffHeightWithDebounce: computed(() => diffHeightWithDebounce.value),- direction: computed(() => direction.value),- nextCurrentY: computed(() => nextCurrentY.value),- status: 'standby',- })-/*** Overlay Opacity*/@@ -206,29 +192,6 @@ export function useBottomSheetDrag({const isHasScroll = contentHasScroll(event)- const bodyHeight = document.querySelector('body')?.clientHeight ?? 0- const contentInsideHeight = contentInside.value?.clientHeight ?? 0- const drugHeight = drug.value?.clientHeight ?? 0-- if (- isDragging.value- && drug.value- && drugHeight < contentInsideHeight- && drugHeight + EDGE_PADDING < bodyHeight- ) {- drug.value- ?.querySelector('.scrollerBlock')- ?.classList- .add('pointer-events-none')- drug.value.style.height = `${initialHeight.value - nextCurrentY.value}px`- }- else {- drug.value- ?.querySelector('.scrollerBlock')- ?.classList- .remove('pointer-events-none')- }-if (isHasScroll && !isHandler.value) {isDragging.value = falseinitialY.value = 0@@ -238,12 +201,6 @@ export function useBottomSheetDrag({if (isDragging.value)clientY.value = getClientY(event)-- if (settings.debug) {- debug.value.status = nextCurrentY.value >= settings.pixelsNeedToDrugForClose && direction.value === 'down'- ? 'will close'- : 'will open'- }}/**@@ -253,22 +210,6 @@ export function useBottomSheetDrag({if (disabled.value || !isDragging.value)return- const bodyHeight = document.querySelector('body')?.clientHeight ?? 0- const contentInsideHeight = contentInside.value?.clientHeight ?? 0- const drugHeight = drug.value?.clientHeight ?? 0-- if (direction.value === 'up' && nextCurrentY.value < 0) {- await nextTick()- if (- isDragging.value- && drug.value- && drugHeight < contentInsideHeight- && drugHeight + EDGE_PADDING < bodyHeight- ) {- drug.value.style.height = `${bodyHeight - EDGE_PADDING}px`- }- }-const isNeedClose= nextCurrentY.value >= settings.pixelsNeedToDrugForClose&& direction.value === 'down'@@ -396,16 +337,10 @@ export function useBottomSheetDrag({}return {- // Stateclose,- debug,- direction,- disabled,drugStyles,- // Functionsinit,isDragging,- open,opened,// Computed classesdiff --git a/app/components/categories/CommandPalette.vue b/app/components/categories/CommandPalette.vueindex f90df96b..ad006b8d 100644--- a/app/components/categories/CommandPalette.vue+++ b/app/components/categories/CommandPalette.vue@@ -9,9 +9,6 @@ const props = defineProps<{}>()const emit = defineEmits<{- clickParent: [id: CategoryId]- close: []- filter: [id: CategoryId]selected: [id: CategoryId]}>()@@ -61,7 +58,6 @@ const cats = computed(() => {function onSelect(item: CategoryItemWithId) {emit('selected', item.id)- emit('close')if (props.hide)props.hide()}@@ -91,7 +87,6 @@ function onSelect(item: CategoryItemWithId) {<div class="grid grow"><CategoriesName- :alt="item.alt":category="item"/></div>diff --git a/app/components/categories/Form.vue b/app/components/categories/Form.vueindex e4e9b023..d0f5e05b 100644--- a/app/components/categories/Form.vue+++ b/app/components/categories/Form.vue@@ -324,7 +324,6 @@ async function onSave() {:activeItemId="props.categoryForm.parentId":categoriesItemProps="{ class: 'group' }":ids="categoriesStore.categoriesForBeParent.filter(id => id !== categoryId)"- :slider="() => ({})"class="!gap-x-1"@click="id => onParentSelect(id, close)"/>diff --git a/app/components/categories/Item.vue b/app/components/categories/Item.vueindex 73923856..a9e346fd 100644--- a/app/components/categories/Item.vue+++ b/app/components/categories/Item.vue@@ -11,10 +11,8 @@ export type CategoryItemProps = {class?: stringcontextMenuItems?: any[][]insideClasses?: string- isShowDots?: booleanisShowParent?: booleanlineWidth?: number- slider?: object}const props = defineProps<CategoryItemProps>()diff --git a/app/components/categories/List.vue b/app/components/categories/List.vueindex e9487ec4..23b4ae09 100644--- a/app/components/categories/List.vue+++ b/app/components/categories/List.vue@@ -10,12 +10,10 @@ const props = defineProps<{getContextMenuItems?: (categoryId: CategoryId) => any[][] | undefinedids: CategoryId[]insideClasses?: string- slider?: object}>()const emit = defineEmits<{click: [id: CategoryId]- clickIcon: [id: CategoryId]}>()const categoriesStore = useCategoriesStore()@@ -30,13 +28,10 @@ const categoriesStore = useCategoriesStore():category="categoriesStore.items[categoryId]":categoryId="categoryId":contextMenuItems="props.getContextMenuItems?.(categoryId)"- :slider="slider":insideClasses="props.insideClasses":lineWidth="1"- isShowDotsv-bind="categoriesItemProps"@click="emit('click', categoryId)"- @filter="emit('clickIcon', categoryId)"/></div></template>diff --git a/app/components/categories/SelectorGrid.vue b/app/components/categories/SelectorGrid.vueindex 62424407..7cd4179f 100644--- a/app/components/categories/SelectorGrid.vue+++ b/app/components/categories/SelectorGrid.vue@@ -5,14 +5,10 @@ import { useCategoriesStore } from '~/components/categories/useCategoriesStore'const props = defineProps<{activeItemId?: CategoryId- hide?: () => voidids: CategoryId[]}>()const emit = defineEmits<{- clickParent: [id: CategoryId]- close: []- filter: [id: CategoryId]selected: [id: CategoryId]}>()@@ -20,19 +16,10 @@ const categoriesStore = useCategoriesStore()const itemClasses = 'bg-item-3 rounded-sm'function select(id: CategoryId) {- if (categoriesStore.hasChildren(id)) {- emit('clickParent', id)+ if (categoriesStore.hasChildren(id))return- }emit('selected', id)- emit('close')- if (props.hide)- props.hide()-}--function onFilter(id: CategoryId) {- emit('filter', id)}</script>@@ -48,7 +35,6 @@ function onFilter(id: CategoryId) {isShowParentalt@click="select(categoryId)"- @filter.stop="onFilter(categoryId)"/></div></template>diff --git a/app/components/categories/SelectorTree.vue b/app/components/categories/SelectorTree.vueindex 2bd16035..3d345cd4 100644--- a/app/components/categories/SelectorTree.vue+++ b/app/components/categories/SelectorTree.vue@@ -4,13 +4,10 @@ import type { CategoryId } from '~/components/categories/types'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'const props = defineProps<{- hide?: () => voidselectedIds?: CategoryId[]}>()const emit = defineEmits<{- close: []- filter: [id: CategoryId]selected: [id: CategoryId]setCategories: [ids: CategoryId[]]}>()@@ -30,9 +27,6 @@ function select(categoryId: CategoryId, isForce: boolean) {}emit('selected', categoryId)- emit('close')- if (props.hide)- props.hide()}function onFilter(id: CategoryId) {diff --git a/app/components/categories/StatPage.vue b/app/components/categories/StatPage.vueindex 6411c31b..df6b2110 100644--- a/app/components/categories/StatPage.vue+++ b/app/components/categories/StatPage.vue@@ -82,8 +82,6 @@ useHead({ title: category.value?.name }):filter="{isShowCategories: false,isShowWallets: true,- isShow: true,- isShowSelected: filter.isShow?.value && filter.categoriesIds.value.length > 0,}":config="{isShowWallets: true,@@ -98,7 +96,7 @@ useHead({ title: category.value?.name })<template #popover><UiHeaderLink- v-if="!categoriesStore.transferCategoriesIds.includes(categoryId)"+ v-if="categoryId !== 'transfer'"icon="lucide:pencil"@click="router.push(`/categories/${categoryId}/edit`)">diff --git a/app/components/categories/page/List.vue b/app/components/categories/page/List.vueindex 42841fa6..a974bfd9 100644--- a/app/components/categories/page/List.vue+++ b/app/components/categories/page/List.vue@@ -4,6 +4,7 @@ import { useStorage } from '@vueuse/core'import type { CategoryId } from '~/components/categories/types'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'+import { useCategoryContextMenu } from '~/components/categories/useCategoryContextMenu'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { showErrorToast, showSuccessToast } from '~/composables/useStoreSync'@@ -67,25 +68,9 @@ async function onDeleteConfirm() {}, 300)}-function getContextMenuItems(categoryId: CategoryId) {- if (categoriesStore.transferCategoriesIds.includes(categoryId))- return undefined-- return [[- {- icon: 'lucide:pencil',- label: t('base.edit'),- onSelect: () => router.push(`/categories/${categoryId}/edit`),- },- ], [- {- color: 'error' as const,- icon: 'lucide:trash-2',- label: t('base.delete'),- onSelect: () => onClickDelete(categoryId),- },- ]]-}+const { getCategoryContextMenuItems } = useCategoryContextMenu({+ onDelete: categoryId => onClickDelete(categoryId),+})</script><template>@@ -136,7 +121,7 @@ function getContextMenuItems(categoryId: CategoryId) {:class="{'grid gap-1.5 @sm:grid-cols-2 @2xl/page:grid-cols-3': categoriesView === 'grid',}"- :getContextMenuItems="getContextMenuItems"+ :getContextMenuItems="getCategoryContextMenuItems":insideClasses="categoriesView === 'grid' ? 'bg-item-2' : ''"@click="(categoryId: CategoryId) => router.push(`/categories/${categoryId}`)"/>diff --git a/app/components/categories/page/id/Index.vue b/app/components/categories/page/id/Index.vueindex 64fd64b0..8014b9f7 100644--- a/app/components/categories/page/id/Index.vue+++ b/app/components/categories/page/id/Index.vue@@ -141,7 +141,6 @@ const categoriesIds = computed(() => categoriesStore.getChildrenIds(categoryId.visShowCategories: true,}":filter="{- isShow: true,isShowWallets: true,}">@@ -160,7 +159,7 @@ const categoriesIds = computed(() => categoriesStore.getChildrenIds(categoryId.v</template><template- v-if="!categoriesStore.transferCategoriesIds.includes(categoryId)"+ v-if="categoryId !== 'transfer'"#popover="{ close }"><UiHeaderLinkdiff --git a/app/components/categories/useCategoriesStore.test.ts b/app/components/categories/useCategoriesStore.test.tsindex 89615950..8ed0d0eb 100644--- a/app/components/categories/useCategoriesStore.test.ts+++ b/app/components/categories/useCategoriesStore.test.ts@@ -1,32 +1,10 @@+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'-// --- Mocks -----const localforageStore = new Map<string, any>()-vi.mock('localforage', () => ({- default: {- getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),- removeItem: vi.fn((key: string) => {- localforageStore.delete(key)- return Promise.resolve()- }),- setItem: vi.fn((key: string, value: any) => {- localforageStore.set(key, value)- return Promise.resolve()- }),- },-}))--vi.mock('@vueuse/core', () => ({- useDebounceFn: (fn: (...args: any[]) => any) => fn,-}))--vi.mock('vue-deepunref', () => ({- deepUnref: (v: any) => v,-}))+// --- Entity-specific mocks ---vi.mock('~~/services/convex/api', () => ({convexCategoriesToMap: (v: any) => v,@@ -35,27 +13,11 @@ vi.mock('~~/services/convex/api', () => ({vi.mock('~/components/categories/utils', () => ({compareCategoriesByParentAndName: () => 0,getTransactibleCategoriesIds: () => [],- getTransferCategoriesIds: () => ['transfer'],}))const mutationMock = vi.fn(() => Promise.resolve())const onUpdateMock = vi.fn()-vi.stubGlobal('useConvexClient', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,-}))-vi.stubGlobal('useConvexClientComposable', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,-}))-vi.stubGlobal('asConvexId', (id: string) => id)-vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))-vi.stubGlobal('useConvexApi', () => ({- api: {- categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },- },-}))vi.stubGlobal('useConvexClientWithApi', () => ({api: {categories: { create: 'categories.create', list: 'categories.list', remove: 'categories.remove', update: 'categories.update', updateWithChildren: 'categories.updateWithChildren' },@@ -66,22 +28,6 @@ vi.stubGlobal('useConvexClientWithApi', () => ({},}))-const toastAddMock = vi.fn()-vi.stubGlobal('useToast', () => ({ add: toastAddMock }))-vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))-vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))-vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))--vi.mock('~/assets/js/emo', () => ({- errorEmo: ['π€·ββοΈ'],- random: (items: any[]) => items[0],-}))--vi.stubGlobal('defineStore', (await import('pinia')).defineStore)-const { computed, shallowRef } = await import('vue')-vi.stubGlobal('shallowRef', shallowRef)-vi.stubGlobal('computed', computed)-const removeTrnsFromStoreMock = vi.fn()const deleteTrnsByIdsMock = vi.fn()vi.mock('~/components/trns/useTrnsStore', () => ({@@ -93,16 +39,6 @@ vi.mock('~/components/trns/useTrnsStore', () => ({}),}))-vi.mock('~/components/demo/useDemo', () => ({- useDemo: () => ({- isDemo: { value: false },- }),-}))--vi.mock('~/components/offline/replay', () => ({- isReplaying: () => false,-}))-const offlineHelpers = await import('~/components/offline/helpers')vi.mock('~/components/offline/helpers', async (importOriginal) => {const actual = await importOriginal() as any@@ -135,9 +71,9 @@ function makeCategory(overrides: Partial<CategoryItem> = {}): CategoryItem {// --- Tests ---describe('useCategoriesStore', () => {- beforeEach(() => {+ beforeEach(async () => {setActivePinia(createPinia())- localforageStore.clear()+ await localforage.clear()vi.clearAllMocks()mutationMock.mockReturnValue(Promise.resolve())})@@ -160,7 +96,7 @@ describe('useCategoriesStore', () => {expect(store.items.c1.name).toBe('Food')})- it('saves to localforage', () => {+ it('saves to localforage', async () => {const store = useCategoriesStore()store.saveCategory({@@ -169,7 +105,8 @@ describe('useCategoriesStore', () => {values: makeCategory(),})- expect(localforageStore.get('finapp.categories')).toHaveProperty('c1')+ const saved = await localforage.getItem<any>('finapp.categories')+ expect(saved).toHaveProperty('c1')})it('pushes to offline queue immediately', () => {@@ -304,6 +241,7 @@ describe('useCategoriesStore', () => {})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()@@ -397,6 +335,7 @@ describe('useCategoriesStore', () => {})it('shows toast on delete mutation failure', async () => {+ const { toastAddMock } = await import('~/test-utils/setup-store')mutationMock.mockReturnValue(Promise.reject(new Error('Server error')))const store = useCategoriesStore()store.items = { ...store.items, c1: makeCategory() }diff --git a/app/components/categories/useCategoriesStore.ts b/app/components/categories/useCategoriesStore.tsindex 60282c3c..437b6418 100644--- a/app/components/categories/useCategoriesStore.ts+++ b/app/components/categories/useCategoriesStore.ts@@ -4,7 +4,7 @@ import type { AddCategoryParams, Categories, CategoryId, CategoryItem } from '~/import type { TrnId } from '~/components/trns/types'import type { RemapInfo } from '~/composables/useStoreSync'-import { compareCategoriesByParentAndName, getTransactibleCategoriesIds, getTransferCategoriesIds } from '~/components/categories/utils'+import { compareCategoriesByParentAndName, getTransactibleCategoriesIds } from '~/components/categories/utils'import { useDemo } from '~/components/demo/useDemo'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { TrnType } from '~/components/trns/types'@@ -51,8 +51,6 @@ type CategoriesStore = {recentCategoriesIds: ComputedRef<CategoryId[]>saveCategory: (params: AddCategoryParams) => Promise<RemapInfo | void> | voidsetCategories: (values: Categories | null) => void- transactibleIds: ComputedRef<CategoryId[]>- transferCategoriesIds: ComputedRef<CategoryId[]>}const logger = createLogger('categories')@@ -66,36 +64,27 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreObject.keys(items.value).some(id => id !== 'transfer' && id !== 'adjustment'),)- const transferCategoriesIds = computed(() => getTransferCategoriesIds(items.value))-- const categoriesIds = computed(() => {- if (!items.value)- return []-- return Object.keys(items.value)- })+ const categoriesIds = computed(() => Object.keys(items.value))const categoriesRootIds = computed(() => {- if (!hasItems.value || !items.value)+ if (!hasItems.value)return []- const transferIds = new Set(transferCategoriesIds.value)return Object.keys(items.value)- .filter(id => items.value?.[id]?.parentId === 0 && !transferIds.has(id) && id !== 'adjustment')+ .filter(id => items.value?.[id]?.parentId === 0 && id !== 'transfer' && id !== 'adjustment').sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))})const categoriesForBeParent = computed(() => {- if (!hasItems.value || !items.value)+ if (!hasItems.value)return []const usedCategoryIds = new Set(Object.values(trnsStore.items ?? {}).map(trn => trn.categoryId),)- const transferIds = new Set(transferCategoriesIds.value)return categoriesRootIds.value.filter((id: CategoryId) =>- !usedCategoryIds.has(id) && !transferIds.has(id),+ !usedCategoryIds.has(id) && id !== 'transfer',)})@@ -127,7 +116,6 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStoreconst trnsItems = trnsStore.itemsconst maxCategories = Math.min(categoriesIds.value.length, 16)- const transferIds = new Set(transferCategoriesIds.value)const favoriteIds = new Set(favoriteCategoriesIds.value)// Track most recent date per category (single pass)@@ -151,7 +139,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStorereturn accconst category = items.value[categoryId]- if (!category || !category.showInLastUsed || transferIds.has(categoryId) || favoriteIds.has(categoryId))+ if (!category || !category.showInLastUsed || categoryId === 'transfer' || favoriteIds.has(categoryId))return accacc.push(categoryId)@@ -163,9 +151,8 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore})const categoriesIdsForTrnValues = computed<CategoryId[]>(() => {- const transferIds = new Set(transferCategoriesIds.value)return categoriesIds.value.filter((id) => {- if (transferIds.has(id))+ if (id === 'transfer')return falsereturn !items.value[id]?.childIds?.length})@@ -363,7 +350,6 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStorereturn {cancelPersist: () => debouncedPersist.cancel?.(),categoriesForBeParent,- categoriesIds,categoriesIdsForTrnValues,categoriesRootIds,deleteCategory,@@ -379,7 +365,5 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStorerecentCategoriesIds,saveCategory,setCategories,- transactibleIds,- transferCategoriesIds,}})diff --git a/app/components/categories/useCategoryContextMenu.ts b/app/components/categories/useCategoryContextMenu.tsnew file mode 100644index 00000000..342c3723--- /dev/null+++ b/app/components/categories/useCategoryContextMenu.ts@@ -0,0 +1,31 @@+import type { CategoryId } from '~/components/categories/types'++export function useCategoryContextMenu(options?: {+ onDelete?: (categoryId: CategoryId) => void+}) {+ const { t } = useI18n()+ const router = useRouter()++ function getCategoryContextMenuItems(categoryId: CategoryId) {+ if (categoryId === 'transfer')+ return undefined++ const editGroup = [{+ icon: 'lucide:pencil',+ label: t('base.edit'),+ onSelect: () => router.push(`/categories/${categoryId}/edit`),+ }]++ if (!options?.onDelete)+ return [editGroup]++ return [editGroup, [{+ color: 'error' as const,+ icon: 'lucide:trash-2',+ label: t('base.delete'),+ onSelect: () => options.onDelete!(categoryId),+ }]]+ }++ return { getCategoryContextMenuItems }+}diff --git a/app/components/categories/utils.test.ts b/app/components/categories/utils.test.tsindex 79f9065b..5a36562d 100644--- a/app/components/categories/utils.test.ts+++ b/app/components/categories/utils.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import type { Categories } from '~/components/categories/types'-import { getTransactibleCategoriesIds, getTransferCategoriesIds } from '~/components/categories/utils'+import { getTransactibleCategoriesIds } from '~/components/categories/utils'export const mockCategories: Categories = {child1: {@@ -117,47 +117,3 @@ describe('getTransactibleCategoriesIds', () => {expect(result).toEqual(['241120_7fxrno'])})})--describe('getTransferCategoriesIds', () => {- it('returns only the reserved transfer ID', () => {- const result = getTransferCategoriesIds(mockCategories)- expect(result).toEqual(['transfer'])- })-- it('does not match user categories named "transfer" or "ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄"', () => {- const items: Categories = {- myTransfer: {- color: '#000',- icon: 'mdi:repeat',- name: 'transfer',- parentId: 0,- },- transfer: {- color: 'var(--ui-primary)',- icon: 'mdi:repeat',- name: 'Transfer',- parentId: 0,- },- ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄: {- color: '#000',- icon: 'mdi:repeat',- name: 'ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄',- parentId: 0,- },- }- const result = getTransferCategoriesIds(items)- expect(result).toEqual(['transfer'])- })-- it('empty categories object', () => {- // @ts-expect-error for test- const result = getTransferCategoriesIds({})- expect(result).toEqual([])- })-- it('undefined categories', () => {- // @ts-expect-error for test- const result = getTransferCategoriesIds(undefined)- expect(result).toEqual([])- })-})diff --git a/app/components/categories/utils.ts b/app/components/categories/utils.tsindex a820b97b..7abdfc70 100644--- a/app/components/categories/utils.ts+++ b/app/components/categories/utils.ts@@ -23,13 +23,6 @@ export function getTransactibleCategoriesIds(items: Categories, ids?: CategoryIdreturn result}-export function getTransferCategoriesIds(items: Categories): CategoryId[] {- if (!items?.transfer)- return []-- return ['transfer']-}-export function getParentCategoryIdOrReturnSame(items: Categories, categoryId: CategoryId): CategoryId {const category = items[categoryId]if (!category || category.parentId === 0)diff --git a/app/components/color/colors.ts b/app/components/color/colors.tsindex 15eeb8dd..70503afd 100644--- a/app/components/color/colors.ts+++ b/app/components/color/colors.ts@@ -1,5 +1,5 @@/* eslint-disable perfectionist/sort-objects */-export const colors = {+const colors = {slate: {50: '#f8fafc',100: '#f1f5f9',diff --git a/app/components/currencies/useCurrenciesStore.ts b/app/components/currencies/useCurrenciesStore.tsindex 3fa7bc3c..fbc2a8a6 100644--- a/app/components/currencies/useCurrenciesStore.ts+++ b/app/components/currencies/useCurrenciesStore.ts@@ -3,7 +3,6 @@ import { defineStore } from 'pinia'import type { Rates } from '~/components/currencies/types'-import { currencies as allCurrencies } from '~/components/currencies/currencies'import { STORAGE_KEYS } from '~/components/offline/storageKeys'import { useUserStore } from '~/components/user/useUserStore'import { isPersistBlocked } from '~/composables/useStoreSync'@@ -11,8 +10,6 @@ import { createLogger } from '~/utils/logger'const logger = createLogger('currencies')-export const currencies = allCurrencies-export const useCurrenciesStore = defineStore('currencies', () => {const userStore = useUserStore()diff --git a/app/components/date/LinkItemNoBg.vue b/app/components/date/LinkItemNoBg.vueindex 0b5ec00b..36023f47 100644--- a/app/components/date/LinkItemNoBg.vue+++ b/app/components/date/LinkItemNoBg.vue@@ -2,9 +2,6 @@const props = defineProps<{isActive?: boolean}>()-const emit = defineEmits<{- click: [e: Event]-}>()</script><template>@@ -12,7 +9,6 @@ const emit = defineEmits<{:class="cn('flex min-h-[32px] items-center justify-center rounded-full px-1 text-xs leading-none text-nowrap text-(--ui-text)',props.isActive && 'text-primary bg-(--item-5)',)"- @click="(e: Event) => emit('click', e)"><slot /></div>diff --git a/app/components/date/Ranges.vue b/app/components/date/Ranges.vueindex a2f3a4c7..e187fed5 100644--- a/app/components/date/Ranges.vue+++ b/app/components/date/Ranges.vue@@ -3,7 +3,6 @@ import type { DateLinkItemProps } from '~/components/date/LinkItem.vue'import type { IntervalGroupedLabel, StatDateProvider } from '~/components/date/types'const props = defineProps<{- isShowMaxRange?: booleanisShowRangeAdjust?: booleanitemProps?: Partial<DateLinkItemProps>statDate: StatDateProviderdiff --git a/app/components/date/useDateFormats.ts b/app/components/date/useDateFormats.tsindex b09aa7cc..4123f3ad 100644--- a/app/components/date/useDateFormats.ts+++ b/app/components/date/useDateFormats.ts@@ -38,7 +38,6 @@ export function useDateFormats() {}case 'trnItem':- default:return formatDateToStringWithLast({ by: 'day', duration: 1, end: date, start: date, type: 'start' })}}diff --git a/app/components/date/useStatDate.ts b/app/components/date/useStatDate.tsindex 9a443de8..c3f0a68e 100644--- a/app/components/date/useStatDate.ts+++ b/app/components/date/useStatDate.ts@@ -198,7 +198,6 @@ export function useStatDate({return {addInterval,delInterval,- getIntervalsInRange,intervalsInRange,maxRange,minusRange,diff --git a/app/components/layout/Sidebar.vue b/app/components/layout/Sidebar.vueindex 63cffb4e..bcb5c622 100644--- a/app/components/layout/Sidebar.vue+++ b/app/components/layout/Sidebar.vue@@ -1,8 +1,11 @@<script setup lang="ts">import { useDemo } from '~/components/demo/useDemo'import { useUserStore } from '~/components/user/useUserStore'+import { useWalletContextMenu } from '~/components/wallets/useWalletContextMenu'import { useWalletsStore } from '~/components/wallets/useWalletsStore'+import type { WalletId } from '../wallets/types'+const props = defineProps<{isShowSidebar?: boolean}>()@@ -18,6 +21,7 @@ const { width } = useWindowSize()const walletsStore = useWalletsStore()const isShowLogoMenu = ref(false)+const { getWalletContextMenuItems } = useWalletContextMenu()</script><template>@@ -85,6 +89,7 @@ const isShowLogoMenu = ref(false)v-for="(walletItem, walletId) in walletsItemsLimited":key="walletId":activeItemId="(route.params.id as string)"+ :contextMenuItems="getWalletContextMenuItems(walletId as WalletId)":lineWidth="1":wallet="walletItem":walletIddiff --git a/app/components/stat/Average.vue b/app/components/stat/Average.vueindex b33263cc..434f7983 100644--- a/app/components/stat/Average.vue+++ b/app/components/stat/Average.vue@@ -43,8 +43,6 @@ const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({until: dates.value.end,},walletsIds: props.walletId ? [...(props.filter.walletsIds.value ?? []), props.walletId] : props.filter.walletsIds.value,-}, {- includesChildCategories: true,}))const total = computed(() => getTotalOfTrnsIds(datedTrnsIds.value))diff --git a/app/components/stat/Header.vue b/app/components/stat/Header.vueindex c4d929be..17caeffd 100644--- a/app/components/stat/Header.vue+++ b/app/components/stat/Header.vue@@ -8,13 +8,10 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'const props = defineProps<{config?: {- isShowCategories?: booleanisShowWallets?: boolean}filter?: {- isShow?: booleanisShowCategories?: boolean- isShowSelected?: booleanisShowWallets?: boolean}}>()@@ -61,7 +58,6 @@ const statConfigModal: Ref<StatConfigModal> = ref({<StatConfigModalv-if="props.config"- :isShowCategories="!!props.config.isShowCategories":isShowWallets="!!props.config.isShowWallets":statConfigModal>@@ -91,27 +87,22 @@ const statConfigModal: Ref<StatConfigModal> = ref({</template><template- v-if="statConfig.config.value.wallets.isShow || $slots.summary"+ v-if="statConfig.config.value.wallets.isShow"#after><div class="grid gap-2 px-2 pb-0 lg:px-4 2xl:px-8">- <template v-if="statConfig.config.value.wallets.isShow">- <div- v-if="statConfig.config.value.wallets.isShow"- class="flex max-w-6xl gap-1 overflow-x-auto py-px"- >- <WalletsItem- v-for="walletId in sortedFilterWalletsIds"- :key="walletId"- :activeItemId="filter.walletsIds.value.includes(`${walletId}`) ? walletId : null"- :walletId- :wallet="walletsStore.itemsComputed?.[walletId]!"- insideClasses="!min-h-[38px]"- alt- @click="onClickWallet(walletId)"- />- </div>- </template>+ <div class="flex max-w-6xl gap-1 overflow-x-auto py-px">+ <WalletsItem+ v-for="walletId in sortedFilterWalletsIds"+ :key="walletId"+ :activeItemId="filter.walletsIds.value.includes(`${walletId}`) ? walletId : null"+ :walletId+ :wallet="walletsStore.itemsComputed?.[walletId]!"+ insideClasses="!min-h-[38px]"+ alt+ @click="onClickWallet(walletId)"+ />+ </div></div></template></UiHeader>diff --git a/app/components/stat/Item.vue b/app/components/stat/Item.vueindex de5d424b..3dbeb433 100644--- a/app/components/stat/Item.vue+++ b/app/components/stat/Item.vue@@ -29,7 +29,7 @@ const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()const categoryId = computed(() => props.isOneCategory ? route.params.id as CategoryId : undefined)-const isNotTransferCategory = computed(() => !props.isOneCategory || !categoriesStore.transferCategoriesIds.includes(categoryId.value))+const isNotTransferCategory = computed(() => !props.isOneCategory || categoryId.value !== 'transfer')const {averageTotal,@@ -77,7 +77,7 @@ function onClickCategory(clickedCategoryId: CategoryId) {quickViewTrns.value = trnsStore.getStoreTrnsIds({categoriesIds: [clickedCategoryId],trnsIds: selectedAndFilteredTrnsIds.value,- }, { includesChildCategories: true })+ })}function onClickSumItemWrap(type: SeriesSlugSelected) {@@ -158,8 +158,6 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {<StatTrns:isPeriodOneDay="isPeriodOneDay":selectedTrnsIds="selectedAndFilteredTrnsIds"- :storageKey="newBaseStorageKey"- :type="props.type ?? 'netIncome'"class="@3xl/page:order-1"/></div>diff --git a/app/components/stat/Page.vue b/app/components/stat/Page.vueindex 70ef5d2b..1b60c2c8 100644--- a/app/components/stat/Page.vue+++ b/app/components/stat/Page.vue@@ -24,7 +24,7 @@ const storageKey = computed(() => `dashboard-${activeTab.value}`)const trnsIds = computed(() => trnsStore.getStoreTrnsIds({categoriesIds: filter?.categoriesIds?.value,walletsIds: filter?.walletsIds?.value,-}, { includesChildCategories: true }))+}))const maxRange = computed(() => trnsStore.getRange(trnsIds.value))diff --git a/app/components/stat/Trns.vue b/app/components/stat/Trns.vueindex 0b1332a7..5bd9dc80 100644--- a/app/components/stat/Trns.vue+++ b/app/components/stat/Trns.vue@@ -1,12 +1,9 @@<script setup lang="ts">-import type { StatTabSlug } from '~/components/stat/types'import type { TrnId } from '~/components/trns/types'defineProps<{isPeriodOneDay: booleanselectedTrnsIds: TrnId[]- storageKey: string- type: StatTabSlug}>()</script>diff --git a/app/components/stat/Wrap.vue b/app/components/stat/Wrap.vueindex c2d80aef..23e77693 100644--- a/app/components/stat/Wrap.vue+++ b/app/components/stat/Wrap.vue@@ -32,15 +32,11 @@ const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({const expenseTrnsIds = computed(() => trnsStore.getStoreTrnsIds({trnsIds: datedTrnsIds.value,trnsTypes: [TrnType.Expense, TrnType.Transfer],-}, {- includesChildCategories: true,}))const incomeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({trnsIds: datedTrnsIds.value,trnsTypes: [TrnType.Income, TrnType.Transfer],-}, {- includesChildCategories: true,}))</script>diff --git a/app/components/stat/categories/Line.vue b/app/components/stat/categories/Line.vueindex b20e9abd..1c0b8d33 100644--- a/app/components/stat/categories/Line.vue+++ b/app/components/stat/categories/Line.vue@@ -15,7 +15,6 @@ const props = defineProps<{insideClass?: stringinsideStyle?: stringisActive?: boolean- isShowDots?: booleanisShowParent?: booleanitem: CategoryWithDatalineWidth?: number@@ -23,7 +22,6 @@ const props = defineProps<{const emit = defineEmits<{click: [categoryId: CategoryId]- clickIcon: [id: CategoryId]}>()const statDate = inject(statDateKey)!@@ -120,14 +118,12 @@ onLongPress(:color="category?.color":name="category?.icon"invert- @click="emit('clickIcon', props.item.id)"/><UiIconBasev-else:color="category?.color":name="category?.icon"class="ml-1 !w-6"- @click="emit('clickIcon', props.item.id)"/></template>diff --git a/app/components/stat/categories/Round.vue b/app/components/stat/categories/Round.vuedeleted file mode 100644index 29bfeda1..00000000--- a/app/components/stat/categories/Round.vue+++ /dev/null@@ -1,103 +0,0 @@-<script setup lang="ts">-import type { CategoryId } from '~/components/categories/types'-import type { CategoryWithData } from '~/components/stat/types'--import { useCategoriesStore } from '~/components/categories/useCategoriesStore'-import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'-import { statDateKey } from '~/components/stat/injectionKeys'-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'--const props = defineProps<{- isShowAmount?: boolean- item: CategoryWithData-}>()--const emit = defineEmits<{- click: [categoryId: CategoryId]-}>()--const statDate = inject(statDateKey)!-const categoriesStore = useCategoriesStore()-const currenciesStore = useCurrenciesStore()-const trnsFormStore = useTrnsFormStore()--const category = computed(() => categoriesStore.items[props.item.id])--const longPressRef = ref(null)-onLongPress(- longPressRef,- () => {- const isTransactible = categoriesStore.isItTransactible(props.item.id)- if (!isTransactible)- return-- trnsFormStore.trnFormCreate()- trnsFormStore.$patch((state) => {- state.values.amount = [0, 0, 0]- state.values.amountRaw = ['', '', '']- state.values.categoryId = props.item.id- state.ui.isShow = true-- const isDayDate = statDate.params.value.intervalSelected !== -1 && statDate.params.value.intervalsBy === 'day'- if (isDayDate && statDate.selectedInterval.value?.start) {- state.values.date = statDate.selectedInterval.value!.start- }- else {- state.values.date = new Date().getTime()- }- })- },- {- onMouseUp: (duration: number, distance: number, isLongPress: boolean) => {- if (!isLongPress && distance < 100) {- emit('click', props.item.id)- }- },- },-)-</script>--<template>- <div- v-if="category"- ref="longPressRef"- :class="cn('dark:bg-item-3 relative flex items-center gap-2 overflow-hidden rounded-full p-1 pr-2 hover:bg-(--item-5)',- props.item.value === 0 && 'opacity-60',- )"- >- <div- :style="{ backgroundColor: category?.color }"- class="absolute inset-0 size-full opacity-10"- />-- <div class="size-6">- <UiIconBase- :name="category?.icon"- :color="category?.color"- :size="14"- class="!w-6 p-1"- invert- />- </div>-- <div class="text-xs">- {{ category.name }}- </div>-- <div- v-if="props.isShowAmount"- class="opacity-90"- >- <Amount- :amount="props.item.value"- :type="props.item.value >= 0 ? 1 : 0"- :currencyCode="currenciesStore.base"- :isShowBaseRate="false"- :isShowSymbol="false"- align="left"- variant="xs"- colorize="income"- />- </div>- </div>-</template>diff --git a/app/components/stat/categories/Section2.vue b/app/components/stat/categories/Section2.vueindex 1833cc54..eac38df3 100644--- a/app/components/stat/categories/Section2.vue+++ b/app/components/stat/categories/Section2.vue@@ -12,7 +12,6 @@ import { statConfigKey } from '~/components/stat/injectionKeys'const props = defineProps<{isOneCategory?: booleanpreCategoriesIds?: CategoryId[]- selectedAndFilteredTrnsIds?: TrnId[]selectedTrnsIds?: TrnId[]storageKey: stringtype: StatTabSlugdiff --git a/app/components/stat/categories/Vertical.vue b/app/components/stat/categories/Vertical.vueindex 58c10320..fc15082a 100644--- a/app/components/stat/categories/Vertical.vue+++ b/app/components/stat/categories/Vertical.vue@@ -16,7 +16,6 @@ const props = defineProps<{const emit = defineEmits<{click: [categoryId: CategoryId]- clickIcon: [id: CategoryId]}>()const statDate = inject(statDateKey)!diff --git a/app/components/stat/categories/useStatCategories.ts b/app/components/stat/categories/useStatCategories.tsindex 0d1439a5..5d2d5df3 100644--- a/app/components/stat/categories/useStatCategories.ts+++ b/app/components/stat/categories/useStatCategories.ts@@ -14,12 +14,11 @@ export function useStatCategories() {const { getTotalOfTrnsIds } = useAmount()function collectCategoriesByTrns(trnsIds: TrnId[], preCategoriesIds?: CategoryId[]): CategoriesWithData {- const transferIds = new Set(categoriesStore.transferCategoriesIds)const categoriesByTrns = trnsIds.reduce((acc, trnId) => {const categoryId = trnsStore.items?.[trnId]?.categoryIdconst category = categoryId && categoriesStore.items[categoryId]- if (!categoryId || !category || transferIds.has(categoryId))+ if (!categoryId || !category || categoryId === 'transfer')return accacc[categoryId] ??= {diff --git a/app/components/stat/chart/View.vue b/app/components/stat/chart/View.vueindex fd73452e..1f2f5732 100644--- a/app/components/stat/chart/View.vue+++ b/app/components/stat/chart/View.vue@@ -8,7 +8,6 @@ import VChart from 'vue-echarts'import type { Period } from '~/components/date/types'import type { ChartType } from '~/components/stat/chart/types'-import type { PeriodNameWithAll } from '~/components/stat/filter/types'import type { ChartSeries } from '~/components/stat/types'import { formatByLocale } from '~/components/date/utils'@@ -17,13 +16,11 @@ import { getLocalAmount } from '~/components/stat/chart/utils'const {chartType = 'line',- isShowDataLabels,period,series,xAxisLabels,} = defineProps<{chartType?: ChartType- isShowDataLabels?: booleanperiod: Periodseries: ChartSeries[]xAxisLabels: number[]@@ -49,18 +46,15 @@ use([const { locale } = useI18n()const chartRef = ref()-function getFormatForChart(periodName: PeriodNameWithAll) {+function getFormatForChart(periodName: Period) {switch (periodName) {case 'day':- return 'd MMM'case 'week':return 'd MMM'case 'month':return 'MMM'case 'year':return 'yyyy'- default:- return 'MM'}}@@ -74,11 +68,11 @@ const option = computed(() => {})data.xAxis.axisLabel.formatter = (date: string) => {- return formatByLocale(new Date(+date), getFormatForChart(period, new Date(+date)), locale.value)+ return formatByLocale(new Date(+date), getFormatForChart(period), locale.value)}data.xAxis.axisPointer.label.formatter = ({ value }: { value: string }) => {- return formatByLocale(new Date(+value), getFormatForChart(period, new Date(+value)), locale.value)+ return formatByLocale(new Date(+value), getFormatForChart(period), locale.value)}return data@@ -97,10 +91,7 @@ function setChartSeries(series: ChartSeries[]) {return series.map((item: ChartSeries) => ({...defu(lineConfig, item),- label: {- ...lineConfig.label,- show: isShowDataLabels,- },+ label: lineConfig.label,stack: (chartType || item.type) === 'bar' ? 'b' : false,type: item.markedArea ? 'bar' : (chartType || item.type),}))diff --git a/app/components/stat/chart/config.ts b/app/components/stat/chart/config.tsindex 7d0f310c..19ffd555 100644--- a/app/components/stat/chart/config.ts+++ b/app/components/stat/chart/config.ts@@ -14,20 +14,17 @@ type EChartsOption = ComposeOption<>type SeriesOption = (BarSeriesOption | LineSeriesOption) & {- localeKey: stringmarkLineColor?: string}export const seriesOptions: Record<SeriesSlug, SeriesOption> = {expense: {color: 'var(--expense-1)',- localeKey: 'money.expense',markLineColor: 'var(--expense-2)',type: 'bar',},income: {color: 'var(--income-1)',- localeKey: 'money.expense',markLineColor: 'var(--income-2)',type: 'bar',},diff --git a/app/components/stat/chart/useStatChart.ts b/app/components/stat/chart/useStatChart.tsindex 73182811..12e852e1 100644--- a/app/components/stat/chart/useStatChart.ts+++ b/app/components/stat/chart/useStatChart.ts@@ -42,7 +42,7 @@ export function useStatChart() {return {color: seriesOptions[typeItem]?.color,- data: data.map(i => typeItem !== 'summary' ? Math.abs(i[typeItem]) : i[typeItem]),+ data: data.map(i => Math.abs(i[typeItem])),markLine,name: t(`money.${typeItem}`),type: seriesOptions[typeItem]?.type,diff --git a/app/components/stat/date/Quick.vue b/app/components/stat/date/Quick.vueindex 205f5af4..01b9528b 100644--- a/app/components/stat/date/Quick.vue+++ b/app/components/stat/date/Quick.vue@@ -4,10 +4,6 @@ import 'swiper/css'import { statDateKey } from '~/components/stat/injectionKeys'-const emit = defineEmits<{- close: []-}>()-const statDate = inject(statDateKey)!const sliderRef = ref<HTMLElement | null>(null)@@ -39,7 +35,6 @@ onMounted(() => {:itemProps="{ variant: 'small' }":statDateview="periods"- @close="emit('close')"/></div>@@ -48,7 +43,6 @@ onMounted(() => {:itemProps="{ variant: 'small' }":statDateview="presets"- @close="emit('close')"/></div>@@ -57,7 +51,6 @@ onMounted(() => {:itemProps="{ variant: 'small' }":statDateview="maximum"- @close="emit('close')"/></div></div>diff --git a/app/components/stat/date/useGetDateRange.test.ts b/app/components/stat/date/useGetDateRange.test.tsindex f36b865f..7b584412 100644--- a/app/components/stat/date/useGetDateRange.test.ts+++ b/app/components/stat/date/useGetDateRange.test.ts@@ -1,4 +1,4 @@-import { addMonths, endOfDay, endOfMonth, endOfWeek, endOfYear, startOfDay, startOfMonth, startOfWeek, startOfYear } from 'date-fns'+import { addMonths, endOfDay, endOfMonth, endOfWeek, endOfYear, startOfDay, startOfMonth, startOfWeek, startOfYear, sub } from 'date-fns'import { afterAll, describe, expect, it, vi } from 'vitest'import { useGetDateRange } from '~/components/stat/date/useGetDateRange'@@ -8,16 +8,24 @@ function t(key: string) {const translations: Record<string, string> = {'dates.day.current': 'Today','dates.day.last': 'Yesterday',+ 'dates.day.plural': 'days','dates.day.simple': 'Days',+ 'dates.last.day': 'Last',+ 'dates.last.month': 'Last','dates.last.simple': 'Last',+ 'dates.last.week': 'Last',+ 'dates.last.year': 'Last','dates.month.current': 'This Month','dates.month.last': 'Last Month',+ 'dates.month.plural': 'months','dates.month.simple': 'Months','dates.week.current': 'This Week','dates.week.last': 'Last Week',+ 'dates.week.plural': 'weeks','dates.week.simple': 'Weeks','dates.year.current': 'This Year','dates.year.last': 'Last Year',+ 'dates.year.plural': 'years','dates.year.simple': 'Years',}return translations[key] || key@@ -31,9 +39,16 @@ vi.useFakeTimers()vi.setSystemTime(fixedDate)describe('useGetDateRange', () => {- const { getStringDateRange } = useGetDateRange(t)+ const { formatDateToStringWithLast, getStringDateRange } = useGetDateRange(t)const today = fixedDate+ /** Call formatDateToStringWithLast for both 'start' and 'end', return concatenated label */+ function getLabel(params: { by: 'day' | 'month' | 'week' | 'year', duration: number, end: Date, start: Date }, isShowMaxRange?: boolean): string {+ const s = formatDateToStringWithLast({ ...params, type: 'start' }, isShowMaxRange)+ const e = formatDateToStringWithLast({ ...params, type: 'end' }, isShowMaxRange)+ return `${s}${e}`+ }+afterAll(() => {vi.useRealTimers()})@@ -93,4 +108,39 @@ describe('useGetDateRange', () => {expect(getStringDateRange(range, 'day', 5)).toBe('10-15 Mar 2024')})})++ describe('formatDateToStringWithLast β current/last period labels', () => {+ it('shows "Today" for current day', () => {+ expect(getLabel({ by: 'day', duration: 1, end: today, start: today })).toBe('Today')+ })++ it('shows "Yesterday" for previous day', () => {+ const yesterday = sub(today, { days: 1 })+ expect(getLabel({ by: 'day', duration: 1, end: yesterday, start: yesterday })).toBe('Yesterday')+ })++ it('shows "This Month" for current month', () => {+ expect(getLabel({ by: 'month', duration: 1, end: endOfMonth(today), start: startOfMonth(today) })).toBe('This Month')+ })++ it('shows "Last Month" for previous month', () => {+ const lastMonth = sub(today, { months: 1 })+ expect(getLabel({ by: 'month', duration: 1, end: endOfMonth(lastMonth), start: startOfMonth(lastMonth) })).toBe('Last Month')+ })++ it('shows "Last N periods" when end is in current period', () => {+ const start = sub(today, { days: 2 })+ expect(getLabel({ by: 'day', duration: 3, end: today, start })).toBe('Last 3 days')+ })++ it('shows "d MMMM" for single day in current year (not today/yesterday)', () => {+ const date = new Date('2025-03-15T12:00:00')+ expect(getLabel({ by: 'day', duration: 1, end: date, start: date })).toBe('15 March')+ })++ it('shows "d MMM yyyy" for single day in past year', () => {+ const date = new Date('2024-06-15T12:00:00')+ expect(getLabel({ by: 'day', duration: 1, end: date, start: date })).toBe('15 Jun 2024')+ })+ })})diff --git a/app/components/stat/filter/Selected.vue b/app/components/stat/filter/Selected.vueindex 60b217e9..16359f28 100644--- a/app/components/stat/filter/Selected.vue+++ b/app/components/stat/filter/Selected.vue@@ -40,7 +40,6 @@ const itemClasses = 'bg-item-3 rounded-sm':categoryId="categoryId":class="itemClasses"alt- isShowDotsinsideClasses="!min-h-[38px]"@click="filter.removeCategoryId(categoryId)"/>diff --git a/app/components/stat/filter/Selector.vue b/app/components/stat/filter/Selector.vueindex 80d87484..e3b6d0a0 100644--- a/app/components/stat/filter/Selector.vue+++ b/app/components/stat/filter/Selector.vue@@ -98,7 +98,6 @@ const modals = ref({<CategoriesSelectorTree:selectedIds="filter?.categoriesIds.value"class="min-w-80 px-3"- @filter="filter.toggleCategoryId"@selected="filter.toggleCategoryId"@setCategories="filter.setCategories"/>diff --git a/app/components/stat/sum/Item.vue b/app/components/stat/sum/Item.vueindex f87c8b01..57e7f00b 100644--- a/app/components/stat/sum/Item.vue+++ b/app/components/stat/sum/Item.vue@@ -1,16 +1,12 @@<script setup lang="ts">-import type { AmountProps } from '~/components/amount/Amount.vue'import type { SeriesSlugSelected } from '~/components/stat/types'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'const props = defineProps<{amount: number- amountProps?: Partial<AmountProps>averageTotal?: Record<string, number>- currencyCode?: stringisActive?: boolean- isTotal?: booleantitle?: stringtype: SeriesSlugSelected}>()@@ -37,20 +33,18 @@ const currenciesStore = useCurrenciesStore()</UiTextSubtitle><UiTextSubtitle v-if="!props.title">- {{ props.isTotal ? t('money.all') : '' }}{{ t(`money.${props.type}`) }}</UiTextSubtitle><Amount:amount="props.amount"- :currencyCode="props.currencyCode || currenciesStore.base"+ :currencyCode="currenciesStore.base":class="{'!text-income-1': props.amount > 0 && props.type !== 'netIncome','!text-expense-1': props.amount < 0 && props.type !== 'netIncome',}"align="left"variant="xl"- v-bind="props.amountProps"/></div>diff --git a/app/components/stat/sum/ItemWallet.vue b/app/components/stat/sum/ItemWallet.vueindex 64132c3f..2bdb346f 100644--- a/app/components/stat/sum/ItemWallet.vue+++ b/app/components/stat/sum/ItemWallet.vue@@ -4,21 +4,15 @@ import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'const props = defineProps<{amount: numbercurrencyCode?: string- isActive?: booleantitle?: string}>()-const emit = defineEmits<{- click: [e: Event]-}>()-const currenciesStore = useCurrenciesStore()</script><template><divclass="flex grid min-h-[42px] min-w-[42px] grow-0 items-center gap-1 py-1 lg:gap-1"- @click="(e: Event) => emit('click', e)"><UiTextSubtitle>{{ props.title }}</UiTextSubtitle>diff --git a/app/components/stat/sum/Wrap.vue b/app/components/stat/sum/Wrap.vueindex 815c92b0..bd1f586e 100644--- a/app/components/stat/sum/Wrap.vue+++ b/app/components/stat/sum/Wrap.vue@@ -14,7 +14,6 @@ const props = defineProps<{isShowAverage: booleanisShowExpense: booleanisShowIncome: boolean- statTabSlug?: StatTabSlugtotal: TotalReturnstrnsIds: TrnId[]type: StatTabSlugdiff --git a/app/components/stat/useStatConfig.ts b/app/components/stat/useStatConfig.tsindex 919e00f3..34614c26 100644--- a/app/components/stat/useStatConfig.ts+++ b/app/components/stat/useStatConfig.ts@@ -15,14 +15,10 @@ export const ConfigSchema = z.object({isLines: z.boolean(),isRoundIcon: z.boolean(),isShow: z.boolean(),- isShowFavorites: z.boolean(),- isShowRecent: z.boolean(),}),catsRound: z.object({isGrouped: z.boolean(),isShow: z.boolean(),- isShowFavorites: z.boolean(),- isShowRecent: z.boolean(),}),catsView: z.enum(['list', 'round']),chart: z.object({@@ -50,7 +46,6 @@ export const ConfigSchema = z.object({})export type MiniItemConfig = z.infer<typeof ConfigSchema>-export type UpdateConfigFn = <K extends keyof MiniItemConfig>(key: K, value: MiniItemConfig[K]) => voidtype StatConfigParams = {props?: DeepPartial<MiniItemConfig>@@ -67,14 +62,10 @@ export function useStatConfig({ props, storageKey }: StatConfigParams) {isLines: true,isRoundIcon: true,isShow: true,- isShowFavorites: false,- isShowRecent: false,},catsRound: {isGrouped: false,isShow: true,- isShowFavorites: false,- isShowRecent: false,},catsView: 'list',chart: {diff --git a/app/components/stat/useStatItem.ts b/app/components/stat/useStatItem.tsindex bd78fb2c..5b6cc7f7 100644--- a/app/components/stat/useStatItem.ts+++ b/app/components/stat/useStatItem.ts@@ -74,12 +74,12 @@ export function useStatItem({const rangeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({trnsIds: trnsIds.value,- }, { includesChildCategories: false }))+ }))const rangeTrnsIdsWithFilteredCategories = computed(() => trnsStore.getStoreTrnsIds({categoriesIds: filteredCategoriesIds.value,trnsIds: trnsIds.value,- }, { includesChildCategories: true }))+ }))function getIntervalsData(ids: TrnId[], intervalsInRange: Range[]) {return intervalsInRange.reduce((acc, range) => {@@ -106,7 +106,7 @@ export function useStatItem({? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds: rangeTrnsIds.value,trnsTypes: selectedTypesMapping.value,- }, { includesChildCategories: false }))+ }))const selectedAndFilteredTrnsIds = computed(() => trnsStore.getStoreTrnsIds({categoriesIds: filteredCategoriesIds.value,@@ -114,7 +114,7 @@ export function useStatItem({? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds: rangeTrnsIds.value,trnsTypes: selectedTypesMapping.value,- }, { includesChildCategories: true }))+ }))const rangeTotal = computed(() => {const ids = statDate.params.value.intervalSelected !== -1diff --git a/app/components/theme/SwitcherTabs.vue b/app/components/theme/SwitcherTabs.vuedeleted file mode 100644index bb124a0f..00000000--- a/app/components/theme/SwitcherTabs.vue+++ /dev/null@@ -1,19 +0,0 @@-<script setup lang="ts">-import { useTheme } from '~/components/theme/useTheme'--const { options, preference, setTheme } = useTheme()-</script>--<template>- <UiTabsScroll>- <UiTabsItemPill- v-for="theme in options"- :key="theme.value"- variant="outline"- :isActive="preference === theme.value"- @click="setTheme(theme.value)"- >- {{ theme.label }}- </UiTabsItemPill>- </UiTabsScroll>-</template>diff --git a/app/components/trnForm/Categories.vue b/app/components/trnForm/Categories.vuedeleted file mode 100644index 1c957949..00000000--- a/app/components/trnForm/Categories.vue+++ /dev/null@@ -1,124 +0,0 @@-<script setup lang="ts">-import Swiper from 'swiper'-import 'swiper/css'--import type { CategoryId } from '~/components/categories/types'--import { useCategoriesStore } from '~/components/categories/useCategoriesStore'-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'--const emit = defineEmits<{- click: [id: CategoryId]-}>()--const { t } = useI18n()-const trnsFormStore = useTrnsFormStore()-const categoriesStore = useCategoriesStore()--const sliderObj = ref()-const sliderRef = ref()--function onClick(categoryId: CategoryId) {- emit('click', categoryId)-}--onMounted(() => {- const initialSlide = 1-- sliderObj.value = new Swiper(sliderRef.value, {- autoHeight: false,- initialSlide,- longSwipesMs: 60,- longSwipesRatio: 0.1,- observeParents: true,- observer: true,- shortSwipes: false,- slidesPerView: 1,- touchStartPreventDefault: false,- })-})-</script>--<template>- <div class="relative grid h-full grid-rows-[1fr_auto] overflow-hidden">- <div class="h-full overflow-hidden">- <div ref="sliderRef" class="swiper-container h-full">- <div class="swiper-wrapper">- <!-- Recent -->- <div class="swiper-slide h-full">- <div- class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold"- >- {{ t('categories.recentCategories') }}- </div>- <div class="px-3 pb-1">- <CategoriesList- :activeItemId="trnsFormStore?.values?.categoryId"- :ids="categoriesStore.recentCategoriesIds"- class="!gap-x-1"- @click="onClick"- />- </div>- </div>-- <!-- Main -->- <div class="swiper-slide h-full">- <div- class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold"- >- {{ t('categories.title') }}- </div>- <div class="px-3 pb-1">- <CategoriesList- :activeItemId="trnsFormStore?.values?.categoryId"- :ids="categoriesStore.categoriesRootIds"- class="!gap-x-1"- @click="onClick"- />- </div>- </div>-- <!-- Favorite -->- <div class="swiper-slide h-full">- <div class="scrollerBlock font-primary rounded-t-2xl bg-(--item-1) px-3 py-4 text-center text-xl font-semibold">- {{ t('categories.favoriteCategories') }}- </div>- <div class="px-3 pb-1">- <CategoriesList- :activeItemId="trnsFormStore?.values?.categoryId"- :ids="categoriesStore.favoriteCategoriesIds"- class="!gap-x-1"- @click="onClick"- />- </div>- </div>- </div>- </div>- </div>-- <div v-if="sliderObj" class="px-3 py-2">- <UiTabsBar>- <UiTabsItemFill- :isActive="sliderObj.activeIndex === 0"- @click="sliderObj.slideTo(0)"- >- {{ t('categories.recentCategories') }}- </UiTabsItemFill>-- <UiTabsItemFill- :isActive="sliderObj.activeIndex === 1"- @click="sliderObj.slideTo(1)"- >- {{ t('categories.allTitle') }}- </UiTabsItemFill>-- <UiTabsItemFill- :isActive="sliderObj.activeIndex === 2"- @click="sliderObj.slideTo(2)"- >- {{ t('categories.favoriteCategories') }}- </UiTabsItemFill>- </UiTabsBar>- </div>- </div>-</template>diff --git a/app/components/trnForm/FloatOpener.vue b/app/components/trnForm/FloatOpener.vueindex 3042f8ef..303b981d 100644--- a/app/components/trnForm/FloatOpener.vue+++ b/app/components/trnForm/FloatOpener.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'-const { onClose, trnFormCreate, ui } = useTrnsFormStore()+const { trnFormCreate, ui } = useTrnsFormStore()</script><template>@@ -12,7 +12,7 @@ const { onClose, trnFormCreate, ui } = useTrnsFormStore()justify-end from-transparent to-(--item-5)transition hover:bg-gradient-to-r xl:flex"- @click="ui.isShow ? onClose() : trnFormCreate()"+ @click="trnFormCreate()"><divclass="diff --git a/app/components/trnForm/Main.vue b/app/components/trnForm/Main.vueindex 4dc42a74..4520934a 100644--- a/app/components/trnForm/Main.vue+++ b/app/components/trnForm/Main.vue@@ -14,34 +14,15 @@ const { t } = useI18n()const categoriesStore = useCategoriesStore()const trnsFormStore = useTrnsFormStore()const walletsStore = useWalletsStore()-const { width } = useWindowSize()-const { pointerType } = usePointer()--const isLaptop = computed(() => width.value >= 766 && pointerType.value === 'mouse')-const walletId = computed(() => {const walletsIds = Object.keys(walletsStore.items ?? {})const firstWalletId = walletsIds[0]return trnsFormStore.values.walletId ?? firstWalletId})--const isShow = ref(false)-const initialSlide = ref(0)-function show(slide: number) {- isShow.value = true- initialSlide.value = slide-}</script><template><div class="grid pb-0">- <TrnFormSelection- v-if="isShow"- v-model:isShow="isShow"- :maxHeight="maxHeight"- :initialSlide- />-<UiTitleModal @click="trnsFormStore.values.trnId = null">{{ trnsFormStore.values.trnId ? t('trnForm.titleEditTrn') : t('trnForm.createTrn') }}</UiTitleModal>@@ -72,10 +53,8 @@ function show(slide: number) {<TrnFormSelectorWalletv-if="walletId":bottomSheetStyle="{ maxHeight }"- :isLaptop:title="t('trnForm.wallet.select')":walletId="walletId"- @open="show(0)"@selected="(id: WalletId) => trnsFormStore.values.walletId = id"/>@@ -84,9 +63,7 @@ function show(slide: number) {:bottomSheetStyle="{ maxHeight }":category="categoriesStore.items[trnsFormStore.values.categoryId ?? categoriesStore.categoriesIdsForTrnValues[0]]":categoryId="trnsFormStore.values.categoryId ?? categoriesStore.categoriesIdsForTrnValues[0]"- :isLaptop:title="t('trnForm.category.select')"- @open="show(2)"@selected="(id: CategoryId) => trnsFormStore.values.categoryId = id"/></div>@@ -94,8 +71,6 @@ function show(slide: number) {<TrnFormMainAmountTransferv-if="trnsFormStore.values.trnType === 2":bottomSheetStyle="{ maxHeight }"- isLaptop- @open="show(0)"/><TrnFormMainCalculator />diff --git a/app/components/trnForm/Selection.vue b/app/components/trnForm/Selection.vuedeleted file mode 100644index d522c919..00000000--- a/app/components/trnForm/Selection.vue+++ /dev/null@@ -1,147 +0,0 @@-<script setup lang="ts">-import Swiper from 'swiper'-import { Pagination } from 'swiper/modules'--import type { CategoryId } from '~/components/categories/types'-import type { WalletId } from '~/components/wallets/types'--import { useCategoriesStore } from '~/components/categories/useCategoriesStore'-import { getParentCategoryIdOrReturnSame } from '~/components/categories/utils'-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'--import 'swiper/css'--const { initialSlide = 0, maxHeight = '60vh' } = defineProps<{- initialSlide?: number- maxHeight?: string-}>()--const isShow = defineModel('isShow', {- default: false,-})--const { t } = useI18n()-const categoriesStore = useCategoriesStore()-const trnsFormStore = useTrnsFormStore()--const sliderRef = ref<HTMLElement | null>(null)-const sliderObj = ref<Swiper | null>(null)-onMounted(() => {- if (!sliderObj.value) {- sliderObj.value = new Swiper(sliderRef.value, {- init: false,- initialSlide,- longSwipesMs: 60,- longSwipesRatio: 0.1,- modules: [Pagination],- pagination: {- clickable: true,- el: '.trnFormSelectionPagination',- },- shortSwipes: false,- })- sliderObj.value.init()- }-})--const parentCategoryId = ref<CategoryId | null>(getParentCategoryIdOrReturnSame(categoriesStore.items, trnsFormStore.values.categoryId))--function onSelectWallet(id: WalletId, close: () => void) {- trnsFormStore.values.walletId = id- close()-}--function onSelectCategory(id: CategoryId, close: () => void) {- trnsFormStore.values.categoryId = id- close()-}--async function onSelectParentCategory(id: CategoryId) {- parentCategoryId.value = id- await nextTick()- sliderObj.value.update()- sliderObj.value.slideTo(3)-}-</script>--<template>- <Teleport to="body">- <BottomSheet- :isShow="isShow"- drugClassesCustom="bg-(--item-1) max-w-md"- @closed="isShow = false"- >- <template #handler="{ close }">- <BottomSheetHandler />- <BottomSheetClose @click="close" />- </template>-- <template #default="{ close }">- <div ref="sliderRef" class="swiper-container">- <div class="swiper-wrapper">- <!-- Wallets -->- <div- :style="{ height: maxHeight }"- class="swiper-slide"- >- <div class="scrollerBlock h-full overflow-y-auto pb-3">- <TrnFormSelectionWalletsAll- :maxHeight="maxHeight"- @selectWallet="id => onSelectWallet(id, close)"- />- </div>- </div>-- <!-- Categories fast -->- <div- :style="{ height: maxHeight }"- class="swiper-slide"- >- <div class="scrollerBlock grid h-full gap-4 overflow-y-auto pb-3">- <TrnFormSelectionCategoriesFast- @selectCategory="id => onSelectCategory(id, close)"- @selectParentCategory="id => onSelectParentCategory(id)"- />- </div>- </div>-- <!-- Categories -->- <div- :style="{ height: maxHeight }"- class="swiper-slide"- >- <div class="scrollerBlock h-full overflow-y-auto pb-3">- <UiTitleSection- class="sticky top-0 z-10 bg-(--item-1) px-3 pt-4 pb-3"- @click="trnsFormStore.ui.catsRootModal = true"- >- {{ t('categories.title') }}- </UiTitleSection>- <CategoriesSelectorTree- @selected="id => onSelectCategory(id, close)"- />- </div>- </div>- </div>- </div>- <div class="trnFormSelectionPagination" />- </template>- </BottomSheet>- </Teleport>-</template>--<style>-@reference '~/assets/css/main.css';--.trnFormSelectionPagination.swiper-pagination-horizontal .swiper-pagination-bullet-active {- @apply !bg-neutral-600 dark:!bg-white/80;-}--.trnFormSelectionPagination.swiper-pagination-horizontal {- @apply absolute bottom-[1px] left-1/2 z-[2] flex w-auto -translate-x-1/2 items-center justify-center rounded-md bg-[rgba(23,23,23,0.9)] p-1.5;-}--.trnFormSelectionPagination.swiper-pagination-horizontal .swiper-pagination-bullet {- @apply m-1 size-1.5 rounded-full bg-item-7 opacity-100;-}-</style>diff --git a/app/components/trnForm/SelectionCategoriesFast.vue b/app/components/trnForm/SelectionCategoriesFast.vueindex 4f4aad28..0dfc4964 100644--- a/app/components/trnForm/SelectionCategoriesFast.vue+++ b/app/components/trnForm/SelectionCategoriesFast.vue@@ -5,9 +5,7 @@ import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'const emit = defineEmits<{- close: []selectCategory: [id: CategoryId]- selectParentCategory: [id: CategoryId]}>()const { t } = useI18n()@@ -33,9 +31,9 @@ const isShowAllCategoriesFallback = computed(() =><CategoriesSelectorGrid:activeItemId="trnsFormStore.values.categoryId"- :hide="() => emit('close')"+:ids="categoriesStore.favoriteCategoriesIds"- @clickParent="id => emit('selectParentCategory', id)"+@selected="id => emit('selectCategory', id)"/></div>@@ -48,9 +46,9 @@ const isShowAllCategoriesFallback = computed(() =><CategoriesSelectorGrid:activeItemId="trnsFormStore.values.categoryId"- :hide="() => emit('close')"+:ids="categoriesStore.recentCategoriesIds"- @clickParent="id => emit('selectParentCategory', id)"+@selected="id => emit('selectCategory', id)"/></div>@@ -59,9 +57,9 @@ const isShowAllCategoriesFallback = computed(() =><div v-if="isShowAllCategoriesFallback"><CategoriesSelectorGrid:activeItemId="trnsFormStore.values.categoryId"- :hide="() => emit('close')"+:ids="categoriesStore.categoriesIdsForTrnValues"- @clickParent="id => emit('selectParentCategory', id)"+@selected="id => emit('selectCategory', id)"/></div>diff --git a/app/components/trnForm/SelectionWalletsAll.vue b/app/components/trnForm/SelectionWalletsAll.vuedeleted file mode 100644index 61ad7d25..00000000--- a/app/components/trnForm/SelectionWalletsAll.vue+++ /dev/null@@ -1,30 +0,0 @@-<script setup lang="ts">-import type { WalletId } from '~/components/wallets/types'--import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'--defineProps<{- maxHeight: string-}>()--const emit = defineEmits<{- selectWallet: [id: WalletId]-}>()--const { t } = useI18n()-const trnsFormStore = useTrnsFormStore()-</script>--<template>- <div>- <UiTitleModal @click="trnsFormStore.ui.walletsModal = true">- {{ t('wallets.title') }}- </UiTitleModal>-- <WalletsSelector- :activeItemId="trnsFormStore.values.walletId ?? undefined"- class="min-w-80 px-2 py-px"- @selected="id => emit('selectWallet', id)"- />- </div>-</template>diff --git a/app/components/trnForm/SelectorCategory.vue b/app/components/trnForm/SelectorCategory.vueindex c1e44c94..4ae9e4f6 100644--- a/app/components/trnForm/SelectorCategory.vue+++ b/app/components/trnForm/SelectorCategory.vue@@ -5,12 +5,10 @@ const props = defineProps<{bottomSheetStyle?: Record<string, string>category: CategoryItemcategoryId: CategoryId- isLaptop: booleantitle?: string}>()const emit = defineEmits<{- open: [slide: number]selected: [id: CategoryId]}>()diff --git a/app/components/trnForm/SelectorWallet.vue b/app/components/trnForm/SelectorWallet.vueindex 8cc9d416..8a99c380 100644--- a/app/components/trnForm/SelectorWallet.vue+++ b/app/components/trnForm/SelectorWallet.vue@@ -5,13 +5,11 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'const props = defineProps<{bottomSheetStyle?: Record<string, string>- isLaptop: booleantitle?: stringwalletId: WalletId}>()const emit = defineEmits<{- open: [slide: number]selected: [id: WalletId]}>()diff --git a/app/components/trnForm/Sidebar.vue b/app/components/trnForm/Sidebar.vueindex c0ecc891..2cd57a34 100644--- a/app/components/trnForm/Sidebar.vue+++ b/app/components/trnForm/Sidebar.vue@@ -65,7 +65,6 @@ watch(isShow, async (v) => {<TrnFormMainmaxHeight="100vh"class="!pb-0"- typesPosition="top"/><divv-if="trnsFormStore.values.trnType !== 2"diff --git a/app/components/trnForm/main/AmountTransfer.vue b/app/components/trnForm/main/AmountTransfer.vueindex c3ecd0bb..b4582842 100644--- a/app/components/trnForm/main/AmountTransfer.vue+++ b/app/components/trnForm/main/AmountTransfer.vue@@ -9,11 +9,6 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'const props = defineProps<{bottomSheetStyle?: Record<string, string>- isLaptop: boolean-}>()--const emit = defineEmits<{- open: [slide: number]}>()const trnsFormStore = useTrnsFormStore()@@ -108,20 +103,16 @@ function copyAmount() {<TrnFormSelectorWalletv-if="slug === 'income' && incomeWalletId":bottomSheetStyle="props.bottomSheetStyle"- :isLaptop:title="t(`trnForm.transfer.${slug}`)":walletId="incomeWalletId"- @open="n => emit('open', n)"@selected="id => trnsFormStore.values.incomeWalletId = id"/><TrnFormSelectorWalletv-if="slug === 'expense' && expenseWalletId":bottomSheetStyle="props.bottomSheetStyle"- :isLaptop:title="t(`trnForm.transfer.${slug}`)":walletId="expenseWalletId"- @open="n => emit('open', n)"@selected="id => trnsFormStore.values.expenseWalletId = id"/></div>diff --git a/app/components/trnForm/types.ts b/app/components/trnForm/types.tsindex 0ba4f8c3..d109e9b2 100644--- a/app/components/trnForm/types.ts+++ b/app/components/trnForm/types.ts@@ -1,5 +1,3 @@export type TrnFormUi = {- catsRootModal: booleanisShow: boolean- walletsModal: boolean}diff --git a/app/components/trnForm/useTrnsFormStore.ts b/app/components/trnForm/useTrnsFormStore.tsindex 441c17db..695cbd9a 100644--- a/app/components/trnForm/useTrnsFormStore.ts+++ b/app/components/trnForm/useTrnsFormStore.ts@@ -47,9 +47,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {})const ui = ref<TrnFormUi>({- catsRootModal: false,isShow: false,- walletsModal: false,})const modal = ref({@@ -122,9 +120,7 @@ export const useTrnsFormStore = defineStore('trnForm', () => {values.walletId = nullui.value = {- catsRootModal: false,isShow: false,- walletsModal: false,}modal.value = {description: false,@@ -241,20 +237,15 @@ export const useTrnsFormStore = defineStore('trnForm', () => {ui.value.isShow = true}- function trnFormCreate(props?: { categoryId?: CategoryId, walletId?: WalletId }) {+ function trnFormCreate() {setValues({action: 'create',categoriesIds: categoriesStore.categoriesIdsForTrnValues,trn: trnsStore.lastCreatedTrnItem,- walletId: props?.walletId ?? walletsStore.sortedIds[0],+ walletId: walletsStore.sortedIds[0],walletsIds: walletsStore.sortedIds,})ui.value.isShow = true-- if (props) {- if (props.categoryId)- values.categoryId = props.categoryId- }}function trnFormDuplicate(trnId: TrnId) {@@ -289,7 +280,6 @@ export const useTrnsFormStore = defineStore('trnForm', () => {onClose,onSubmit,openTrnFormModal,- setValues,trnFormCreate,trnFormDuplicate,trnFormEdit,diff --git a/app/components/trnForm/utils/calculate.ts b/app/components/trnForm/utils/calculate.tsindex 232c134b..d1aad091 100644--- a/app/components/trnForm/utils/calculate.ts+++ b/app/components/trnForm/utils/calculate.ts@@ -51,7 +51,7 @@ export function evaluateExpression(value: string): number {return result <= Number.MAX_SAFE_INTEGER ? Math.abs(result) : 0}catch {- return Number.isInteger(value) ? Number(value) : 0+ return 0}}diff --git a/app/components/trnForm/utils/validate.test.ts b/app/components/trnForm/utils/validate.test.tsnew file mode 100644index 00000000..d8659c81--- /dev/null+++ b/app/components/trnForm/utils/validate.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest'++import { validate } from '~/components/trnForm/utils/validate'+import { TrnType } from '~/components/trns/types'++const now = Date.now()++const validTransaction = {+ amount: 100,+ categoryId: 'food',+ date: now,+ type: TrnType.Expense,+ updatedAt: now,+ walletId: 'w1',+}++const validTransfer = {+ categoryId: 'transfer' as const,+ date: now,+ expenseAmount: 100,+ expenseWalletId: 'w1',+ incomeAmount: 100,+ incomeWalletId: 'w2',+ type: TrnType.Transfer,+ updatedAt: now,+}++describe('validate', () => {+ it('returns null for valid transaction', () => {+ expect(validate(validTransaction)).toBeNull()+ })++ it('returns amountEmpty when amount is 0', () => {+ expect(validate({ ...validTransaction, amount: 0 })).toBe('trnForm.errors.amountEmpty')+ })++ it('returns selectWallet when walletId is empty', () => {+ expect(validate({ ...validTransaction, walletId: '' })).toBe('trnForm.errors.selectWallet')+ })++ it('returns selectCategory when categoryId is empty', () => {+ expect(validate({ ...validTransaction, categoryId: '' })).toBe('trnForm.errors.selectCategory')+ })++ it('returns null for valid transfer', () => {+ expect(validate(validTransfer)).toBeNull()+ })++ it('returns transferSameWallet when wallets are the same', () => {+ expect(validate({ ...validTransfer, incomeWalletId: 'w1' })).toBe('trnForm.errors.transferSameWallet')+ })++ it('returns transferAmountEmpty when transfer amount is 0', () => {+ expect(validate({ ...validTransfer, expenseAmount: 0 })).toBe('trnForm.errors.transferAmountEmpty')+ })+})diff --git a/app/components/trns/Item.vue b/app/components/trns/Item.vueindex fddc5c90..55a4c050 100644--- a/app/components/trns/Item.vue+++ b/app/components/trns/Item.vue@@ -64,7 +64,6 @@ const emit = defineEmits<{class="grid grow gap-0.5"><CategoriesName- v-if="trnItem.type !== TrnType.Transfer":category="trnItem.category":parentCategory="trnItem.categoryParent"isShowDots@@ -118,9 +117,6 @@ const emit = defineEmits<{<template v-if="trnItem.incomeAmount !== trnItem.expenseAmount"><Amount:amount="trnItem.incomeAmount || trnItem.amount"- :class="{- 'opacity-0': trnItem.incomeAmount === trnItem.expenseAmount,- }":currencyCode="trnItem.incomeWallet.currency":type="TrnType.Income"colorize="income"diff --git a/app/components/trns/List.vue b/app/components/trns/List.vueindex 1ec86132..1a84ab41 100644--- a/app/components/trns/List.vue+++ b/app/components/trns/List.vue@@ -2,7 +2,6 @@import type { TrnId, TrnsViewType } from '~/components/trns/types'import { useAmount } from '~/components/amount/useAmount'-import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useDateFormats } from '~/components/date/useDateFormats'import { getStartOf } from '~/components/date/utils'@@ -12,7 +11,6 @@ import { useTrnsStore } from '~/components/trns/useTrnsStore'const {alt,- initTrnType = 'all',isShowDates,isShowExpense,isShowFilterByDesc,@@ -25,7 +23,6 @@ const {trnsIds = [],} = defineProps<{alt?: boolean- initTrnType?: TrnsViewTypeisShowDates?: booleanisShowExpense?: booleanisShowFilterByDesc?: boolean@@ -43,7 +40,6 @@ const emit = defineEmits<{}>()const currenciesStore = useCurrenciesStore()-const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()const trnsFormStore = useTrnsFormStore()@@ -51,7 +47,7 @@ const { getTotalOfTrnsIds } = useAmount()const { t } = useI18n()const { formatDate } = useDateFormats()const isShowWithDesc = ref(false)-const filterBy = ref<TrnsViewType>(initTrnType)+const filterBy = ref<TrnsViewType>('all')const pageNumber = ref(1)type TypeFilter = {@@ -102,7 +98,7 @@ const filteredByTypeIds = computed(() => {return trnsStore.items[id]?.categoryId === 'adjustment'if (filterBy.value === 'transfer')- return trnsStore.items[id]?.type === selectedTypeFilter.value?.type || categoriesStore.transferCategoriesIds.includes(trnsStore.items[id]?.categoryId)+ return trnsStore.items[id]?.type === selectedTypeFilter.value?.type || trnsStore.items[id]?.categoryId === 'transfer'return trnsStore.items[id]?.type === selectedTypeFilter.value?.type})diff --git a/app/components/trns/getTrns.test.ts b/app/components/trns/getTrns.test.tsindex 8e7dcc62..8b741872 100644--- a/app/components/trns/getTrns.test.ts+++ b/app/components/trns/getTrns.test.ts@@ -13,8 +13,8 @@ describe('get Transactions IDs', () => {'transactionExpenseWalletCashUSD400','transferExpenseWalletCreditUSD40IncomeWalletCashUSD40','transferExpenseWalletCashUSD10IncomeWalletRUB700',- 'transferCategoryIncomeWalletCashUSD30',- 'transferCategoryIdExpenseWalletCashUSD30',+ 'adjustmentIncomeWalletCashUSD30',+ 'adjustmentExpenseWalletCashUSD30',]))})@@ -39,8 +39,8 @@ describe('get Transactions IDs', () => {'transferExpenseWalletCreditUSD40IncomeWalletCashUSD40','transferExpenseWalletRUB300IncomeWalletCreditUSD10','transferExpenseWalletCashUSD10IncomeWalletRUB700',- 'transferCategoryIncomeWalletCashUSD30',- 'transferCategoryIdExpenseWalletCashUSD30',+ 'adjustmentIncomeWalletCashUSD30',+ 'adjustmentExpenseWalletCashUSD30',]))})})diff --git a/app/components/trns/getTrns.ts b/app/components/trns/getTrns.tsindex 7d552695..379e48b9 100644--- a/app/components/trns/getTrns.ts+++ b/app/components/trns/getTrns.ts@@ -11,11 +11,6 @@ export function getTrnsIds(props: TrnsGetterProps) {const typesSet = Array.isArray(props.trnsTypes) ? new Set(props.trnsTypes) : nullconst filters: Array<(ids: TrnId[]) => TrnId[]> = [- // Type filter- ids => props.trnType != null- ? ids.filter(id => props.trnsItems?.[id]?.type === props.trnType)- : ids,-// Types filterids => typesSet? ids.filter(id => typesSet.has(props.trnsItems?.[id]?.type))diff --git a/app/components/trns/pages/History.vue b/app/components/trns/pages/History.vueindex 81fb980e..62b43bed 100644--- a/app/components/trns/pages/History.vue+++ b/app/components/trns/pages/History.vue@@ -20,8 +20,6 @@ useHead({const trnsIds = computed(() => trnsStore.getStoreTrnsIds({categoriesIds: filter.categoriesIds.value,walletsIds: filter.walletsIds.value,-}, {- includesChildCategories: true,}))const lastFilter = useStorage<{diff --git a/app/components/trns/types.ts b/app/components/trns/types.tsindex 09b601ca..f9b9f825 100644--- a/app/components/trns/types.ts+++ b/app/components/trns/types.ts@@ -73,8 +73,6 @@ export type TrnsGetterProps = {trnsIds?: TrnId[]trnsItems?: TrnstrnsTypes?: TrnType[]- trnType?: TrnType- untilDate?: numberwalletsIds?: WalletId[]}diff --git a/app/components/trns/useTrnsStore.test.ts b/app/components/trns/useTrnsStore.test.tsindex 82d2bdff..581022e0 100644--- a/app/components/trns/useTrnsStore.test.ts+++ b/app/components/trns/useTrnsStore.test.ts@@ -1,32 +1,10 @@+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'-// --- Mocks -----const localforageStore = new Map<string, any>()-vi.mock('localforage', () => ({- default: {- getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),- removeItem: vi.fn((key: string) => {- localforageStore.delete(key)- return Promise.resolve()- }),- setItem: vi.fn((key: string, value: any) => {- localforageStore.set(key, value)- return Promise.resolve()- }),- },-}))--vi.mock('@vueuse/core', () => ({- useDebounceFn: (fn: (...args: any[]) => any) => fn,-}))--vi.mock('vue-deepunref', () => ({- deepUnref: (v: any) => v,-}))+// --- Entity-specific mocks ---vi.mock('~~/services/convex/api', () => ({convexTrnsToMap: (arr: any[]) => {@@ -43,32 +21,6 @@ const mutationMock = vi.fn(() => Promise.resolve())const queryMock = vi.fn(() => Promise.resolve(null))const onUpdateMock = vi.fn()-// Mock Convex composables (auto-imported in Nuxt)-vi.stubGlobal('useConvexClient', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,- query: queryMock,-}))-vi.stubGlobal('useConvexClientComposable', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,- query: queryMock,-}))-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.stubGlobal('useConvexApi', () => ({- api: {- trns: { create: 'trns.create', delta: 'trns.delta', ensureSyncMeta: 'trns.ensureSyncMeta', idsHash: 'trns.idsHash', list: 'trns.list', remove: 'trns.remove', update: 'trns.update' },- },-}))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' },@@ -80,37 +32,10 @@ vi.stubGlobal('useConvexClientWithApi', () => ({},}))-// Toast & i18n auto-imports-const toastAddMock = vi.fn()-vi.stubGlobal('useToast', () => ({ add: toastAddMock }))-vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))-vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))-vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))--// Emo helpers-vi.mock('~/assets/js/emo', () => ({- errorEmo: ['πΏ'],- random: (items: any[]) => items[0],-}))--// Pinia auto-imports-vi.stubGlobal('defineStore', (await import('pinia')).defineStore)-vi.stubGlobal('shallowRef', (await import('vue')).shallowRef)-vi.stubGlobal('computed', (await import('vue')).computed)--// Mock demo composable-vi.mock('~/components/demo/useDemo', () => ({- useDemo: () => ({- isDemo: { value: false },- }),-}))--// Mock dependent storesvi.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 } },- transferCategoriesIds: ['transfer'],}),}))@@ -120,11 +45,6 @@ vi.mock('~/components/wallets/useWalletsStore', () => ({}),}))-vi.mock('~/components/offline/replay', () => ({- isReplaying: () => false,-}))--// Mock offline helpers β spy on real implementationsconst offlineHelpers = await import('~/components/offline/helpers')vi.mock('~/components/offline/helpers', async (importOriginal) => {const actual = await importOriginal() as any@@ -139,7 +59,6 @@ vi.mock('~/components/offline/helpers', async (importOriginal) => {}})-// Re-import after mocksconst { useTrnsStore } = await import('~/components/trns/useTrnsStore')// --- Helpers ---@@ -159,12 +78,11 @@ function makeTrn(overrides: Partial<TrnItem> = {}): TrnItem {// --- Tests ---describe('useTrnsStore', () => {- beforeEach(() => {+ beforeEach(async () => {setActivePinia(createPinia())- localforageStore.clear()+ await localforage.clear()vi.clearAllMocks()mutationMock.mockReturnValue(Promise.resolve())- toastAddMock.mockClear()})afterEach(() => {@@ -183,13 +101,14 @@ describe('useTrnsStore', () => {expect(store.items!.trn1.amount).toBe(100)})- it('saves to localforage', () => {+ it('saves to localforage', async () => {const store = useTrnsStore()store.items = {}store.saveTrn({ id: 'trn1', values: makeTrn() })- expect(localforageStore.get('finapp.trns')).toHaveProperty('trn1')+ const saved = await localforage.getItem<any>('finapp.trns')+ expect(saved).toHaveProperty('trn1')})it('pushes to offline queue immediately', () => {@@ -233,14 +152,12 @@ describe('useTrnsStore', () => {store.saveTrn({ id: 'trn1', values: makeTrn() })- // Wait for .then() to resolveawait vi.waitFor(() => {expect(offlineHelpers.removeOfflineOp).toHaveBeenCalledWith('trns', 'trn1')})})it('keeps offline queue when mutation fails', async () => {- // Mutation returns a never-resolving promise to simulate offlinemutationMock.mockReturnValue(new Promise(() => {}))const store = useTrnsStore()@@ -248,7 +165,6 @@ describe('useTrnsStore', () => {store.saveTrn({ id: 'trn1', values: makeTrn() })- // Give time for potential .then() β it shouldn't fireawait new Promise(r => setTimeout(r, 10))expect(offlineHelpers.removeOfflineOp).not.toHaveBeenCalled()@@ -265,6 +181,7 @@ describe('useTrnsStore', () => {})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()@@ -323,6 +240,7 @@ describe('useTrnsStore', () => {})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()@@ -387,8 +305,7 @@ describe('useTrnsStore', () => {await store.initTrns()expect(store.items).toHaveProperty('trn1')- const syncMeta = localforageStore.get('finapp.trns.syncMeta')- // Hash is computed locally from list result, not fetched from server+ const syncMeta = await localforage.getItem<any>('finapp.trns.syncMeta')expect(syncMeta).toHaveProperty('idsHash')expect(syncMeta.idsHash).toBeTruthy()expect(syncMeta).not.toHaveProperty('serverIds')@@ -415,11 +332,10 @@ describe('useTrnsStore', () => {})it('performs delta sync with hash match (no deletion check)', async () => {- // Pre-populate cache and sync meta β compute real hash for trn1const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')const hash = computeHash(['trn1'])- localforageStore.set('finapp.trns', { trn1: makeTrn() })- localforageStore.set('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })+ 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')@@ -436,16 +352,14 @@ describe('useTrnsStore', () => {})it('performs delta sync with hash mismatch (falls back to fullSync)', async () => {- // Cache has trn1 and trn2, but trn2 was deleted on server- localforageStore.set('finapp.trns', { trn1: makeTrn(), trn2: makeTrn() })- localforageStore.set('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })+ await localforage.setItem('finapp.trns', { trn1: makeTrn(), trn2: makeTrn() })+ await localforage.setItem('finapp.trns.syncMeta', { idsHash: 'old_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: 'new_hash', serverTime: 1700000002000 })- // fullSync fallback: list returns only trn1if (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)@@ -461,8 +375,8 @@ describe('useTrnsStore', () => {it('applies delta changes and updates hash', async () => {const { xorIdsHash: computeHash } = await import('~~/utils/fnv1a')const hash = computeHash(['trn1'])- localforageStore.set('finapp.trns', { trn1: makeTrn({ amount: 100 }) })- localforageStore.set('finapp.trns.syncMeta', { idsHash: hash, lastSyncedAt: 1700000000000 })+ 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')@@ -479,8 +393,8 @@ describe('useTrnsStore', () => {})it('clears store when user has no trns (idsHash returns null)', async () => {- localforageStore.set('finapp.trns', { trn1: makeTrn() })- localforageStore.set('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })+ await localforage.setItem('finapp.trns', { trn1: makeTrn() })+ await localforage.setItem('finapp.trns.syncMeta', { idsHash: 'old_hash', lastSyncedAt: 1700000000000 })queryMock.mockImplementation(() => Promise.resolve(null))diff --git a/app/components/trns/useTrnsStore.ts b/app/components/trns/useTrnsStore.tsindex 6fdf9753..28d2e95e 100644--- a/app/components/trns/useTrnsStore.ts+++ b/app/components/trns/useTrnsStore.ts@@ -20,10 +20,6 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'import { createDebouncedPersist, handleMutationResult, isPersistBlocked, mergeOfflineOps, pushDeleteOp, pushSaveOp } from '~/composables/useStoreSync'import { createLogger } from '~/utils/logger'-type TrnsGetterParams = {- includesChildCategories?: boolean-}-const logger = createLogger('trns')async function fetchAllPages<T>(@@ -58,14 +54,12 @@ export const useTrnsStore = defineStore('trns', () => {const items = shallowRef<Trns | null>(null)- function getStoreTrnsIds(props: TrnsGetterProps, params?: TrnsGetterParams) {- const categoriesIds = params?.includesChildCategories- ? categoriesStore.getTransactibleIds(props.categoriesIds)- : props.categoriesIds-+ function getStoreTrnsIds(props: TrnsGetterProps) {return getTrnsIds({...props,- categoriesIds,+ categoriesIds: props.categoriesIds?.length+ ? categoriesStore.getTransactibleIds(props.categoriesIds)+ : props.categoriesIds,trnsItems: items.value ?? undefined,})}@@ -90,13 +84,12 @@ export const useTrnsStore = defineStore('trns', () => {if (!hasItems.value)return undefined- const transferIds = new Set(categoriesStore.transferCategoriesIds)let latestId: TrnId | undefinedlet latestDate = -1for (const trnId of Object.keys(items.value)) {const trn = items.value[trnId]- if (!trn || trn.type === TrnType.Transfer || trn.categoryId === 'adjustment' || transferIds.has(trn.categoryId))+ if (!trn || trn.type === TrnType.Transfer || trn.categoryId === 'adjustment' || trn.categoryId === 'transfer')continueif (trn.date > latestDate) {latestDate = trn.date@@ -424,7 +417,6 @@ export const useTrnsStore = defineStore('trns', () => {hasItems,initTrns,items,- lastCreatedTrnId,lastCreatedTrnItem,removeTrnsFromStore,saveTrn,diff --git a/app/components/ui/ButtonAccent.vue b/app/components/ui/ButtonAccent.vueindex 5336cf60..3e55fb3a 100644--- a/app/components/ui/ButtonAccent.vue+++ b/app/components/ui/ButtonAccent.vue@@ -6,7 +6,7 @@ const props = defineProps<{variant?: 'outline' | 'ghost' | 'solid'}>()-const emit = defineEmits(['click'])+const emit = defineEmits<{ click: [] }>()</script><template>diff --git a/app/components/ui/ButtonWithRight.vue b/app/components/ui/ButtonWithRight.vueindex dfb1b408..fce874a0 100644--- a/app/components/ui/ButtonWithRight.vue+++ b/app/components/ui/ButtonWithRight.vue@@ -1,8 +1,4 @@<script setup lang="ts">-const props = defineProps<{- isShowTitle?: boolean-}>()-const emit = defineEmits<{click: [e: Event]}>()@@ -10,39 +6,20 @@ const emit = defineEmits<{<template><div>- <UiTitleSection- v-if="props.isShowTitle"- class="pb-2"- >- <slot name="label" />- </UiTitleSection>-<UiElementclass="@container/element"insideClasses="max-w-lg w-full !min-h-[42px] bg-item-3 px-2 @xs/element:pl-4 @xs/element:pr-3 block @xs/element:flex @xs/element:flex-wrap gap-0 gap-x-2"@click="(e: Event) => emit('click', e)">- <div- v-if="!props.isShowTitle"- class="text-muted text-sm"- >+ <div class="text-muted text-sm"><slot name="label" /></div>- <div- :class="{- '@xs/element:ml-auto': !props.isShowTitle,- 'grow': props.isShowTitle,- }"- class="flex items-center gap-1 text-base"- >+ <div class="flex items-center gap-1 text-base @xs/element:ml-auto"><slot name="value" /><Iconname="lucide:chevron-down"class="text-4"- :class="{- 'ml-auto': props.isShowTitle,- }"/></div></UiElement>diff --git a/app/components/ui/IconBase.vue b/app/components/ui/IconBase.vueindex af8400f8..a4815c58 100644--- a/app/components/ui/IconBase.vue+++ b/app/components/ui/IconBase.vue@@ -6,10 +6,6 @@ const props = defineProps<{name: stringsize?: number}>()--const emit = defineEmits<{- click: [e: Event]-}>()</script><template>@@ -22,7 +18,6 @@ const emit = defineEmits<{[cn('rounded-full w-7 p-1.5', props.class)]: props.invert,}"class="flex-center text-icon-primary aspect-square overflow-hidden"- @click="(e: Event) => emit('click', e)"><Icon:name="props.name"diff --git a/app/components/ui/SwitchItem.vue b/app/components/ui/SwitchItem.vueindex f9c8fadf..e2215c54 100644--- a/app/components/ui/SwitchItem.vue+++ b/app/components/ui/SwitchItem.vue@@ -18,10 +18,7 @@ function handleClick() {class="flex grow items-center gap-3 rounded-lg p-2 text-sm hover:bg-(--item-5)"@click="handleClick">- <FormSwitch- v-if="checkboxValue !== undefined"- :value="checkboxValue"- />+ <FormSwitch :value="checkboxValue" /><div class="text-muted grow">{{ title }}diff --git a/app/components/ui/TabsItemFill.vue b/app/components/ui/TabsItemFill.vueindex 6a882894..8f60923e 100644--- a/app/components/ui/TabsItemFill.vue+++ b/app/components/ui/TabsItemFill.vue@@ -3,7 +3,7 @@ const props = defineProps<{isActive?: boolean}>()-const emit = defineEmits(['click'])+const emit = defineEmits<{ click: [] }>()</script><template>diff --git a/app/components/ui/TabsItemPill.vue b/app/components/ui/TabsItemPill.vueindex cfde4e77..477aedc8 100644--- a/app/components/ui/TabsItemPill.vue+++ b/app/components/ui/TabsItemPill.vue@@ -4,7 +4,7 @@ const { isActive = false, variant = 'default' } = defineProps<{variant?: 'default' | 'outline'}>()-const emit = defineEmits(['click'])+const emit = defineEmits<{ click: [] }>()</script><template>diff --git a/app/components/ui/TextMuted.vue b/app/components/ui/TextMuted.vueindex 92da7199..60e311ec 100644--- a/app/components/ui/TextMuted.vue+++ b/app/components/ui/TextMuted.vue@@ -2,10 +2,6 @@const { size = 'xs' } = defineProps<{size?: 'xs' | 'sm'}>()--const emit = defineEmits<{- click: [e: Event]-}>()</script><template>@@ -14,7 +10,6 @@ const emit = defineEmits<{'font-primary text-muted leading-none',size === 'xs' ? 'text-xs' : 'text-sm',)"- @click="(e: Event) => emit('click', e)"><slot /></div>diff --git a/app/components/ui/TextSubtitle.vue b/app/components/ui/TextSubtitle.vueindex 344f863c..061743c8 100644--- a/app/components/ui/TextSubtitle.vue+++ b/app/components/ui/TextSubtitle.vue@@ -1,14 +1,5 @@-<script setup lang="ts">-const emit = defineEmits<{- click: [e: Event]-}>()-</script>-<template>- <div- class="text-2xs text-2 leading-none lg:text-sm"- @click="(e: Event) => emit('click', e)"- >+ <div class="text-2xs text-2 leading-none lg:text-sm"><slot /></div></template>diff --git a/app/components/ui/TitleSection.vue b/app/components/ui/TitleSection.vueindex cef1d301..f114faaf 100644--- a/app/components/ui/TitleSection.vue+++ b/app/components/ui/TitleSection.vue@@ -2,10 +2,6 @@const { size = 'md' } = defineProps<{size?: 'sm' | 'md'}>()--const emit = defineEmits<{- click: [e: Event]-}>()</script><template>@@ -14,7 +10,6 @@ const emit = defineEmits<{'font-tertiary text-muted leading-none font-semibold',size === 'md' && 'text-base',)"- @click="(e: Event) => emit('click', e)"><slot /></div>diff --git a/app/components/ui/Toggle.vue b/app/components/ui/Toggle.vueindex 8bf1b675..dfb0ef65 100644--- a/app/components/ui/Toggle.vue+++ b/app/components/ui/Toggle.vue@@ -3,7 +3,6 @@ import { useStorage } from '@vueuse/core'const props = defineProps<{initStatus?: boolean- openPadding?: stringstorageKey?: string}>()@@ -22,7 +21,6 @@ const isShown = useStorage(`${props.storageKey}`, props.initStatus)<divv-if="isShown"- :class="[props.openPadding]"><slot:toggle="() => isShown = !isShown"diff --git a/app/components/ui/ToggleControlled.vue b/app/components/ui/ToggleControlled.vueindex 03493cba..818d3fbf 100644--- a/app/components/ui/ToggleControlled.vue+++ b/app/components/ui/ToggleControlled.vue@@ -1,8 +1,6 @@<script setup lang="ts">const props = defineProps<{isShown: boolean- lineWidth?: number- openPadding?: string}>()const emit = defineEmits<{@@ -20,21 +18,10 @@ const emit = defineEmits<{/></div>- <div- v-if="isShown"- :class="[props.openPadding]"- >+ <div v-if="isShown"><slot:toggle="() => emit('click', !props.isShown)"/></div>-- <div- v-if="lineWidth && !isShown"- :class="cn('mx-2 h-px bg-(--item-5) group-last:hidden',- lineWidth === 3 && 'ml-12',- lineWidth === 2 && 'ml-11',- )"- /></div></template>diff --git a/app/components/ui/ToggleWithStorage.vue b/app/components/ui/ToggleWithStorage.vueindex 14dd08c0..ebc997a6 100644--- a/app/components/ui/ToggleWithStorage.vue+++ b/app/components/ui/ToggleWithStorage.vue@@ -4,7 +4,6 @@ import { useStorage } from '@vueuse/core'const props = defineProps<{initStatus?: booleanlineWidth?: number- openPadding?: stringstorageKey?: string}>()@@ -14,9 +13,6 @@ const isShown = useStorage(`ui-toggle-${props.storageKey}`, props.initStatus)<template><divclass="group relative"- :class="{- [props.openPadding]: props.openPadding && isShown,- }"><div class="-my-px overflow-hidden"><divdiff --git a/app/components/user/useUserStore.test.ts b/app/components/user/useUserStore.test.tsindex 972659c2..e20e52e0 100644--- a/app/components/user/useUserStore.test.ts+++ b/app/components/user/useUserStore.test.ts@@ -1,43 +1,13 @@+import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ref } from 'vue'-// --- Mocks -----const localforageStore = new Map<string, any>()-vi.mock('localforage', () => ({- default: {- clear: vi.fn(() => {- localforageStore.clear()- return Promise.resolve()- }),- getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),- setItem: vi.fn((key: string, value: any) => {- localforageStore.set(key, value)- return Promise.resolve()- }),- },-}))--vi.mock('vue-deepunref', () => ({- deepUnref: (v: any) => v,-}))+// --- Entity-specific mocks ---const mutationMock = vi.fn(() => Promise.resolve())const queryMock = vi.fn(() => Promise.resolve(null))-vi.stubGlobal('useConvexClient', () => ({- mutation: mutationMock,- query: queryMock,-}))-vi.stubGlobal('useConvexClientComposable', () => ({- mutation: mutationMock,- query: queryMock,-}))-vi.stubGlobal('useConvexApi', () => ({- api: {- userSettings: { get: 'userSettings.get', upsert: 'userSettings.upsert' },- },-}))vi.stubGlobal('useConvexClientWithApi', () => ({api: {userSettings: { get: 'userSettings.get', upsert: 'userSettings.upsert' },@@ -48,16 +18,10 @@ vi.stubGlobal('useConvexClientWithApi', () => ({},}))-vi.stubGlobal('defineStore', (await import('pinia')).defineStore)-const { computed, ref } = await import('vue')-vi.stubGlobal('computed', computed)-vi.stubGlobal('ref', ref)-const setLocaleMock = vi.fn()vi.stubGlobal('useNuxtApp', () => ({$i18n: { setLocale: setLocaleMock },}))-vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))const useSessionMock = vi.fn(() => ref({ data: null, isPending: false }))vi.stubGlobal('useAuth', () => ({@@ -83,12 +47,6 @@ vi.mock('~/components/wallets/useWalletsStore', () => ({}),}))-vi.mock('~/components/demo/useDemo', () => ({- useDemo: () => ({- isDemo: { value: false },- }),-}))-vi.mock('~/composables/useAuthCookie', () => ({clearAuthCookie: vi.fn(),}))@@ -98,9 +56,9 @@ const { useUserStore } = await import('~/components/user/useUserStore')// --- Tests ---describe('useUserStore', () => {- beforeEach(() => {+ beforeEach(async () => {setActivePinia(createPinia())- localforageStore.clear()+ await localforage.clear()vi.clearAllMocks()})@@ -115,17 +73,19 @@ describe('useUserStore', () => {expect(store.baseCurrency).toBe('EUR')})- it('persists to localforage', () => {+ it('persists to localforage', async () => {const store = useUserStore()store.setUserBaseCurrency('EUR')- const saved = localforageStore.get('finapp.userSettings')+ 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')@@ -137,12 +97,10 @@ describe('useUserStore', () => {})it('skips Convex mutation in demo mode', async () => {- // Override isDemo for this testconst demoModule = await import('~/components/demo/useDemo')const original = demoModule.useDemo;(demoModule as any).useDemo = () => ({ ...original(), isDemo: { value: true } })- // Need fresh store to pick up new mocksetActivePinia(createPinia())const store = useUserStore()store.saveUserBaseCurrency('GBP')@@ -150,7 +108,6 @@ describe('useUserStore', () => {expect(store.baseCurrency).toBe('GBP')expect(mutationMock).not.toHaveBeenCalled()- // Restore;(demoModule as any).useDemo = original})})@@ -164,17 +121,19 @@ describe('useUserStore', () => {expect(setLocaleMock).toHaveBeenCalledWith('ru')})- it('persists to localforage', () => {+ it('persists to localforage', async () => {const store = useUserStore()store.setUserLocale('ru')- const saved = localforageStore.get('finapp.userSettings')+ const saved = await localforage.getItem<any>('finapp.userSettings')expect(saved).toEqual({ baseCurrency: 'USD', locale: 'ru' })})})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')@@ -198,7 +157,6 @@ describe('useUserStore', () => {expect(setLocaleMock).toHaveBeenCalledWith('ru')expect(mutationMock).not.toHaveBeenCalled()- // Restore;(demoModule as any).useDemo = original})})@@ -247,12 +205,12 @@ describe('useUserStore', () => {})describe('persistUserSettings', () => {- it('saves both baseCurrency and locale together', () => {+ it('saves both baseCurrency and locale together', async () => {const store = useUserStore()store.setUserBaseCurrency('EUR')store.setUserLocale('ru')- const saved = localforageStore.get('finapp.userSettings')+ const saved = await localforage.getItem<any>('finapp.userSettings')expect(saved).toEqual({ baseCurrency: 'EUR', locale: 'ru' })})})diff --git a/app/components/user/useUserStore.ts b/app/components/user/useUserStore.tsindex 1e803314..50a68a2c 100644--- a/app/components/user/useUserStore.ts+++ b/app/components/user/useUserStore.ts@@ -53,8 +53,6 @@ export const useUserStore = defineStore('user', () => {return null // Session checked, no user})- const sessionUid = computed(() => session.value?.data?.user?.id ?? null)-const uid = computed<string | null>(() => currentUser.value?.uid || null)function setUser(values: User | null) {@@ -244,12 +242,10 @@ export const useUserStore = defineStore('user', () => {removeAllUserData,saveUserBaseCurrency,saveUserLocale,- sessionUid,setUser,setUserBaseCurrency,setUserLocale,signOut,uid,- user,}})diff --git a/app/components/wallets/CurrenciesToggleDep.vue b/app/components/wallets/CurrenciesToggleDep.vuedeleted file mode 100644index 06829a9e..00000000--- a/app/components/wallets/CurrenciesToggleDep.vue+++ /dev/null@@ -1,54 +0,0 @@-<script setup lang="ts">-import type { CurrencyCode } from '~/components/currencies/types'-import type { WalletsCurrencyFiltered } from '~/components/wallets/types'--import { useWalletsStore } from '~/components/wallets/useWalletsStore'--defineProps<{- currencyFiltered: WalletsCurrencyFiltered-}>()--const emit = defineEmits<{- selectFilterCurrency: [code: CurrencyCode]-}>()--const { t } = useI18n()-const walletsStore = useWalletsStore()-</script>--<template>- <UiToggleWithStorage- :initStatus="true"- :lineWidth="0"- class="grid md:max-w-lg @xl/page:max-w-xl"- storageKey="finapp-wallets-currencies"- >- <template #header="{ toggle, isShown }">- <UiTitleCollapse- :isShown- @click="toggle"- >- {{ t('wallets.filterByCurrency') }}- {{ (currencyFiltered !== 'all' && !isShown) ? currencyFiltered : '' }}- </UiTitleCollapse>- </template>-- <UiTabsScroll class="flex gap-1 px-2 @xl/page:px-0">- <UiTabsItemFill- :isActive="currencyFiltered === 'all'"- @click="emit('selectFilterCurrency', 'all')"- >- {{ t('common.all') }}- </UiTabsItemFill>-- <UiTabsItemFill- v-for="currency in walletsStore.currenciesUsed"- :key="currency"- :isActive="currencyFiltered === currency"- @click="emit('selectFilterCurrency', currency)"- >- {{ currency }}- </UiTabsItemFill>- </UiTabsScroll>- </UiToggleWithStorage>-</template>diff --git a/app/components/wallets/List.vue b/app/components/wallets/List.vueindex e19e012f..77a10d4e 100644--- a/app/components/wallets/List.vue+++ b/app/components/wallets/List.vue@@ -55,7 +55,7 @@ onMounted(() => stateLimit.value = limit){{ t('wallets.showAll') }}</template>- <template v-else-if="stateLimit !== limit">+ <template v-else>{{ t('wallets.showOnly') }} {{ limit }}</template></div>diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vueindex 5899b5c9..ad736b80 100644--- a/app/components/wallets/page/List.vue+++ b/app/components/wallets/page/List.vue@@ -7,6 +7,7 @@ import type { WalletId, WalletsGroupedBy } from '~/components/wallets/types'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { useUserStore } from '~/components/user/useUserStore'+import { useWalletContextMenu } from '~/components/wallets/useWalletContextMenu'import { useWalletsStore } from '~/components/wallets/useWalletsStore'import { showSuccessToast } from '~/composables/useStoreSync'@@ -28,7 +29,6 @@ const userStore = useUserStore()const trnsStore = useTrnsStore()const isSortModalOpen = ref(false)-const isShowBaseCurrencyModal = ref(false)const isOpen = ref(false)const deleteWalletId = ref<WalletId | null>(null)@@ -70,28 +70,14 @@ async function onDeleteConfirm() {}, 300)}-function getWalletContextMenuItems(walletId: WalletId) {- return [[- {- icon: 'lucide:pencil',- label: t('base.edit'),- onSelect: () => router.push(`/wallets/${walletId}/edit`),- },- ], [- {- color: 'error' as const,- icon: 'lucide:trash-2',- label: t('base.delete'),- onSelect: () => { deleteWalletId.value = walletId },- },- ]]-}+const { getWalletContextMenuItems } = useWalletContextMenu({+ onDelete: (walletId: WalletId) => { deleteWalletId.value = walletId },+})const groupedBy = useStorage<WalletsGroupedBy>('finapp-wallets-groupedBy', 'none')const {currencyFiltered,- isShowCurrencyFilter,onSelectFilterCurrency,selectedWalletsIds,selectedWalletsIdsWithCurrency,@@ -419,22 +405,4 @@ const isSecondaryGroupingActive = computed(() =><!-- Sort Modal --><WalletsSortModal v-if="isSortModalOpen" @close="isSortModalOpen = false" />-- <!-- Base Currency Modal -->- <CurrenciesModal- v-if="isShowBaseCurrencyModal"- :activeCode="currenciesStore.base"- @select="userStore.setUserBaseCurrency"- @close="isShowBaseCurrencyModal = false"- />-- <!-- Currency Filter Modal -->- <CurrenciesModal- v-if="walletsStore.currenciesUsed.length > 1 && isShowCurrencyFilter"- :activeCode="currencyFiltered"- isShowAllButton- isHideUnused- @select="onSelectFilterCurrency"- @close="isShowCurrencyFilter = false"- /></template>diff --git a/app/components/wallets/page/id/Index.vue b/app/components/wallets/page/id/Index.vueindex 219506cd..a637c481 100644--- a/app/components/wallets/page/id/Index.vue+++ b/app/components/wallets/page/id/Index.vue@@ -110,7 +110,7 @@ async function onDeleteConfirm() {<template><UiPage v-if="wallet"><StatHeader- :config="{ isShowCategories: true }"+ :config="{}":filter="{ isShowCategories: true }"><template #title>diff --git a/app/components/wallets/page/useWalletsPageFilter.ts b/app/components/wallets/page/useWalletsPageFilter.tsindex 99b38e34..a193139c 100644--- a/app/components/wallets/page/useWalletsPageFilter.ts+++ b/app/components/wallets/page/useWalletsPageFilter.ts@@ -46,20 +46,16 @@ export function useWalletsPageFilter(groupedBy: Ref<WalletsGroupedBy>) {})})- const isShowCurrencyFilter = ref(false)-function onSelectFilterCurrency(code: CurrencyCode, toggle?: () => void) {if (currencyFiltered.value === code && toggle)toggle()walletViewType.value = 'total'currencyFiltered.value = code- isShowCurrencyFilter.value = false}return {currencyFiltered,- isShowCurrencyFilter,onSelectFilterCurrency,selectedWalletsIds,selectedWalletsIdsWithCurrency,diff --git a/app/components/wallets/useWalletContextMenu.ts b/app/components/wallets/useWalletContextMenu.tsnew file mode 100644index 00000000..5ff4572d--- /dev/null+++ b/app/components/wallets/useWalletContextMenu.ts@@ -0,0 +1,28 @@+import type { WalletId } from '~/components/wallets/types'++export function useWalletContextMenu(options?: {+ onDelete?: (walletId: WalletId) => void+}) {+ const { t } = useI18n()+ const router = useRouter()++ function getWalletContextMenuItems(walletId: WalletId) {+ const editGroup = [{+ icon: 'lucide:pencil',+ label: t('base.edit'),+ onSelect: () => router.push(`/wallets/${walletId}/edit`),+ }]++ if (!options?.onDelete)+ return [editGroup]++ return [editGroup, [{+ color: 'error' as const,+ icon: 'lucide:trash-2',+ label: t('base.delete'),+ onSelect: () => options.onDelete!(walletId),+ }]]+ }++ return { getWalletContextMenuItems }+}diff --git a/app/components/wallets/useWalletsStore.test.ts b/app/components/wallets/useWalletsStore.test.tsindex 38c697b1..7d11a9cc 100644--- a/app/components/wallets/useWalletsStore.test.ts+++ b/app/components/wallets/useWalletsStore.test.ts@@ -1,32 +1,10 @@+import localforage from 'localforage'import { createPinia, setActivePinia } from 'pinia'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { WalletItem } from '~/components/wallets/types'-// --- Mocks -----const localforageStore = new Map<string, any>()-vi.mock('localforage', () => ({- default: {- getItem: vi.fn((key: string) => Promise.resolve(localforageStore.get(key) ?? null)),- removeItem: vi.fn((key: string) => {- localforageStore.delete(key)- return Promise.resolve()- }),- setItem: vi.fn((key: string, value: any) => {- localforageStore.set(key, value)- return Promise.resolve()- }),- },-}))--vi.mock('@vueuse/core', () => ({- useDebounceFn: (fn: (...args: any[]) => any) => fn,-}))--vi.mock('vue-deepunref', () => ({- deepUnref: (v: any) => v,-}))+// --- Entity-specific mocks ---vi.mock('~~/services/convex/api', () => ({convexWalletsToMap: (v: any) => v,@@ -39,21 +17,6 @@ vi.mock('~~/utils/simple', () => ({const mutationMock = vi.fn(() => Promise.resolve())const onUpdateMock = vi.fn()-vi.stubGlobal('useConvexClient', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,-}))-vi.stubGlobal('useConvexClientComposable', () => ({- mutation: mutationMock,- onUpdate: onUpdateMock,-}))-vi.stubGlobal('asConvexId', (id: string) => id)-vi.stubGlobal('isLocalId', (id: string) => id.startsWith('local_'))-vi.stubGlobal('useConvexApi', () => ({- api: {- wallets: { create: 'wallets.create', list: 'wallets.list', remove: 'wallets.remove', update: 'wallets.update', updateOrder: 'wallets.updateOrder' },- },-}))vi.stubGlobal('useConvexClientWithApi', () => ({api: {wallets: { create: 'wallets.create', list: 'wallets.list', remove: 'wallets.remove', update: 'wallets.update', updateOrder: 'wallets.updateOrder' },@@ -64,23 +27,6 @@ vi.stubGlobal('useConvexClientWithApi', () => ({},}))-const toastAddMock = vi.fn()-vi.stubGlobal('useToast', () => ({ add: toastAddMock }))-vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))-vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))-vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))--vi.mock('~/assets/js/emo', () => ({- errorEmo: ['πΏ'],- random: (items: any[]) => items[0],-}))--vi.stubGlobal('defineStore', (await import('pinia')).defineStore)-const { computed, ref, shallowRef } = await import('vue')-vi.stubGlobal('computed', computed)-vi.stubGlobal('ref', ref)-vi.stubGlobal('shallowRef', shallowRef)-const removeTrnsFromStoreMock = vi.fn()vi.mock('~/components/trns/useTrnsStore', () => ({useTrnsStore: () => ({@@ -105,16 +51,6 @@ vi.mock('~/components/user/useUserStore', () => ({}),}))-vi.mock('~/components/demo/useDemo', () => ({- useDemo: () => ({- isDemo: { value: false },- }),-}))--vi.mock('~/components/offline/replay', () => ({- isReplaying: () => false,-}))-const offlineHelpers = await import('~/components/offline/helpers')vi.mock('~/components/offline/helpers', async (importOriginal) => {const actual = await importOriginal() as any@@ -125,6 +61,7 @@ vi.mock('~/components/offline/helpers', async (importOriginal) => {pushOfflineOp: vi.fn(actual.pushOfflineOp),removeOfflineOp: vi.fn(actual.removeOfflineOp),removeOfflineOpByType: vi.fn(actual.removeOfflineOpByType),+ removeOfflineOps: vi.fn(actual.removeOfflineOps),}})@@ -151,12 +88,11 @@ function makeWallet(overrides: Partial<WalletItem> = {}): WalletItem {// --- Tests ---describe('useWalletsStore', () => {- beforeEach(() => {+ beforeEach(async () => {setActivePinia(createPinia())- localforageStore.clear()+ await localforage.clear()vi.clearAllMocks()mutationMock.mockReturnValue(Promise.resolve())- toastAddMock.mockClear()})afterEach(() => {@@ -174,13 +110,14 @@ describe('useWalletsStore', () => {expect(store.items!.w1.name).toBe('Cash')})- it('saves to localforage', () => {+ it('saves to localforage', async () => {const store = useWalletsStore()store.items = {}store.saveWallet({ id: 'w1', values: makeWallet() })- expect(localforageStore.get('finapp.wallets')).toHaveProperty('w1')+ const saved = await localforage.getItem<any>('finapp.wallets')+ expect(saved).toHaveProperty('w1')})it('pushes to offline queue immediately', () => {@@ -243,6 +180,7 @@ describe('useWalletsStore', () => {})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()@@ -310,6 +248,7 @@ describe('useWalletsStore', () => {})it('shows toast on delete mutation failure', async () => {+ const { toastAddMock } = await import('~/test-utils/setup-store')mutationMock.mockReturnValue(Promise.reject(new Error('network')))const store = useWalletsStore()store.items = { w1: makeWallet() }@@ -358,6 +297,7 @@ describe('useWalletsStore', () => {})it('shows toast on failure', async () => {+ const { toastAddMock } = await import('~/test-utils/setup-store')mutationMock.mockReturnValue(Promise.reject(new Error('network')))const store = useWalletsStore()diff --git a/app/components/wallets/useWalletsStore.ts b/app/components/wallets/useWalletsStore.tsindex 989101ca..a5210dfa 100644--- a/app/components/wallets/useWalletsStore.ts+++ b/app/components/wallets/useWalletsStore.ts@@ -217,7 +217,6 @@ export const useWalletsStore = defineStore('wallets', () => {cancelPersist: () => debouncedPersist.cancel?.(),currenciesUsed,deleteWallet,- getWalletTotal,hasItems,initWallets,items,diff --git a/app/composables/useStoreSync.test.ts b/app/composables/useStoreSync.test.tsnew file mode 100644index 00000000..1cb50f7e--- /dev/null+++ b/app/composables/useStoreSync.test.ts@@ -0,0 +1,276 @@+import localforage from 'localforage'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { OfflineOp } from '~/components/offline/types'++// ---------------------------------------------------------------------------+// Mocks β entity-specific (offline helpers)+// ---------------------------------------------------------------------------+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('~/components/offline/helpers', () => ({+ getOfflineOpsByEntity: (...args: any[]) => getOfflineOpsByEntityMock(...args),+ pushOfflineOp: (...args: any[]) => pushOfflineOpMock(...args),+ removeOfflineOp: (...args: any[]) => removeOfflineOpMock(...args),+ removeOfflineOps: (...args: any[]) => removeOfflineOpsMock(...args),+}))++let isReplayingValue = false+vi.mock('~/components/offline/replay', () => ({+ isReplaying: () => isReplayingValue,+}))++beforeEach(async () => {+ vi.clearAllMocks()+ isReplayingValue = false+ await localforage.clear()+})++// ---------------------------------------------------------------------------+// mergeOfflineOps+// ---------------------------------------------------------------------------+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')++ // w1 overwritten with pending update data+ expect(result.w1).toEqual({ name: 'Updated' })+ // w2 deleted+ expect(result).not.toHaveProperty('w2')+ // w3 unchanged+ 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')++ // No pending ops for local_stale+ 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')+ })+})++// ---------------------------------------------------------------------------+// handleMutationResult β ID remap+// ---------------------------------------------------------------------------+describe('handleMutationResult', () => {+ it('remaps local_id β convexId on successful create', async () => {+ const { handleMutationResult, unblockPersist } = await import('~/composables/useStoreSync')+ 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'),+ })++ // local_abc replaced with convex_w1+ expect(items.value).not.toHaveProperty('local_abc')+ expect(items.value).toHaveProperty('convex_w1')+ expect(items.value!.convex_w1).toEqual({ name: 'Cash' })+ // existing untouched+ expect(items.value).toHaveProperty('existing')+ // returns remap info+ expect(remap).toEqual({ convexId: 'convex_w1', localId: 'local_abc' })+ // persisted to localforage+ 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'),+ })++ // Remap still happens+ expect(items.value).toHaveProperty('convex_w1')+ // But not persisted+ expect(await localforage.getItem('finapp.wallets')).toBeNull()++ // Cleanup+ const { unblockPersist } = await import('~/composables/useStoreSync')+ 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')),+ })++ // Toast shown with error color+ expect(toastAddMock).toHaveBeenCalledWith(+ expect.objectContaining({ color: 'error' }),+ )+ // Offline op NOT removed (so it can be retried)+ expect(removeOfflineOpMock).not.toHaveBeenCalled()+ })++ 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()+ })+})++// ---------------------------------------------------------------------------+// pushSaveOp / pushDeleteOp+// ---------------------------------------------------------------------------+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')++ const result = pushDeleteOp({ entity: 'wallets', id: 'w1', isDemo: true })++ expect(result).toBe(false)+ expect(pushOfflineOpMock).not.toHaveBeenCalled()+ })+})diff --git a/app/middleware/auth.global.test.ts b/app/middleware/auth.global.test.tsnew file mode 100644index 00000000..b55a9b7b--- /dev/null+++ b/app/middleware/auth.global.test.ts@@ -0,0 +1,287 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++// ---------------------------------------------------------------------------+// Shared mock state (hoisted so vi.mock factories can reference them)+// ---------------------------------------------------------------------------+const {+ clearAuthCookieMock,+ getSessionMock,+ hasAuthCookieMock,+ isDemoRef,+ navigateToMock,+ setAuthCookieMock,+} = vi.hoisted(() => ({+ clearAuthCookieMock: vi.fn(),+ getSessionMock: vi.fn(),+ hasAuthCookieMock: vi.fn(() => false),+ isDemoRef: { value: false },+ navigateToMock: vi.fn(),+ setAuthCookieMock: vi.fn(),+}))++// ---------------------------------------------------------------------------+// Module mocks+// ---------------------------------------------------------------------------+vi.mock('~/components/demo/useDemo', () => ({+ useDemo: () => ({ isDemo: isDemoRef }),+}))++vi.mock('~/composables/useAuthCookie', () => ({+ clearAuthCookie: clearAuthCookieMock,+ hasAuthCookie: hasAuthCookieMock,+ setAuthCookie: setAuthCookieMock,+ useAuthCookieSSR: () => ({ value: null }),+}))++vi.mock('~/utils/logger', () => ({+ createLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+}))++// ---------------------------------------------------------------------------+// Nuxt auto-import stubs+// ---------------------------------------------------------------------------+vi.stubGlobal('defineNuxtRouteMiddleware', (fn: any) => fn)+vi.stubGlobal('navigateTo', navigateToMock)+vi.stubGlobal('useAuth', () => ({ getSession: getSessionMock }))+vi.stubGlobal('getSafeRedirectPath', (value: unknown) => {+ if (typeof value === 'string' && value.startsWith('/') && !value.startsWith('//'))+ return value+ return '/dashboard'+})++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------+function createRoute(path: string, query: Record<string, string> = {}) {+ const qs = Object.entries(query).map(([k, v]) => `${k}=${v}`).join('&')+ 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>++async function loadMiddleware(): Promise<MiddlewareFn> {+ const mod = await import('~/middleware/auth.global')+ return mod.default as MiddlewareFn+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------+// Note: import.meta.prerender and import.meta.server are undefined in vitest,+// so SSR/prerender code paths are not exercised. All tests cover client behavior.++describe('auth.global middleware', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()+ isDemoRef.value = false+ hasAuthCookieMock.mockReturnValue(false)+ })++ // --- OTT handling ---++ 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()+ })+ })++ // --- /auth/callback passthrough ---++ 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()+ })+ })++ // --- Demo mode ---++ describe('demo mode', () => {+ beforeEach(() => {+ isDemoRef.value = true+ })++ it('redirects /login to the redirect query path', async () => {+ const middleware = await loadMiddleware()+ await 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'))++ expect(navigateToMock).toHaveBeenCalledWith('/dashboard')+ })++ it('passes through non-login routes', async () => {+ const middleware = await loadMiddleware()+ const result = await middleware(createRoute('/dashboard'))++ expect(navigateToMock).not.toHaveBeenCalled()+ expect(result).toBeUndefined()+ })+ })++ // --- Client: with auth cookie ---++ describe('client: with auth cookie', () => {+ beforeEach(() => {+ hasAuthCookieMock.mockReturnValue(true)+ getSessionMock.mockResolvedValue({ data: { user: { id: 'u1' } } })+ })++ it('passes through protected routes', async () => {+ const middleware = await loadMiddleware()+ const result = await 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'))++ 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()++ // First visit: session expired β clearCookie + redirect+ await middleware(createRoute('/dashboard'))+ await flushPromises()+ expect(clearAuthCookieMock).toHaveBeenCalled()+ expect(getSessionMock).toHaveBeenCalledOnce()++ // Simulate re-login: cookie is back, next navigation should call getSession again+ 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()++ // First call: getSession fails+ await middleware(createRoute('/dashboard'))+ await flushPromises()+ expect(getSessionMock).toHaveBeenCalledOnce()++ // Second call: sessionInitialized was reset, so getSession fires again+ getSessionMock.mockResolvedValue({ data: { user: { id: 'u1' } } })+ await middleware(createRoute('/settings'))++ expect(getSessionMock).toHaveBeenCalledTimes(2)+ })+ })++ // --- Client: no auth cookie ---++ describe('client: no auth cookie', () => {+ it('passes through /login without verification', async () => {+ const middleware = await loadMiddleware()+ const result = await 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' } } })+ 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'))++ expect(navigateToMock).toHaveBeenCalledWith({+ path: '/login',+ query: { redirect: '/settings' },+ })+ })++ it('omits redirect param for root path', async () => {+ getSessionMock.mockResolvedValue({ data: { user: null } })+ const middleware = await loadMiddleware()+ await 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' },+ })+ })+ })+})diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.tsindex 4e7336a4..5275e6b7 100644--- a/app/middleware/auth.global.ts+++ b/app/middleware/auth.global.ts@@ -73,6 +73,7 @@ export default defineNuxtRouteMiddleware(async (to) => {const user = session.data?.user || nullif (!user) {logger.error('Background getSession: session expired, redirecting to login')+ sessionInitialized = falseclearAuthCookie()navigateTo('/login')}diff --git a/app/plugins/convex.ts b/app/plugins/convex.tsindex 9c46bbce..6118a451 100644--- a/app/plugins/convex.ts+++ b/app/plugins/convex.ts@@ -18,12 +18,9 @@ export default defineNuxtPlugin(() => {}let convex: ConvexClient | ConvexHttpClient- let convexHttp: ConvexHttpClientif (import.meta.server) {- const httpClient = createConvexHttpClient(convexUrl)- convex = httpClient- convexHttp = httpClient+ convex = createConvexHttpClient(convexUrl)}else {const client = createConvexClient(convexUrl)@@ -131,13 +128,11 @@ export default defineNuxtPlugin(() => {)convex = client- convexHttp = createConvexHttpClient(convexUrl)}return {provide: {convex,- convexHttp,},}})diff --git a/app/test-utils/setup-store.ts b/app/test-utils/setup-store.tsnew file mode 100644index 00000000..3578cd03--- /dev/null+++ b/app/test-utils/setup-store.ts@@ -0,0 +1,71 @@+/**+ * Shared setup for Pinia store tests.+ *+ * Runs before each store test file (vitest setupFile).+ * 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.+ */+import { vi } from 'vitest'++// ---------------------------------------------------------------------------+// 1. Vue / Pinia auto-imports+// ---------------------------------------------------------------------------+const { computed, ref, shallowRef, watch } = await import('vue')+const { defineStore } = await import('pinia')++vi.stubGlobal('computed', computed)+vi.stubGlobal('ref', ref)+vi.stubGlobal('shallowRef', shallowRef)+vi.stubGlobal('watch', watch)+vi.stubGlobal('defineStore', defineStore)++// ---------------------------------------------------------------------------+// 2. VueUse auto-imports β synchronous for test predictability+// ---------------------------------------------------------------------------+vi.stubGlobal('useDebounceFn', (fn: (...args: any[]) => any) => fn)++// ---------------------------------------------------------------------------+// 3. Nuxt auto-imports+// ---------------------------------------------------------------------------+export const toastAddMock = vi.fn()++vi.stubGlobal('useToast', () => ({ add: toastAddMock }))+vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))+vi.stubGlobal('useNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))+vi.stubGlobal('tryUseNuxtApp', () => ({ $i18n: { t: (key: string) => key } }))++// ---------------------------------------------------------------------------+// 4. Project auto-imports (utils/)+// ---------------------------------------------------------------------------+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+})++// ---------------------------------------------------------------------------+// 5. Common module mocks+// ---------------------------------------------------------------------------+vi.mock('vue-deepunref', () => ({ deepUnref: (v: any) => v }))++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],+ successEmo: [':)'],+ warningEmo: [':/'],+}))diff --git a/app/types/vue-deepunref.d.ts b/app/types/vue-deepunref.d.tsnew file mode 100644index 00000000..c18b4211--- /dev/null+++ b/app/types/vue-deepunref.d.ts@@ -0,0 +1,3 @@+declare module 'vue-deepunref' {+ export function deepUnref<T>(value: T): T+}diff --git a/app/utils/convexId.test.ts b/app/utils/convexId.test.tsnew file mode 100644index 00000000..565cfcf6--- /dev/null+++ b/app/utils/convexId.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'++import { cleanupFrontendIds, isLocalId } from '~/utils/convexId'++describe('cleanupFrontendIds', () => {+ it('removes stale local IDs not in pending queue', () => {+ const data = { local_abc: { n: 1 }, server123: { n: 2 } }+ const result = cleanupFrontendIds(data, {})++ expect(result).not.toHaveProperty('local_abc')+ expect(result).toHaveProperty('server123')+ })++ it('keeps local IDs that are still pending', () => {+ const data = { local_abc: { n: 1 }, local_def: { n: 2 } }+ const pending = { local_abc: { n: 1 } }+ const result = cleanupFrontendIds(data, pending)++ expect(result).toHaveProperty('local_abc')+ expect(result).not.toHaveProperty('local_def')+ })++ it('does not mutate original data', () => {+ const data = { local_abc: { n: 1 } }+ cleanupFrontendIds(data, {})++ expect(data).toHaveProperty('local_abc')+ })+})++describe('generateId + isLocalId contract', () => {+ it('generateId produces IDs recognized by isLocalId', async () => {+ const { generateId } = await import('~~/utils/generateId')++ expect(isLocalId(generateId())).toBe(true)+ })+})diff --git a/app/utils/redirect.test.ts b/app/utils/redirect.test.tsnew file mode 100644index 00000000..47ed500c--- /dev/null+++ b/app/utils/redirect.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'++import { getSafeRedirectPath } from '~/utils/redirect'++describe('getSafeRedirectPath', () => {+ it('allows relative paths', () => {+ expect(getSafeRedirectPath('/dashboard')).toBe('/dashboard')+ expect(getSafeRedirectPath('/settings/profile')).toBe('/settings/profile')+ })++ it('blocks protocol-relative URLs (open redirect vector)', () => {+ expect(getSafeRedirectPath('//evil.com')).toBe('/dashboard')+ expect(getSafeRedirectPath('//evil.com/phish')).toBe('/dashboard')+ })++ it('blocks absolute URLs', () => {+ expect(getSafeRedirectPath('https://evil.com')).toBe('/dashboard')+ expect(getSafeRedirectPath('http://evil.com')).toBe('/dashboard')+ })++ it('blocks non-string values', () => {+ expect(getSafeRedirectPath(null)).toBe('/dashboard')+ expect(getSafeRedirectPath(undefined)).toBe('/dashboard')+ expect(getSafeRedirectPath(123)).toBe('/dashboard')+ })++ it('blocks empty string', () => {+ expect(getSafeRedirectPath('')).toBe('/dashboard')+ })+})diff --git a/convex/auth.ts b/convex/auth.tsindex 135e285e..1eabbc03 100644--- a/convex/auth.ts+++ b/convex/auth.ts@@ -8,7 +8,6 @@ import { createAuthMiddleware } from 'better-auth/plugins'import type { DataModel } from './_generated/dataModel'import { components } from './_generated/api'-import { query } from './_generated/server'import authConfig from './auth.config'import { frontendOrigins } from './origins'@@ -60,10 +59,3 @@ function createAuth(ctx: GenericCtx<DataModel>) {}export { createAuth }--export const getCurrentUser = query({- args: {},- handler: async (ctx) => {- return await authComponent.safeGetAuthUser(ctx)- },-})diff --git a/convex/categories.ts b/convex/categories.tsindex 137890c6..ab95eaf7 100644--- a/convex/categories.ts+++ b/convex/categories.ts@@ -68,7 +68,6 @@ async function updateCategoryCore(ctx: MutationCtx,id: Id<'categories'>,args: {- childIds?: Id<'categories'>[]color?: stringicon?: stringname?: string@@ -114,7 +113,6 @@ export const list = query({export const create = mutation({args: {- childIds: v.optional(v.array(v.id('categories'))),color: v.string(),icon: v.string(),name: v.string(),@@ -157,7 +155,6 @@ export const create = mutation({export const update = mutation({args: {- childIds: v.optional(v.array(v.id('categories'))),color: v.optional(v.string()),icon: v.optional(v.string()),id: v.id('categories'),diff --git a/convex/migrate.ts b/convex/migrate.tsindex 4cb8fd40..73f70ddd 100644--- a/convex/migrate.ts+++ b/convex/migrate.ts@@ -2,6 +2,7 @@ import { v } from 'convex/values'import { components, internal } from './_generated/api'import { internalAction, internalMutation } from './_generated/server'+import { TrnType } from './shared'import { addTrnsToHash, fnv1aNum, getOrCreateSyncMeta } from './trnsHash'export const deleteTablePage = internalMutation({@@ -213,3 +214,54 @@ export const recalcHashForUser = internalAction({}},})++// --- Migrate old transfers to adjustment ---+// Old transfers have categoryId: 'transfer' with type: Expense(0) or Income(1).+// Modern transfers use type: Transfer(2). Old transfers are semantically adjustments.++export const migrateOldTransfersPage = internalMutation({+ args: {+ cursor: v.union(v.string(), v.null()),+ },+ handler: async (ctx, { cursor }) => {+ const page = await ctx.db+ .query('trns')+ .paginate({ cursor, numItems: 500 })++ let patched = 0+ for (const trn of page.page) {+ if (trn.categoryId === 'transfer' && (trn.type === TrnType.Expense || trn.type === TrnType.Income)) {+ await ctx.db.patch(trn._id, { categoryId: 'adjustment' })+ patched+++ }+ }++ return {+ continueCursor: page.continueCursor,+ hasMore: !page.isDone,+ patched,+ }+ },+})++export const migrateOldTransfers = internalAction({+ args: {},+ handler: async (ctx) => {+ let cursor: string | null = null+ let totalPatched = 0++ while (true) {+ const result: { continueCursor: string, hasMore: boolean, patched: number }+ = await ctx.runMutation(internal.migrate.migrateOldTransfersPage, { cursor })+ totalPatched += result.patched++ if (!result.hasMore)+ break++ cursor = result.continueCursor+ }++ console.log(`migrateOldTransfers: patched ${totalPatched} transactions`)+ return totalPatched+ },+})diff --git a/convex/rates.ts b/convex/rates.tsindex 7fe4dfcb..9b144cad 100644--- a/convex/rates.ts+++ b/convex/rates.ts@@ -16,16 +16,6 @@ export const getLatest = query({},})-export const getByDate = query({- args: { date: v.string() },- handler: async (ctx, { date }) => {- return await ctx.db- .query('rates')- .withIndex('by_date', q => q.eq('date', date))- .first()- },-})-export const saveRates = internalMutation({args: {date: v.string(),diff --git a/convex/shared.ts b/convex/shared.tsindex 3aa5f5e3..ce17484e 100644--- a/convex/shared.ts+++ b/convex/shared.ts@@ -3,8 +3,7 @@ import type { MutationCtx, QueryCtx } from './_generated/server'import { authComponent } from './auth'-export { TrnType, walletTypes, walletTypeValidator } from './validators'-export type { WalletType } from './validators'+export { TrnType, walletTypeValidator } from './validators'/*** Get authenticated user or return null (for queries).diff --git a/mocks/trns.ts b/mocks/trns.tsindex 605b315a..ff7b1115 100644--- a/mocks/trns.ts+++ b/mocks/trns.ts@@ -3,6 +3,42 @@ import type { TrnId, TrnItem } from '~/components/trns/types'import { TrnType } from '~/components/trns/types'export const trnsItems: Record<TrnId, TrnItem> = {+ adjustmentExpenseWalletCashUSD30: {+ amount: 30,+ categoryId: 'adjustment',+ date: 123456,+ type: TrnType.Expense,+ updatedAt: 12,+ walletId: 'walletCashUSD',+ },++ adjustmentExpenseWalletCashUSD50: {+ amount: 50,+ categoryId: 'adjustment',+ date: 123456,+ type: TrnType.Expense,+ updatedAt: 12,+ walletId: 'walletCashUSD',+ },++ adjustmentIncomeWalletCashUSD30: {+ amount: 30,+ categoryId: 'adjustment',+ date: 123456,+ type: TrnType.Income,+ updatedAt: 12,+ walletId: 'walletCashUSD',+ },++ adjustmentIncomeWalletCashUSD200: {+ amount: 200,+ categoryId: 'adjustment',+ date: 123456,+ type: TrnType.Income,+ updatedAt: 12,+ walletId: 'walletCashUSD',+ },+transactionExpenseWalletCashUSD400: {amount: 400,categoryId: 'expense',@@ -39,24 +75,6 @@ export const trnsItems: Record<TrnId, TrnItem> = {walletId: 'walletOneRUB',},- transferCategoryIdExpenseWalletCashUSD30: {- amount: 30,- categoryId: 'transfer',- date: 123456,- type: TrnType.Expense,- updatedAt: 12,- walletId: 'walletCashUSD',- },-- transferCategoryIncomeWalletCashUSD30: {- amount: 30,- categoryId: 'transfer',- date: 123456,- type: TrnType.Income,- updatedAt: 12,- walletId: 'walletCashUSD',- },-transferExpenseWalletCashUSD10IncomeWalletRUB700: {categoryId: 'transfer',date: 123456,diff --git a/package.json b/package.jsonindex 8bdb7d33..f13f3a59 100644--- a/package.json+++ b/package.json@@ -69,6 +69,7 @@"eslint-plugin-format": "^1.1.0","eslint-plugin-perfectionist": "^4.15.1","eslint-plugin-tailwindcss": "4.0.0-beta.0",+ "happy-dom": "^20.8.3","nuxt": "^4.2.1","prettier": "^3.7.4","prettier-plugin-tailwindcss": "^0.7.2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e9cdb70f..c8abe92e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -10,7 +10,7 @@ importers:dependencies:'@convex-dev/better-auth':specifier: ^0.10.10- version: 0.10.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@standard-schema/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])+ version: 0.10.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@standard-schema/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])'@formkit/drag-and-drop':specifier: ^0.5.3version: 0.5.3@@ -25,7 +25,7 @@ importers:version: 0.11.3([email protected])([email protected]([email protected])([email protected]([email protected])))better-auth:specifier: ^1.4.9- version: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))+ version: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))convex:specifier: ^1.22.0version: 1.31.7([email protected])@@ -65,7 +65,7 @@ importers:devDependencies:'@antfu/eslint-config':specifier: ^6.4.1- version: 6.4.1(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 6.4.1(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@iconify-json/lucide':specifier: ^1.2.78version: 1.2.78@@ -86,7 +86,7 @@ importers:version: 1.1.0([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])'@vitest/coverage-v8':specifier: ^4.0.15- version: 4.0.15([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.0.15([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vueuse/core':specifier: ^13.9.0version: 13.9.0([email protected]([email protected]))@@ -123,6 +123,9 @@ importers:eslint-plugin-tailwindcss:specifier: 4.0.0-beta.0version: 4.0.0-beta.0([email protected])+ happy-dom:+ specifier: ^20.8.3+ version: 20.8.3nuxt:specifier: ^4.2.1version: 4.2.1(@netlify/[email protected])(@parcel/[email protected])(@types/[email protected])(@vue/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -143,7 +146,7 @@ importers:version: 5.9.3vitest:specifier: ^4.0.15- version: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])workbox-core:specifier: ^7.4.0version: 7.4.0@@ -3119,6 +3122,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}+'@typescript-eslint/[email protected]':resolution: {integrity: sha512-X63hI1bxl5ohelzr0LY5coufyl0LJNthld+abwxpCoo6Gq+hSqhKwci7MUWkXo67mzgUK6YFByhmaHmUcuBJmA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -4522,6 +4531,10 @@ packages:resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}engines: {node: '>=0.12'}+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}@@ -5157,6 +5170,10 @@ packages:resolution: {integrity: sha512-YzJeWSkDZxAhvmp8dexjRK5hxziRO7I9m0N53WhvYL5NiWfkUkzssVzY9jvGu0HBoLFW6+duYmNSn6MaZBCCtg==}+ resolution: {integrity: sha512-lMHQRRwIPyJ70HV0kkFT7jH/gXzSI7yDkQFe07E2flwmNDFoWUTRMKpW2sglsnpeA7b6S2TJPp98EbQxai8eaQ==}+ engines: {node: '>=20.0.0'}+resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}engines: {node: '>= 0.4'}@@ -7892,6 +7909,10 @@ packages:resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}+ resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}@@ -8112,7 +8133,7 @@ snapshots:'@jridgewell/gen-mapping': 0.3.12'@jridgewell/trace-mapping': 0.3.29- '@antfu/[email protected](@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@antfu/[email protected](@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@antfu/install-pkg': 1.1.0'@clack/prompts': 0.11.0@@ -8121,7 +8142,7 @@ snapshots:'@stylistic/eslint-plugin': 5.6.1([email protected]([email protected]))'@typescript-eslint/eslint-plugin': 8.48.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@vitest/eslint-plugin': 1.5.1([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/eslint-plugin': 1.5.1([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))ansis: 4.2.0cac: 6.7.14eslint: 9.39.1([email protected])@@ -9020,14 +9041,14 @@ snapshots:nanostores: 1.1.0zod: 4.3.6- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])':dependencies:'@better-auth/core': 1.4.18(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.3.0'@better-fetch/fetch': 1.1.21'@simplewebauthn/browser': 13.2.2'@simplewebauthn/server': 13.2.2- better-auth: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))+ better-auth: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))better-call: 1.1.8([email protected])nanostores: 1.1.0zod: 4.3.6@@ -9061,11 +9082,11 @@ snapshots:dependencies:mime: 3.0.0- '@convex-dev/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@standard-schema/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])':+ '@convex-dev/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@standard-schema/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])':dependencies:- '@better-auth/passkey': 1.4.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])+ '@better-auth/passkey': 1.4.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])'@better-fetch/fetch': 1.1.21- better-auth: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))+ better-auth: 1.4.9([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))common-tags: 1.8.2convex: 1.31.7([email protected])convex-helpers: 0.1.111(@standard-schema/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])@@ -11267,6 +11288,12 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 25.2.3+'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@eslint-community/regexpp': 4.12.1@@ -11578,7 +11605,7 @@ snapshots:vite: 7.2.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])vue: 3.5.25([email protected])- '@vitest/[email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@bcoe/v8-coverage': 1.0.2'@vitest/utils': 4.0.15@@ -11591,18 +11618,18 @@ snapshots:obug: 2.1.1std-env: 3.10.0tinyrainbow: 3.0.3- vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color- '@vitest/[email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@typescript-eslint/scope-manager': 8.47.0eslint: 9.39.1([email protected])optionalDependencies:typescript: 5.9.3- vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -12116,7 +12143,7 @@ snapshots:- [email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])):+ [email protected]([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected])):dependencies:'@better-auth/core': 1.4.9(@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/telemetry': 1.4.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))@@ -12133,7 +12160,7 @@ snapshots:optionalDependencies:react: 19.2.4react-dom: 19.2.4([email protected])- vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest: 4.0.15(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vue: 3.5.25([email protected])@@ -12739,6 +12766,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -13662,6 +13691,18 @@ snapshots:ufo: 1.6.3uncrypto: 0.1.3+ dependencies:+ '@types/node': 25.2.3+ '@types/whatwg-mimetype': 3.0.2+ '@types/ws': 8.18.1+ entities: 7.0.1+ whatwg-mimetype: 3.0.0+ ws: 8.18.3+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate+@@ -16654,7 +16695,7 @@ snapshots:terser: 5.43.1yaml: 2.8.2- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 4.0.15'@vitest/mocker': 4.0.15([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -16679,6 +16720,7 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 25.2.3+ happy-dom: 20.8.3transitivePeerDependencies:- jiti- less@@ -16760,6 +16802,8 @@ snapshots:+ [email protected]: {}+dependencies:tr46: 0.0.3diff --git a/services/convex/api.test.ts b/services/convex/api.test.tsnew file mode 100644index 00000000..9f24dbfe--- /dev/null+++ b/services/convex/api.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'+import { convexWalletsToMap } from '~~/services/convex/api'++describe('convexWalletsToMap (arrayToMap)', () => {+ it('strips _id, _creationTime, userId and uses _id as key', () => {+ const docs = [+ { _creationTime: 123, _id: 'w1', color: '#0f0', currency: 'USD', name: 'Cash', userId: 'u1' },+ { _creationTime: 456, _id: 'w2', color: '#f00', currency: 'EUR', name: 'Card', userId: 'u1' },+ ]++ const result = convexWalletsToMap(docs as any)++ expect(result).toEqual({+ w1: { color: '#0f0', currency: 'USD', name: 'Cash' },+ w2: { color: '#f00', currency: 'EUR', name: 'Card' },+ })+ })++ it('returns empty object for empty array', () => {+ expect(convexWalletsToMap([])).toEqual({})+ })+})diff --git a/utils/fnv1a.test.ts b/utils/fnv1a.test.tsnew file mode 100644index 00000000..e39a923a--- /dev/null+++ b/utils/fnv1a.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'+import { fnv1aNum, xorIdsHash } from '~~/utils/fnv1a'++describe('fnv1aNum', () => {+ it('returns consistent hash for same input (regression snapshot)', () => {+ expect(fnv1aNum('trn1')).toBe(563873362)+ expect(fnv1aNum('wallet_abc')).toBe(1520395703)+ })++ it('returns different hashes for different inputs', () => {+ expect(fnv1aNum('a')).not.toBe(fnv1aNum('b'))+ })+})++describe('xorIdsHash', () => {+ it('returns consistent hash (regression snapshot)', () => {+ expect(xorIdsHash(['trn1'])).toBe(fnv1aNum('trn1').toString(36))+ })++ it('is order-independent (critical for sync β DB order not guaranteed)', () => {+ const hash1 = xorIdsHash(['a', 'b', 'c'])+ const hash2 = xorIdsHash(['c', 'a', 'b'])++ expect(hash1).toBe(hash2)+ })++ it('returns "0" for empty array', () => {+ expect(xorIdsHash([])).toBe('0')+ })+})diff --git a/utils/migrate/firebase.js b/utils/migrate/firebase.jsindex 695f0c2c..ab861a4f 100644--- a/utils/migrate/firebase.js+++ b/utils/migrate/firebase.js@@ -173,9 +173,9 @@ const allTrns = Object.entries(data.trns).map(([_oldId, t]) => {else if (t.walletId && t.type !== 2)trn.walletId = walletIdMap[t.walletId] || t.walletId- if (t.categoryId === 'transfer')+ if (t.categoryId === 'transfer' && t.type === 2)trn.categoryId = 'transfer'- else if (t.categoryId === 'adjustment')+ else if (t.categoryId === 'transfer' || t.categoryId === 'adjustment')trn.categoryId = 'adjustment'else if (t.categoryId)trn.categoryId = categoryIdMap[t.categoryId] || t.categoryIddiff --git a/vitest.config.ts b/vitest.config.tsnew file mode 100644index 00000000..ae275be3--- /dev/null+++ b/vitest.config.ts@@ -0,0 +1,35 @@+import { fileURLToPath } from 'node:url'+import { defineConfig } from 'vitest/config'++const appDir = fileURLToPath(new URL('./app', import.meta.url))+const rootDir = fileURLToPath(new URL('.', import.meta.url))++const alias = {+ '~': appDir,+ '~~': rootDir,+}++export default defineConfig({+ resolve: { alias },+ test: {+ projects: [+ {+ resolve: { alias },+ test: {+ exclude: ['app/**/*Store.test.ts', 'app/**/useStoreSync.test.ts'],+ include: ['app/**/*.test.ts', 'utils/**/*.test.ts', 'services/**/*.test.ts'],+ name: 'unit',+ },+ },+ {+ resolve: { alias },+ test: {+ environment: 'happy-dom',+ include: ['app/**/*Store.test.ts', 'app/**/useStoreSync.test.ts'],+ name: 'store',+ setupFiles: ['./app/test-utils/setup-store.ts'],+ },+ },+ ],+ },+})