Open source personal finance application
refactor(wallets): extract pure wallet counts logic and add tests
Ilya Komichevaf0387b8d09e
diff --git a/app/components/user/useUserStore.ts b/app/components/user/useUserStore.tsindex 1174942c..3bc6ac41 100644--- a/app/components/user/useUserStore.ts+++ b/app/components/user/useUserStore.ts@@ -1,4 +1,5 @@import localforage from 'localforage'+import type { CurrencyCode } from '~/components/currencies/types'import type { LocaleSlug } from '~/components/locale/types'diff --git a/app/components/wallets/counts.ts b/app/components/wallets/counts.tsnew file mode 100644index 00000000..223741d9--- /dev/null+++ b/app/components/wallets/counts.ts@@ -0,0 +1,176 @@+import type { CurrencyCode, Rates } from '~/components/currencies/types'+import type { WalletId, WalletItemComputed } from '~/components/wallets/types'++import { getAmountInRate } from '~/components/amount/getTotal'++type CountItem = {+ id: string+ isShow: boolean+ secondValue?: number+ value: number+}++export function computeWalletCounts(params: {+ baseCurrency?: CurrencyCode+ rates?: Rates+ totalWalletsCount: number+ walletIds: WalletId[]+ wallets: Record<WalletId, WalletItemComputed>+}): Record<string, CountItem> {+ const { baseCurrency, rates, totalWalletsCount, walletIds, wallets } = params++ function convert(amount: number, currencyCode: CurrencyCode): number {+ return getAmountInRate({ amount, baseCurrencyCode: baseCurrency, currencyCode, rates })+ }++ const sum = {+ archived: 0,+ cash: 0,+ cashless: 0,+ credit: 0,+ creditPossible: 0,+ crypto: 0,+ debt: 0,+ deposit: 0,+ excludeInTotal: 0,+ total: 0,+ withdrawal: 0,+ }++ let hasArchivedWallet = false++ for (const walletId of walletIds) {+ const wallet = wallets[walletId]+ if (!wallet)+ continue++ const amount = convert(wallet.amount ?? 0, wallet.currency ?? 'USD')++ if (wallet.isExcludeInTotal)+ sum.excludeInTotal += amount+ else if (wallet.type !== 'credit')+ sum.total += amount++ switch (wallet.type) {+ case 'cash':+ sum.cash += amount+ break+ case 'cashless':+ sum.cashless += amount+ break+ case 'credit':+ sum.credit += amount+ if (wallet.creditLimit)+ sum.creditPossible += convert(wallet.creditLimit, wallet.currency ?? 'USD')+ break+ case 'crypto':+ sum.crypto += amount+ break+ case 'debt':+ sum.debt += amount+ break+ case 'deposit':+ sum.deposit += amount+ break+ }++ if (wallet.isWithdrawal)+ sum.withdrawal += amount++ if (wallet.isArchived) {+ sum.archived += amount+ hasArchivedWallet = true+ }+ }++ return {+ archived: {+ id: 'isArchived',+ isShow: hasArchivedWallet,+ value: sum.archived,+ },+ available: {+ id: 'isAvailable',+ isShow: sum.withdrawal !== 0,+ value: sum.withdrawal - Math.abs(sum.credit),+ },+ cash: {+ id: 'cash',+ isShow: totalWalletsCount > 1 && sum.cash !== 0,+ value: sum.cash,+ },+ cashless: {+ id: 'cashless',+ isShow: sum.cashless !== 0,+ value: sum.cashless,+ },+ credit: {+ id: 'credit',+ isShow: sum.credit !== 0,+ secondValue: sum.creditPossible,+ value: sum.credit,+ },+ crypto: {+ id: 'crypto',+ isShow: sum.crypto !== 0,+ value: sum.crypto,+ },+ debt: {+ id: 'debt',+ isShow: sum.debt !== 0,+ value: sum.debt,+ },+ deposit: {+ id: 'deposit',+ isShow: sum.deposit !== 0,+ value: sum.deposit,+ },+ excludeInTotal: {+ id: 'isExcludeInTotal',+ isShow: sum.excludeInTotal !== 0,+ value: sum.excludeInTotal,+ },+ total: {+ id: 'total',+ isShow: true,+ value: sum.total,+ },+ withdrawal: {+ id: 'isWithdrawal',+ isShow: sum.withdrawal !== 0,+ value: sum.withdrawal,+ },+ }+}++export function sumWalletAmounts(params: {+ baseCurrency?: CurrencyCode+ convert?: boolean+ rates?: Rates+ walletIds: WalletId[]+ wallets: Record<WalletId, WalletItemComputed>+}): number {+ const { baseCurrency, convert = true, rates, walletIds, wallets } = params++ let total = 0+ for (const id of walletIds) {+ const wallet = wallets[id]+ if (!wallet)+ continue++ if (convert) {+ total += getAmountInRate({+ amount: wallet.amount,+ baseCurrencyCode: baseCurrency,+ currencyCode: wallet.currency,+ rates,+ })+ }+ else {+ if (!wallet.isExcludeInTotal)+ total += wallet.amount+ }+ }++ return total+}diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vueindex ad736b80..63caf872 100644--- a/app/components/wallets/page/List.vue+++ b/app/components/wallets/page/List.vue@@ -11,7 +11,7 @@ import { useWalletContextMenu } from '~/components/wallets/useWalletContextMenu'import { useWalletsStore } from '~/components/wallets/useWalletsStore'import { showSuccessToast } from '~/composables/useStoreSync'-import { useWalletsPageCounts } from './useWalletsPageCounts'+import { useWalletsCounts } from '~/components/wallets/useWalletsCounts'import { useWalletsPageFilter } from './useWalletsPageFilter'import { useWalletsPageGrouping } from './useWalletsPageGrouping'@@ -88,7 +88,7 @@ const {const {counts,countWalletsSum,-} = useWalletsPageCounts(selectedWalletsIdsWithCurrency)+} = useWalletsCounts(selectedWalletsIdsWithCurrency)const {groupedBySecondary,diff --git a/app/components/wallets/page/useWalletsPageCounts.ts b/app/components/wallets/page/useWalletsPageCounts.tsdeleted file mode 100644index f2633d8a..00000000--- a/app/components/wallets/page/useWalletsPageCounts.ts+++ /dev/null@@ -1,186 +0,0 @@-import type { ComputedRef } from 'vue'--import type { WalletId } from '~/components/wallets/types'--import { useAmount } from '~/components/amount/useAmount'-import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'-import { useWalletsStore } from '~/components/wallets/useWalletsStore'--export function useWalletsPageCounts(- selectedWalletsIdsWithCurrency: ComputedRef<WalletId[]>,-) {- const walletsStore = useWalletsStore()- const currenciesStore = useCurrenciesStore()- const { getAmountInBaseRate } = useAmount()-- const counts = computed(() => {- const sum = {- archived: 0,- available: 0,- cash: 0,- cashless: 0,- credit: 0,- creditPossible: 0,- crypto: 0,- debt: 0,- deposit: 0,- excludeInTotal: 0,- total: 0,- withdrawal: 0,- }-- for (const walletId of selectedWalletsIdsWithCurrency.value) {- const wallet = walletsStore.itemsComputed[walletId]- if (!wallet)- continue-- const itemValue- = wallet.currency === currenciesStore.base- ? (walletsStore.itemsComputed[walletId]?.amount ?? 0)- : +getAmountInBaseRate({- amount: walletsStore.itemsComputed[walletId]?.amount ?? 0,- currencyCode: wallet.currency ?? 'USD',- noFormat: true,- })-- if (wallet.isExcludeInTotal) {- sum.excludeInTotal += itemValue- }- else if (wallet.type !== 'credit') {- sum.total += itemValue- }-- if (wallet.type === 'cash')- sum.cash += itemValue-- if (wallet.type === 'cashless')- sum.cashless += itemValue- if (wallet.type === 'crypto')- sum.crypto += itemValue-- if (wallet.type === 'deposit')- sum.deposit += itemValue-- if (wallet.type === 'debt')- sum.debt += itemValue-- if (wallet.type === 'credit')- sum.credit += itemValue-- if (wallet.type === 'credit' && wallet.creditLimit) {- sum.creditPossible = sum.creditPossible + +getAmountInBaseRate({- amount: wallet.creditLimit ?? 0,- currencyCode: wallet.currency ?? 'USD',- noFormat: true,- })- }-- if (wallet.isWithdrawal)- sum.withdrawal += itemValue-- if (wallet.isArchived) {- sum.archived += itemValue- }- }-- return {- cash: {- id: 'cash',- isShow: Object.keys(walletsStore.itemsComputed).length > 1 && sum.cash !== 0,- value: sum.cash,- },- // eslint-disable-next-line perfectionist/sort-objects- available: {- id: 'isAvailable',- isShow: sum.withdrawal !== 0,- value: sum.withdrawal - Math.abs(sum.credit),- },-- cashless: {- id: 'cashless',- isShow: sum.cashless !== 0,- value: sum.cashless,- },-- credit: {- id: 'credit',- isShow: sum.credit !== 0,- secondValue: sum.creditPossible,- value: sum.credit,- },-- crypto: {- id: 'crypto',- isShow: sum.crypto !== 0,- value: sum.crypto,- },-- debt: {- id: 'debt',- isShow: sum.debt !== 0,- value: sum.debt,- },-- deposit: {- id: 'deposit',- isShow: sum.deposit !== 0,- value: sum.deposit,- },-- total: {- id: 'total',- isShow: true,- value: sum.total,- },-- withdrawal: {- id: 'isWithdrawal',- isShow: sum.withdrawal !== 0,- value: sum.withdrawal,- },- // eslint-disable-next-line perfectionist/sort-objects- excludeInTotal: {- id: 'isExcludeInTotal',- isShow: sum.excludeInTotal !== 0,- value: sum.excludeInTotal,- },- // eslint-disable-next-line perfectionist/sort-objects- archived: {- id: 'isArchived',- isShow: selectedWalletsIdsWithCurrency.value.some(wallet => walletsStore.itemsComputed[wallet]?.isArchived),- value: sum.archived,- },- }- })-- function countWalletsSum(- walletsIds: WalletId[],- isConvert = true,- ) {- return walletsIds.reduce((acc, id) => {- const wallet = walletsStore.itemsComputed[id]- if (!wallet)- return acc-- if (isConvert) {- return (- acc- + +getAmountInBaseRate({- amount: wallet.amount,- currencyCode: wallet.currency,- noFormat: true,- })- )- }-- if (wallet.isExcludeInTotal)- return acc- return acc + wallet.amount- }, 0)- }-- return {- counts,- countWalletsSum,- }-}diff --git a/app/components/wallets/useWalletsCounts.test.ts b/app/components/wallets/useWalletsCounts.test.tsnew file mode 100644index 00000000..23f4db9a--- /dev/null+++ b/app/components/wallets/useWalletsCounts.test.ts@@ -0,0 +1,383 @@+import { describe, expect, it } from 'vitest'++import type { WalletItemComputed } from '~/components/wallets/types'++import { computeWalletCounts, sumWalletAmounts } from '~/components/wallets/counts'++const rates = { EUR: 0.96, RUB: 64.75, USD: 1 }++function wallet(overrides: Partial<WalletItemComputed> & Pick<WalletItemComputed, 'amount' | 'currency' | 'type'>): WalletItemComputed {+ return {+ color: 'blue',+ desc: '',+ isArchived: false,+ isExcludeInTotal: false,+ isWithdrawal: false,+ name: 'Test',+ order: 0,+ updatedAt: 0,+ ...overrides,+ } as WalletItemComputed+}++describe('computeWalletCounts', () => {+ it('returns zeros for empty wallet list', () => {+ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 0,+ walletIds: [],+ wallets: {},+ })++ expect(result.total.value).toBe(0)+ expect(result.cash.value).toBe(0)+ expect(result.credit.value).toBe(0)+ expect(result.total.isShow).toBe(true)+ })++ it('accumulates cash wallet into total', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.total.value).toBe(1000)+ expect(result.cash.value).toBe(1000)+ })++ it('excludes credit wallets from total', () => {+ const wallets = {+ w1: wallet({ amount: 500, currency: 'USD', type: 'cashless' }),+ w2: wallet({ amount: -200, creditLimit: 5000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result.total.value).toBe(500)+ expect(result.credit.value).toBe(-200)+ })++ it('puts isExcludeInTotal wallets into excludeInTotal, not total', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 300, currency: 'USD', isExcludeInTotal: true, type: 'cashless' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result.total.value).toBe(1000)+ expect(result.excludeInTotal.value).toBe(300)+ expect(result.excludeInTotal.isShow).toBe(true)+ })++ it('computes available as withdrawal minus abs(credit)', () => {+ const wallets = {+ w1: wallet({ amount: 5000, currency: 'USD', isWithdrawal: true, type: 'cashless' }),+ w2: wallet({ amount: -1000, creditLimit: 5000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result.available.value).toBe(4000)+ expect(result.withdrawal.value).toBe(5000)+ expect(result.available.isShow).toBe(true)+ })++ it('converts currencies to base rate', () => {+ const wallets = {+ w1: wallet({ amount: 6475, currency: 'RUB', type: 'cash' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.total.value).toBe(100)+ expect(result.cash.value).toBe(100)+ })++ it('converts creditPossible to base currency', () => {+ const wallets = {+ w1: wallet({ amount: -100, creditLimit: 6475, currency: 'RUB', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.credit.secondValue).toBe(100)+ })++ it('accumulates creditPossible from multiple credit wallets', () => {+ const wallets = {+ w1: wallet({ amount: -100, creditLimit: 5000, currency: 'USD', type: 'credit' }),+ w2: wallet({ amount: -200, creditLimit: 3000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result.credit.secondValue).toBe(8000)+ })++ it('cash.isShow false when only 1 wallet exists', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.cash.isShow).toBe(false)+ })++ it('cash.isShow false when sum is zero', () => {+ const wallets = {+ w1: wallet({ amount: 0, currency: 'USD', type: 'cash' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 5,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.cash.isShow).toBe(false)+ })++ it('archived wallets tracked with isShow', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 500, currency: 'USD', isArchived: true, type: 'cashless' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result.archived.value).toBe(500)+ expect(result.archived.isShow).toBe(true)+ })++ it('archived.isShow false when no archived wallets', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.archived.isShow).toBe(false)+ })++ it('skips missing wallets', () => {+ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['nonexistent'],+ wallets: {},+ })++ expect(result.total.value).toBe(0)+ })++ it('all wallet types accumulated correctly', () => {+ const wallets = {+ w1: wallet({ amount: 100, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 200, currency: 'USD', type: 'cashless' }),+ w3: wallet({ amount: 300, currency: 'USD', type: 'crypto' }),+ w4: wallet({ amount: 400, currency: 'USD', type: 'deposit' }),+ w5: wallet({ amount: 500, currency: 'USD', type: 'debt' }),+ w6: wallet({ amount: -600, creditLimit: 10000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 6,+ walletIds: ['w1', 'w2', 'w3', 'w4', 'w5', 'w6'],+ wallets,+ })++ expect(result.cash.value).toBe(100)+ expect(result.cashless.value).toBe(200)+ expect(result.crypto.value).toBe(300)+ expect(result.deposit.value).toBe(400)+ expect(result.debt.value).toBe(500)+ expect(result.credit.value).toBe(-600)+ expect(result.credit.secondValue).toBe(10000)+ // total = 100+200+300+400+500 = 1500 (credit excluded)+ expect(result.total.value).toBe(1500)+ })++ it('isExcludeInTotal credit wallet goes to excludeInTotal, not credit or total', () => {+ const wallets = {+ w1: wallet({ amount: -300, creditLimit: 5000, currency: 'USD', isExcludeInTotal: true, type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 1,+ walletIds: ['w1'],+ wallets,+ })++ expect(result.excludeInTotal.value).toBe(-300)+ expect(result.total.value).toBe(0)+ expect(result.credit.value).toBe(-300)+ })++ it('withdrawal wallet with negative amount', () => {+ const wallets = {+ w1: wallet({ amount: -500, currency: 'USD', isWithdrawal: true, type: 'cashless' }),+ w2: wallet({ amount: -1000, creditLimit: 5000, currency: 'USD', type: 'credit' }),+ }++ const result = computeWalletCounts({+ baseCurrency: 'USD',+ rates,+ totalWalletsCount: 2,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ // available = withdrawal - |credit| = -500 - 1000 = -1500+ expect(result.available.value).toBe(-1500)+ })+})++describe('sumWalletAmounts', () => {+ it('sums with currency conversion', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 6475, currency: 'RUB', type: 'cashless' }),+ }++ const result = sumWalletAmounts({+ baseCurrency: 'USD',+ convert: true,+ rates,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ // 1000 + 6475/64.75 = 1100+ expect(result).toBe(1100)+ })++ it('sums without conversion, excludes isExcludeInTotal', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 500, currency: 'USD', isExcludeInTotal: true, type: 'cashless' }),+ }++ const result = sumWalletAmounts({+ convert: false,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result).toBe(1000)+ })++ it('includes isExcludeInTotal when converting', () => {+ const wallets = {+ w1: wallet({ amount: 1000, currency: 'USD', type: 'cash' }),+ w2: wallet({ amount: 500, currency: 'USD', isExcludeInTotal: true, type: 'cashless' }),+ }++ const result = sumWalletAmounts({+ baseCurrency: 'USD',+ convert: true,+ rates,+ walletIds: ['w1', 'w2'],+ wallets,+ })++ expect(result).toBe(1500)+ })++ it('skips missing wallets', () => {+ const result = sumWalletAmounts({+ baseCurrency: 'USD',+ convert: true,+ rates,+ walletIds: ['nonexistent'],+ wallets: {},+ })++ expect(result).toBe(0)+ })++ it('defaults to convert=true', () => {+ const wallets = {+ w1: wallet({ amount: 6475, currency: 'RUB', type: 'cash' }),+ }++ const result = sumWalletAmounts({+ baseCurrency: 'USD',+ rates,+ walletIds: ['w1'],+ wallets,+ })++ expect(result).toBe(100)+ })+})diff --git a/app/components/wallets/useWalletsCounts.ts b/app/components/wallets/useWalletsCounts.tsnew file mode 100644index 00000000..9f194db0--- /dev/null+++ b/app/components/wallets/useWalletsCounts.ts@@ -0,0 +1,37 @@+import type { ComputedRef } from 'vue'++import type { WalletId } from '~/components/wallets/types'++import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'+import { computeWalletCounts, sumWalletAmounts } from '~/components/wallets/counts'+import { useWalletsStore } from '~/components/wallets/useWalletsStore'++export function useWalletsCounts(+ selectedWalletsIdsWithCurrency: ComputedRef<WalletId[]>,+) {+ const walletsStore = useWalletsStore()+ const currenciesStore = useCurrenciesStore()++ const counts = computed(() => computeWalletCounts({+ baseCurrency: currenciesStore.base,+ rates: currenciesStore.rates,+ totalWalletsCount: Object.keys(walletsStore.itemsComputed).length,+ walletIds: selectedWalletsIdsWithCurrency.value,+ wallets: walletsStore.itemsComputed,+ }))++ function countWalletsSum(walletsIds: WalletId[], isConvert = true) {+ return sumWalletAmounts({+ baseCurrency: currenciesStore.base,+ convert: isConvert,+ rates: currenciesStore.rates,+ walletIds: walletsIds,+ wallets: walletsStore.itemsComputed,+ })+ }++ return {+ counts,+ countWalletsSum,+ }+}diff --git a/app/composables/useAuthCookie.test.ts b/app/composables/useAuthCookie.test.tsindex 24774244..f4346cb3 100644--- a/app/composables/useAuthCookie.test.ts+++ b/app/composables/useAuthCookie.test.ts@@ -52,7 +52,7 @@ describe('useAuthCookie', () => {})})- describe('Secure flag', () => {+ describe('secure flag', () => {it('included on https', async () => {vi.stubGlobal('location', { protocol: 'https:' })vi.resetModules()diff --git a/app/composables/useStoreSync.ts b/app/composables/useStoreSync.tsindex dd213747..b39a4aa8 100644--- a/app/composables/useStoreSync.ts+++ b/app/composables/useStoreSync.ts@@ -1,6 +1,7 @@import type { ShallowRef } from 'vue'import localforage from 'localforage'+import type { EntityType } from '~/components/offline/types'import { errorEmo, random, successEmo, warningEmo } from '~/assets/js/emo'diff --git a/utils/simple.test.ts b/utils/simple.test.tsindex 80542bb1..20a261d4 100644--- a/utils/simple.test.ts+++ b/utils/simple.test.ts@@ -1,5 +1,4 @@import { describe, expect, it } from 'vitest'-import { uniqueElementsBy } from '~~/utils/simple'describe('uniqueElementsBy', () => {