Open source personal finance application
refactor: wallets — extract constants, add credit helpers, improve filtering and grouping
Ilya Komichev0e7ddfa5bbc7
diff --git a/app/components/wallets/ItemBody.vue b/app/components/wallets/ItemBody.vueindex e3817f0d..238a8286 100644--- a/app/components/wallets/ItemBody.vue+++ b/app/components/wallets/ItemBody.vue@@ -4,6 +4,8 @@ import { useStorage } from '@vueuse/core'import type { WalletId, WalletItemComputed } from '~/components/wallets/types'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'+import { WALLET_STORAGE_KEYS } from '~/components/wallets/constants'+import { getCreditAvailable } from '~/components/wallets/types'const props = defineProps<{activeItemId?: WalletId | null@@ -36,7 +38,7 @@ const classes = computed(() => ([]))const creditViews = ['debt', 'summary'] as const-const activeCreditView = useStorage<typeof creditViews[number]>(props.walletId, 'debt')+const activeCreditView = useStorage<typeof creditViews[number]>(`${WALLET_STORAGE_KEYS.creditViewPrefix}${props.walletId}`, 'debt')const walletCreditLimit = computed(() =>props.wallet.type === 'credit' ? props.wallet.creditLimit : 0,@@ -47,7 +49,7 @@ const creditAmount = computed(() => {case 'debt':return props.wallet?.amountcase 'summary':- return Math.abs(walletCreditLimit.value) - Math.abs(props.wallet.amount)+ return getCreditAvailable(walletCreditLimit.value, props.wallet.amount)default:return 0}@@ -110,7 +112,7 @@ if (!props.isSort) {class="flex items-center gap-0.5 opacity-70"><Amount- :amount="walletCreditLimit - Math.abs(wallet.amount)"+ :amount="getCreditAvailable(walletCreditLimit, wallet.amount)":currencyCode="wallet.currency":isShowBaseRate="false":isShowSymbol="false"diff --git a/app/components/wallets/Selector.vue b/app/components/wallets/Selector.vueindex ffd82a3d..d66f204a 100644--- a/app/components/wallets/Selector.vue+++ b/app/components/wallets/Selector.vue@@ -4,6 +4,7 @@ import { useStorage } from '@vueuse/core'import type { CurrencyCode } from '~/components/currencies/types'import type { WalletId } from '~/components/wallets/types'+import { WALLET_STORAGE_KEYS } from '~/components/wallets/constants'import { useWalletsStore } from '~/components/wallets/useWalletsStore'const props = defineProps<{@@ -18,7 +19,7 @@ const emit = defineEmits<{const walletsStore = useWalletsStore()-const currencyFiltered = useStorage<CurrencyCode>('finapp-wallets-selector-currency', 'all')+const currencyFiltered = useStorage<CurrencyCode>(WALLET_STORAGE_KEYS.selectorCurrency, 'all')const selectedWalletsIdsWithCurrency = computed<WalletId[]>(() => {return Object.keys(walletsStore.itemsComputed).filter((id) => {const wallet = walletsStore.itemsComputed[id]diff --git a/app/components/wallets/Statistics.vue b/app/components/wallets/Statistics.vueindex 67fcd46c..71cd7216 100644--- a/app/components/wallets/Statistics.vue+++ b/app/components/wallets/Statistics.vue@@ -1,6 +1,8 @@<script setup lang="ts">import type { CurrencyCode } from '~/components/currencies/types'+import { getCreditAvailable } from '~/components/wallets/types'+const props = defineProps<{activeType?: string | falsecounts: Record<string, {@@ -68,7 +70,7 @@ const itemsGrouped = computed(() => [class="flex items-center gap-1 pt-1 opacity-90"><Amount- :amount="item.secondValue - Math.abs(item.value)"+ :amount="getCreditAvailable(item.secondValue, item.value)":currencyCode="currencyCode"variant="2xs"/>diff --git a/app/components/wallets/constants.ts b/app/components/wallets/constants.tsnew file mode 100644index 00000000..b17f913e--- /dev/null+++ b/app/components/wallets/constants.ts@@ -0,0 +1,10 @@+export const WALLET_STORAGE_KEYS = {+ activeCurrency: 'finapp-wallets-active-currency',+ activeType: 'finapp-wallets-active-type',+ creditViewPrefix: 'finapp-wallets-credit-view-',+ groupedBy: 'finapp-wallets-groupedBy',+ groupedBySecondary: 'finapp-wallets-groupedBySecondary',+ selectorCurrency: 'finapp-wallets-selector-currency',+ toggleMap: 'finapp-wallets-toggle-map',+ totalPrefix: 'finapp-wallets-total-',+} as constdiff --git a/app/components/wallets/counts.ts b/app/components/wallets/counts.tsindex 223741d9..7fa45672 100644--- a/app/components/wallets/counts.ts+++ b/app/components/wallets/counts.ts@@ -46,6 +46,12 @@ export function computeWalletCounts(params: {const amount = convert(wallet.amount ?? 0, wallet.currency ?? 'USD')+ if (wallet.isArchived) {+ sum.archived += amount+ hasArchivedWallet = true+ continue+ }+if (wallet.isExcludeInTotal)sum.excludeInTotal += amountelse if (wallet.type !== 'credit')@@ -76,11 +82,6 @@ export function computeWalletCounts(params: {if (wallet.isWithdrawal)sum.withdrawal += amount-- if (wallet.isArchived) {- sum.archived += amount- hasArchivedWallet = true- }}return {@@ -91,7 +92,7 @@ export function computeWalletCounts(params: {},available: {id: 'isAvailable',- isShow: sum.withdrawal !== 0,+ isShow: sum.withdrawal !== 0 && sum.credit !== 0,value: sum.withdrawal - Math.abs(sum.credit),},cash: {diff --git a/app/components/wallets/filters.test.ts b/app/components/wallets/filters.test.tsindex 7dfe2609..9b667220 100644--- a/app/components/wallets/filters.test.ts+++ b/app/components/wallets/filters.test.ts@@ -114,9 +114,31 @@ describe('filterWalletsByViewType', () => {expect(result).not.toContain('archivedCredit')})- it('cash: returns only cash wallets', () => {+ it('cash: returns only non-archived cash wallets', () => {const result = filterWalletsByViewType(allIds, wallets, 'cash')- expect(result).toEqual(['archived'])+ expect(result).toEqual([])+ })++ it('type filter excludes archived wallets', () => {+ const walletsWithActiveCash = {+ ...wallets,+ activeCash: wallet({ amount: 100, currency: 'USD', type: 'cash' }),+ }+ const ids = Object.keys(walletsWithActiveCash)+ const result = filterWalletsByViewType(ids, walletsWithActiveCash, 'cash')+ expect(result).toContain('activeCash')+ expect(result).not.toContain('archived')+ })++ it('isExcludeInTotal: excludes archived wallets', () => {+ const walletsWithArchivedExcluded = {+ ...wallets,+ archivedExcluded: wallet({ amount: 200, currency: 'USD', isArchived: true, isExcludeInTotal: true, type: 'cashless' }),+ }+ const ids = Object.keys(walletsWithArchivedExcluded)+ const result = filterWalletsByViewType(ids, walletsWithArchivedExcluded, 'isExcludeInTotal')+ expect(result).toContain('excludeUSD')+ expect(result).not.toContain('archivedExcluded')})it('cashless: returns cashless wallets', () => {diff --git a/app/components/wallets/filters.ts b/app/components/wallets/filters.tsindex fb665785..d34df6b7 100644--- a/app/components/wallets/filters.ts+++ b/app/components/wallets/filters.ts@@ -23,11 +23,11 @@ export function filterWalletsByViewType(switch (viewType) {case 'isWithdrawal': return wallet.isWithdrawal && !wallet.isArchived- case 'isExcludeInTotal': return wallet.isExcludeInTotal+ case 'isExcludeInTotal': return wallet.isExcludeInTotal && !wallet.isArchivedcase 'isArchived': return wallet.isArchivedcase 'isAvailable': return (wallet.type === 'credit' || wallet.isWithdrawal) && !wallet.isArchivedcase 'total': return !wallet.isArchived- default: return wallet.type === viewType+ default: return wallet.type === viewType && !wallet.isArchived}})}diff --git a/app/components/wallets/page/GroupHeader.vue b/app/components/wallets/page/GroupHeader.vuenew file mode 100644index 00000000..bb7155b3--- /dev/null+++ b/app/components/wallets/page/GroupHeader.vue@@ -0,0 +1,37 @@+<script setup lang="ts">+import type { CurrencyCode } from '~/components/currencies/types'++import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'++const props = defineProps<{+ amount: number+ isPrimary?: boolean+ label: string+ secondaryAmount?: number+ secondaryCurrency?: CurrencyCode+}>()++const currenciesStore = useCurrenciesStore()+</script>++<template>+ <div class="font-tertiary text-base leading-none font-semibold" :class="[props.isPrimary && '!text-3']">+ {{ props.label }}+ </div>++ <div class="ml-auto" :class="[props.isPrimary && 'opacity-60']">+ <Amount+ :amount="props.amount"+ :currencyCode="currenciesStore.base"+ :isShowBaseRate="false"+ :variant="props.isPrimary ? 'sm' : undefined"+ />+ <Amount+ v-if="props.secondaryAmount != null"+ :amount="props.secondaryAmount"+ :currencyCode="props.secondaryCurrency!"+ :isShowBaseRate="false"+ variant="2xs"+ />+ </div>+</template>diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vueindex de6faf9a..7c187798 100644--- a/app/components/wallets/page/List.vue+++ b/app/components/wallets/page/List.vue@@ -4,6 +4,7 @@ import { useStorage } from '@vueuse/core'import type { WalletsGroupedBy, WalletType } from '~/components/wallets/types'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'+import { WALLET_STORAGE_KEYS } from '~/components/wallets/constants'import { useWalletDelete } from '~/components/wallets/useWalletDelete'import { useWalletsCounts } from '~/components/wallets/useWalletsCounts'import { useWalletsFilter } from '~/components/wallets/useWalletsFilter'@@ -31,7 +32,7 @@ const {requestDelete,} = useWalletDelete()-const groupedBy = useStorage<WalletsGroupedBy>('finapp-wallets-groupedBy', 'none')+const groupedBy = useStorage<WalletsGroupedBy>(WALLET_STORAGE_KEYS.groupedBy, 'none')const {currencyFiltered,@@ -148,7 +149,7 @@ function hasGroups(groups: Record<string, unknown> | undefined) {</div><WalletsStatistics- :storageKey="`finapp-wallets-total-${groupedBy}`"+ :storageKey="`${WALLET_STORAGE_KEYS.totalPrefix}${groupedBy}`":activeType="walletViewType":currencyCode="currenciesStore.base":counts="counts"diff --git a/app/components/wallets/page/id/Edit.vue b/app/components/wallets/page/id/Edit.vueindex cddec9f8..16df66ad 100644--- a/app/components/wallets/page/id/Edit.vue+++ b/app/components/wallets/page/id/Edit.vue@@ -11,10 +11,16 @@ const walletsStore = useWalletsStore()const walletId = computed(() => route.params.id) as Ref<WalletId>const wallet = computed(() => walletsStore.items?.[walletId.value])-const walletForm = ref(walletItemSchema.parse(wallet.value))++if (!wallet.value) {+ router.replace('/wallets')+}++const walletForm = ref(wallet.value ? walletItemSchema.parse(wallet.value) : undefined)function updateField(key: keyof WalletItem, value: WalletItem[keyof WalletItem]) {- (walletForm.value as Record<string, unknown>)[key] = value+ if (walletForm.value)+ (walletForm.value as Record<string, unknown>)[key] = value}useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form.name.label')}` })@@ -22,7 +28,7 @@ useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form<template><UiPage- v-if="wallet"+ v-if="wallet && walletForm"class="flex h-full flex-col"><UiHeader>diff --git a/app/components/wallets/types.ts b/app/components/wallets/types.tsindex 55de4053..4ed18cb1 100644--- a/app/components/wallets/types.ts+++ b/app/components/wallets/types.ts@@ -47,3 +47,10 @@ export type WalletsComputed = Record<WalletId, WalletItemComputed>export type WalletsGroupedBy = 'type' | 'currency' | 'none'export type WalletsCurrencyFiltered = 'all' | CurrencyCode++/**+ * Calculate credit available: credit limit minus absolute amount used.+ */+export function getCreditAvailable(creditLimit: number, amount: number): number {+ return creditLimit - Math.abs(amount)+}diff --git a/app/components/wallets/useWalletsCounts.test.ts b/app/components/wallets/useWalletsCounts.test.tsindex 58d86dab..653e3b46 100644--- a/app/components/wallets/useWalletsCounts.test.ts+++ b/app/components/wallets/useWalletsCounts.test.ts@@ -159,6 +159,22 @@ describe('computeWalletCounts', () => {expect(result.credit!.secondValue).toBe(8000)})+ it('available hidden when no credit wallets', () => {+ const wallets = {+ w1: wallet({ amount: 5000, currency: 'USD', isWithdrawal: true, type: 'cashless' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.available!.isShow).toBe(false)+ })+it('cash.isShow false when only 1 wallet exists', () => {const wallets = {w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),@@ -191,7 +207,7 @@ describe('computeWalletCounts', () => {expect(result.cash!.isShow).toBe(false)})- it('archived wallets tracked with isShow', () => {+ it('archived wallets excluded from total and type sums', () => {const wallets = {w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),w2: wallet({ amount: 500, currency: 'USD', isArchived: true, type: 'cashless' }),@@ -207,6 +223,27 @@ describe('computeWalletCounts', () => {expect(result.archived!.value).toBe(500)expect(result.archived!.isShow).toBe(true)+ expect(result.total!.value).toBe(1000)+ expect(result.cashless!.value).toBe(0)+ })++ it('archived wallets excluded from withdrawal and available', () => {+ const wallets = {+ w1: wallet({ amount: 3000, currency: 'USD', isWithdrawal: true, type: 'cashless' }),+ w2: wallet({ amount: 1000, currency: 'USD', isArchived: true, isWithdrawal: true, type: 'cashless' }),+ w3: wallet({ amount: -500, creditLimit: 5000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 3,+ walletIds: ['w1', 'w2', 'w3'],+ wallets,+ })++ expect(result.withdrawal!.value).toBe(3000)+ expect(result.available!.value).toBe(2500)})it('archived.isShow false when no archived wallets', () => {diff --git a/app/components/wallets/useWalletsCounts.ts b/app/components/wallets/useWalletsCounts.tsindex 9f194db0..7edb9d25 100644--- a/app/components/wallets/useWalletsCounts.ts+++ b/app/components/wallets/useWalletsCounts.ts@@ -15,7 +15,7 @@ export function useWalletsCounts(const counts = computed(() => computeWalletCounts({baseCurrency: currenciesStore.base,rates: currenciesStore.rates,- totalWalletsCount: Object.keys(walletsStore.itemsComputed).length,+ totalWalletsCount: Object.values(walletsStore.itemsComputed).filter(w => !w.isArchived).length,walletIds: selectedWalletsIdsWithCurrency.value,wallets: walletsStore.itemsComputed,}))diff --git a/app/components/wallets/useWalletsFilter.ts b/app/components/wallets/useWalletsFilter.tsindex adff6014..b91ada04 100644--- a/app/components/wallets/useWalletsFilter.ts+++ b/app/components/wallets/useWalletsFilter.ts@@ -2,18 +2,19 @@ import type { Ref } from 'vue'import { useStorage } from '@vueuse/core'-import type { WalletId, WalletsCurrencyFiltered, WalletsGroupedBy, WalletType, WalletViewTypes } from '~/components/wallets/types'+import type { WalletId, WalletsCurrencyFiltered, WalletsGroupedBy, WalletViewTypes } from '~/components/wallets/types'+import { WALLET_STORAGE_KEYS } from '~/components/wallets/constants'import { filterWalletsByCurrency, filterWalletsByViewType } from '~/components/wallets/filters'import { useWalletsStore } from '~/components/wallets/useWalletsStore'export function useWalletsFilter(groupedBy: Ref<WalletsGroupedBy>) {const walletsStore = useWalletsStore()- const currencyFiltered = useStorage<WalletsCurrencyFiltered>('finapp-wallets-active-currency', 'all')- const walletViewType = useStorage<WalletViewTypes | 'total'>('finapp-wallets-active-type', 'total')+ const currencyFiltered = useStorage<WalletsCurrencyFiltered>(WALLET_STORAGE_KEYS.activeCurrency, 'all')+ const walletViewType = useStorage<WalletViewTypes | 'total'>(WALLET_STORAGE_KEYS.activeType, 'total')- function setWalletViewType(v: WalletType | 'total') {+ function setWalletViewType(v: WalletViewTypes | 'total') {walletViewType.value = v}@@ -25,6 +26,14 @@ export function useWalletsFilter(groupedBy: Ref<WalletsGroupedBy>) {filterWalletsByViewType(selectedWalletsIdsWithCurrency.value, walletsStore.itemsComputed, walletViewType.value),)+ watch(selectedWalletsIds, (ids) => {+ if (ids.length === 0 && walletViewType.value !== 'total') {+ const totalIds = filterWalletsByViewType(selectedWalletsIdsWithCurrency.value, walletsStore.itemsComputed, 'total')+ if (totalIds.length > 0)+ walletViewType.value = 'total'+ }+ })+return {currencyFiltered,selectedWalletsIds,diff --git a/app/components/wallets/useWalletsGrouping.ts b/app/components/wallets/useWalletsGrouping.tsindex 44ba55c7..99834a9d 100644--- a/app/components/wallets/useWalletsGrouping.ts+++ b/app/components/wallets/useWalletsGrouping.ts@@ -5,6 +5,7 @@ import { useStorage } from '@vueuse/core'import type { GroupedWallets, WalletsToggleMap } from '~/components/wallets/grouping'import type { WalletId, WalletsGroupedBy } from '~/components/wallets/types'+import { WALLET_STORAGE_KEYS } from '~/components/wallets/constants'import { applyToggle, applyToggleAll, buildWalletGroups, computeToggleStatus } from '~/components/wallets/grouping'import { useWalletsStore } from '~/components/wallets/useWalletsStore'@@ -17,12 +18,12 @@ export function useWalletsGrouping(const { t } = useI18n()const walletsStore = useWalletsStore()- const groupedBySecondary = useStorage('finapp-wallets-groupedBySecondary', {+ const groupedBySecondary = useStorage(WALLET_STORAGE_KEYS.groupedBySecondary, {currency: false,type: false,})- const walletsToggledMap = useStorage<WalletsToggleMap>('finapp-wallets-toggle-map', {} as WalletsToggleMap, localStorage, {+ const walletsToggledMap = useStorage<WalletsToggleMap>(WALLET_STORAGE_KEYS.toggleMap, {} as WalletsToggleMap, localStorage, {mergeDefaults: true,})