Skip to content

Open source personal finance application

refactor(stat): extract pure logic from useStatItem, reorganize stat utils

Ilya Komichev7123823cabcf
diff --git a/app/components/stat/categories/collectAndGroup.test.ts b/app/components/stat/categories/collectAndGroup.test.ts
index f072ab7e..7a2f6eaa 100644
--- a/app/components/stat/categories/collectAndGroup.test.ts
+++ b/app/components/stat/categories/collectAndGroup.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import type { Categories } from '~/components/categories/types'
import type { CategoriesWithData } from '~/components/stat/types'
-import { collectCategoriesByTrns, flattenCategoriesWithValues, groupCategoriesWithValues } from '~/components/stat/categories/collectAndGroup'
+import { collectCategoriesByTrns, flattenCategoriesWithValues, groupCategoriesWithValues, sortCategoriesByAmount } from '~/components/stat/categories/collectAndGroup'
const categories: Categories = {
food: { color: 'red', name: 'Food', order: 0, parentId: 0 },
@@ -242,3 +242,18 @@ describe('groupCategoriesWithValues', () => {
expect(result).toEqual([])
})
})
+
+describe('sortCategoriesByAmount', () => {
+ it('sorts: positive descending, then negative by absolute descending', () => {
+ const categories: CategoriesWithData[string][] = [
+ { id: 'a', name: 'A', trnsIds: [], value: 100 },
+ { id: 'b', name: 'B', trnsIds: [], value: 300 },
+ { id: 'c', name: 'C', trnsIds: [], value: 200 },
+ { id: 'd', name: 'D', trnsIds: [], value: -200 },
+ { id: 'e', name: 'E', trnsIds: [], value: -400 },
+ ]
+
+ expect(categories.sort(sortCategoriesByAmount).map(c => c.value))
+ .toEqual([300, 200, 100, -400, -200])
+ })
+})
diff --git a/app/components/stat/categories/collectAndGroup.ts b/app/components/stat/categories/collectAndGroup.ts
index ad702fad..6975b27c 100644
--- a/app/components/stat/categories/collectAndGroup.ts
+++ b/app/components/stat/categories/collectAndGroup.ts
@@ -3,7 +3,25 @@ import type { CategoriesWithData, CategoryWithData } from '~/components/stat/typ
import type { TrnId } from '~/components/trns/types'
import { getParentCategoryIdOrUndefined } from '~/components/categories/utils'
-import { sortCategoriesByAmount } from '~/components/stat/utils'
+
+export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData) {
+ if (!a || !b)
+ return 0
+
+ if (a.value === 0)
+ return 1
+ if (b.value === 0)
+ return -1
+
+ const isP = a.value > 0 && b.value > 0
+ const isN = a.value < 0 && b.value < 0
+
+ if (isP)
+ return b.value - a.value
+ if (isN)
+ return a.value - b.value
+ return a.value > 0 ? -1 : 1
+}
export function collectCategoriesByTrns(params: {
categoriesItems: Categories
diff --git a/app/components/stat/intervals.test.ts b/app/components/stat/intervals.test.ts
new file mode 100644
index 00000000..7b1fac95
--- /dev/null
+++ b/app/components/stat/intervals.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, it } from 'vitest'
+
+import type { TotalReturns } from '~/components/amount/getTotal'
+import type { Range } from '~/components/date/types'
+import type { TrnItem } from '~/components/trns/types'
+
+import { TrnType } from '~/components/trns/types'
+
+import { bucketTrnsByIntervals, computeAverageTotal, isPeriodOneDay } from './intervals'
+
+const zeroTotal: TotalReturns = {
+ adjustment: 0,
+ expense: 0,
+ expenseTransfers: 0,
+ income: 0,
+ incomeTransfers: 0,
+ sum: 0,
+ sumTransfers: 0,
+}
+
+function makeTotal(income: number, expense: number): TotalReturns {
+ return { ...zeroTotal, expense, income, sum: income - expense }
+}
+
+function makeTrn(date: number, type: TrnType = TrnType.Expense): TrnItem {
+ return {
+ amount: 100,
+ categoryId: 'food',
+ date,
+ type,
+ updatedAt: date,
+ walletId: 'w1',
+ } as TrnItem
+}
+
+// --- bucketTrnsByIntervals ---
+
+describe('bucketTrnsByIntervals', () => {
+ const day1Start = new Date('2024-01-01').getTime()
+ const day1End = new Date('2024-01-01T23:59:59.999').getTime()
+ const day2Start = new Date('2024-01-02').getTime()
+ const day2End = new Date('2024-01-02T23:59:59.999').getTime()
+ const day3Start = new Date('2024-01-03').getTime()
+ const day3End = new Date('2024-01-03T23:59:59.999').getTime()
+
+ const intervals: Range[] = [
+ { end: day1End, start: day1Start },
+ { end: day2End, start: day2Start },
+ { end: day3End, start: day3Start },
+ ]
+
+ it('buckets transactions into correct intervals', () => {
+ const trnsItems: Record<string, TrnItem> = {
+ t1: makeTrn(day1Start + 1000),
+ t2: makeTrn(day2Start + 5000),
+ t3: makeTrn(day1Start + 2000),
+ }
+
+ const result = bucketTrnsByIntervals(
+ trnsItems,
+ ['t1', 't2', 't3'],
+ intervals,
+ ids => makeTotal(0, ids.length * 100),
+ )
+
+ expect(result).toHaveLength(3)
+ expect(result[0].trnsIds).toEqual(['t1', 't3'])
+ expect(result[1].trnsIds).toEqual(['t2'])
+ expect(result[2].trnsIds).toEqual([])
+ })
+
+ it('computes totals via callback', () => {
+ const trnsItems: Record<string, TrnItem> = {
+ t1: makeTrn(day1Start),
+ t2: makeTrn(day1Start + 1000),
+ }
+
+ const result = bucketTrnsByIntervals(
+ trnsItems,
+ ['t1', 't2'],
+ intervals,
+ ids => makeTotal(ids.length * 500, 0),
+ )
+
+ expect(result[0].total.income).toBe(1000)
+ expect(result[0].total.sum).toBe(1000)
+ expect(result[1].total.income).toBe(0)
+ })
+
+ it('returns empty array for empty intervals', () => {
+ const result = bucketTrnsByIntervals({}, ['t1'], [], () => zeroTotal)
+ expect(result).toEqual([])
+ })
+
+ it('skips transactions without date', () => {
+ const trnsItems: Record<string, TrnItem> = {
+ t1: { amount: 100, categoryId: 'food', type: TrnType.Expense, updatedAt: 0, walletId: 'w1' } as TrnItem,
+ }
+
+ const result = bucketTrnsByIntervals(trnsItems, ['t1'], intervals, () => zeroTotal)
+ expect(result[0].trnsIds).toEqual([])
+ })
+
+ it('skips transactions outside any interval', () => {
+ const beforeRange = day1Start - 100000
+ const afterRange = day3End + 100000
+ const trnsItems: Record<string, TrnItem> = {
+ t1: makeTrn(beforeRange),
+ t2: makeTrn(afterRange),
+ t3: makeTrn(day2Start),
+ }
+
+ const result = bucketTrnsByIntervals(trnsItems, ['t1', 't2', 't3'], intervals, ids => makeTotal(0, ids.length))
+ expect(result[0].trnsIds).toEqual([])
+ expect(result[1].trnsIds).toEqual(['t3'])
+ expect(result[2].trnsIds).toEqual([])
+ })
+
+ it('skips missing transaction IDs', () => {
+ const result = bucketTrnsByIntervals({}, ['missing'], intervals, () => zeroTotal)
+ expect(result[0].trnsIds).toEqual([])
+ })
+
+ it('preserves range references in output', () => {
+ const result = bucketTrnsByIntervals({}, [], intervals, () => zeroTotal)
+ expect(result[0].range).toBe(intervals[0])
+ expect(result[2].range).toBe(intervals[2])
+ })
+})
+
+// --- computeAverageTotal ---
+
+describe('computeAverageTotal', () => {
+ it('returns undefined for single-day range', () => {
+ const range: Range = {
+ end: new Date('2024-01-01T23:59:59').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ expect(computeAverageTotal(1000, range)).toBeUndefined()
+ })
+
+ it('computes daily average for multi-day range', () => {
+ const range: Range = {
+ end: new Date('2024-01-10').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ const result = computeAverageTotal(1000, range)
+ expect(result).toBeDefined()
+ expect(result!.day).toBeCloseTo(1000 / 10) // 9 days diff + 1
+ })
+
+ it('computes weekly average for multi-week range', () => {
+ const range: Range = {
+ end: new Date('2024-01-22').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ const result = computeAverageTotal(2100, range)
+ expect(result!.week).toBeDefined()
+ expect(result!.week).toBeCloseTo(2100 / 4) // 3 weeks diff + 1
+ })
+
+ it('computes monthly average for multi-month range', () => {
+ const range: Range = {
+ end: new Date('2024-04-01').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ const result = computeAverageTotal(3000, range)
+ expect(result!.month).toBeCloseTo(3000 / 4) // 3 months diff + 1
+ })
+
+ it('omits zero averages', () => {
+ const range: Range = {
+ end: new Date('2024-01-03').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ const result = computeAverageTotal(0, range)
+ expect(result).toBeUndefined()
+ })
+
+ it('handles negative sums', () => {
+ const range: Range = {
+ end: new Date('2024-01-10').getTime(),
+ start: new Date('2024-01-01').getTime(),
+ }
+ const result = computeAverageTotal(-500, range)
+ expect(result!.day).toBeCloseTo(-50)
+ })
+})
+
+// --- isPeriodOneDay ---
+
+describe('isPeriodOneDay', () => {
+ it('returns true for rangeBy=day with duration=1', () => {
+ expect(isPeriodOneDay({ intervalsBy: 'month', intervalSelected: -1, rangeBy: 'day', rangeDuration: 1 })).toBe(true)
+ })
+
+ it('returns true for intervalsBy=day with selected interval', () => {
+ expect(isPeriodOneDay({ intervalsBy: 'day', intervalSelected: 3, rangeBy: 'month', rangeDuration: 1 })).toBe(true)
+ })
+
+ it('returns false for multi-day range without day interval selected', () => {
+ expect(isPeriodOneDay({ intervalsBy: 'month', intervalSelected: -1, rangeBy: 'day', rangeDuration: 7 })).toBe(false)
+ })
+
+ it('returns false for week range', () => {
+ expect(isPeriodOneDay({ intervalsBy: 'week', intervalSelected: -1, rangeBy: 'week', rangeDuration: 1 })).toBe(false)
+ })
+})
diff --git a/app/components/stat/intervals.ts b/app/components/stat/intervals.ts
new file mode 100644
index 00000000..26017458
--- /dev/null
+++ b/app/components/stat/intervals.ts
@@ -0,0 +1,87 @@
+import { differenceInDays, differenceInMonths, differenceInWeeks } from 'date-fns'
+
+import type { TotalReturns } from '~/components/amount/getTotal'
+import type { Range, StatDateParams } from '~/components/date/types'
+import type { IntervalData } from '~/components/stat/types'
+import type { TrnId, TrnItem } from '~/components/trns/types'
+
+/**
+ * Bucket transaction IDs into date intervals using binary search.
+ * Single pass over trns — O(N log M) where M = number of intervals.
+ */
+export function bucketTrnsByIntervals(
+ trnsItems: Record<TrnId, TrnItem>,
+ trnsIds: TrnId[],
+ intervalsInRange: Range[],
+ computeTotal: (ids: TrnId[]) => TotalReturns,
+): IntervalData[] {
+ if (!intervalsInRange.length)
+ return []
+
+ const buckets: TrnId[][] = intervalsInRange.map(() => [])
+
+ for (const id of trnsIds) {
+ const trnDate = trnsItems[id]?.date
+ if (trnDate == null)
+ continue
+
+ let lo = 0
+ let hi = intervalsInRange.length - 1
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1
+ if (trnDate < intervalsInRange[mid].start) {
+ hi = mid - 1
+ }
+ else if (trnDate > intervalsInRange[mid].end) {
+ lo = mid + 1
+ }
+ else {
+ buckets[mid].push(id)
+ break
+ }
+ }
+ }
+
+ return intervalsInRange.map((range, i) => ({
+ range,
+ total: computeTotal(buckets[i]),
+ trnsIds: buckets[i],
+ }))
+}
+
+/**
+ * Compute averages (per day/week/month) for a date range.
+ * Returns only non-zero entries.
+ */
+export function computeAverageTotal(
+ sum: number,
+ dateRange: Range,
+): Record<string, number> | undefined {
+ if (differenceInDays(dateRange.end, dateRange.start) < 2)
+ return undefined
+
+ const dif = {
+ day: differenceInDays(dateRange.end, dateRange.start) + 1,
+ month: differenceInMonths(dateRange.end, dateRange.start) + 1,
+ week: differenceInWeeks(dateRange.end, dateRange.start) + 1,
+ }
+
+ const items: Record<string, number> = {}
+
+ if (dif.month > 1 && sum !== 0)
+ items.month = sum / dif.month
+ if (dif.week > 1 && sum !== 0)
+ items.week = sum / dif.week
+ if (dif.day > 1 && sum !== 0)
+ items.day = sum / dif.day
+
+ return Object.keys(items).length > 0 ? items : undefined
+}
+
+/**
+ * Check if the current period represents a single day.
+ */
+export function isPeriodOneDay(params: Pick<StatDateParams, 'intervalsBy' | 'intervalSelected' | 'rangeBy' | 'rangeDuration'>): boolean {
+ return (params.rangeBy === 'day' && params.rangeDuration === 1)
+ || (params.intervalsBy === 'day' && params.intervalSelected !== -1)
+}
diff --git a/app/components/stat/useStatItem.ts b/app/components/stat/useStatItem.ts
index 1c2481cc..d8d3b11f 100644
--- a/app/components/stat/useStatItem.ts
+++ b/app/components/stat/useStatItem.ts
@@ -1,10 +1,10 @@
import type { ComputedRef } from 'vue'
import { useStorage } from '@vueuse/core'
-import { differenceInDays, differenceInMonths, differenceInWeeks } from 'date-fns'
+import { differenceInDays } from 'date-fns'
import type { CategoryId } from '~/components/categories/types'
-import type { Range, StatDateProvider } from '~/components/date/types'
+import type { StatDateProvider } from '~/components/date/types'
import type { FilterProvider } from '~/components/stat/filter/types'
import type { ChartSeries, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import type { StatConfigProvider } from '~/components/stat/useStatConfig'
@@ -12,7 +12,8 @@ import type { TrnId } from '~/components/trns/types'
import { useAmount } from '~/components/amount/useAmount'
import { useStatChart } from '~/components/stat/chart/useStatChart'
-import { getTypesMapping } from '~/components/stat/utils'
+import { bucketTrnsByIntervals, computeAverageTotal, isPeriodOneDay as isPeriodOneDayFn } from '~/components/stat/intervals'
+import { getSelectedType, getSelectedTypeForSum, getTypesMapping, getTypesToShow } from '~/components/stat/utils'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
type UseStatItemParams = {
@@ -49,28 +50,11 @@ export function useStatItem({
const filteredCategoriesIds = ref<CategoryId[]>([])
- const selectedType = computed(() => {
- if (statTab.value === 'summary')
- return filteredType.value
- if (statTab.value === 'split')
- return type.value
- return statTab.value
- })
-
- const selectedTypeForSum = computed(() => {
- if (statTab.value === 'summary')
- return 'summary'
- if (statTab.value === 'split')
- return type.value
- return statTab.value
- })
-
+ const selectedType = computed(() => getSelectedType(statTab.value, filteredType.value, type.value))
+ const selectedTypeForSum = computed(() => getSelectedTypeForSum(statTab.value, type.value))
const selectedTypesMapping = computed(() => getTypesMapping(selectedType.value))
- const isPeriodOneDay = computed(() =>
- (statDate.params.value.rangeBy === 'day' && statDate.params.value.rangeDuration === 1)
- || (statDate.params.value.intervalsBy === 'day' && statDate.params.value.intervalSelected !== -1),
- )
+ const isPeriodOneDay = computed(() => isPeriodOneDayFn(statDate.params.value))
const rangeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
trnsIds: trnsIds.value,
@@ -81,45 +65,13 @@ export function useStatItem({
trnsIds: trnsIds.value,
}))
- function getIntervalsData(ids: TrnId[], intervalsInRange: Range[]) {
- if (!intervalsInRange.length)
- return []
-
- // Pre-allocate one bucket per interval
- const buckets: TrnId[][] = intervalsInRange.map(() => [])
-
- // Single pass over trns — binary search for the matching interval
- for (const id of ids) {
- const trnDate = trnsStore.items?.[id]?.date
- if (trnDate == null)
- continue
-
- let lo = 0
- let hi = intervalsInRange.length - 1
- while (lo <= hi) {
- const mid = (lo + hi) >> 1
- if (trnDate < intervalsInRange[mid].start) {
- hi = mid - 1
- }
- else if (trnDate > intervalsInRange[mid].end) {
- lo = mid + 1
- }
- else {
- buckets[mid].push(id)
- break
- }
- }
- }
-
- return intervalsInRange.map((range, i) => ({
- range,
- total: getTotalOfTrnsIds(buckets[i]),
- trnsIds: buckets[i],
- }))
- }
+ const intervalsData = computed(() =>
+ bucketTrnsByIntervals(trnsStore.items ?? {}, rangeTrnsIds.value, statDate.intervalsInRange.value, getTotalOfTrnsIds),
+ )
- const intervalsData = computed(() => getIntervalsData(rangeTrnsIds.value, statDate.intervalsInRange.value))
- const intervalsDataWithFilteredCategories = computed(() => getIntervalsData(rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value))
+ const intervalsDataWithFilteredCategories = computed(() =>
+ bucketTrnsByIntervals(trnsStore.items ?? {}, rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value, getTotalOfTrnsIds),
+ )
const selectedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
sort: true,
@@ -149,50 +101,16 @@ export function useStatItem({
if (differenceInDays(statDate.range.value.end, statDate.range.value.start) < 2)
return
- const sum = filteredType.value === 'netIncome' ? rangeTotal.value.sum : rangeTotal.value[type.value]
+ const sum = filteredType.value === 'netIncome' ? rangeTotal.value.sum : rangeTotal.value[type.value!]
- const date = statDate.params.value.intervalSelected !== -1
+ const dateRange = statDate.params.value.intervalSelected !== -1
? statDate.selectedInterval.value
: statDate.range.value
- const dif = {
- day: differenceInDays(date?.end, date?.start) + 1,
- month: differenceInMonths(date?.end, date?.start) + 1,
- week: differenceInWeeks(date?.end, date?.start) + 1,
- }
-
- const items = {
- month: 0,
- week: 0,
- // eslint-disable-next-line perfectionist/sort-objects
- day: 0,
- }
-
- if (dif.month > 1)
- items.month = sum / dif.month
- if (dif.day > 1)
- items.day = sum / dif.day
- if (dif.week > 1)
- items.week = sum / dif.week
-
- return Object.fromEntries(Object.entries(items).filter(([_, value]) => value !== 0))
+ return computeAverageTotal(sum, dateRange!)
})
- const typesToShow = computed(() => {
- if (statTab.value === 'summary') {
- if (filteredType.value === 'netIncome')
- return ['income', 'expense']
- if (filteredType.value === 'income')
- return ['income']
- if (filteredType.value === 'expense')
- return ['expense']
- }
-
- if (statTab.value === 'expense' || statTab.value === 'income')
- return [statTab.value]
-
- return [type.value]
- })
+ const typesToShow = computed(() => getTypesToShow(statTab.value, filteredType.value, type.value))
const chartSeries = computed<ChartSeries[]>(() => {
const intervalTotals = intervalsDataWithFilteredCategories.value.map(g => g.total)
diff --git a/app/components/stat/utils.test.ts b/app/components/stat/utils.test.ts
index e174cd85..e2af4db5 100644
--- a/app/components/stat/utils.test.ts
+++ b/app/components/stat/utils.test.ts
@@ -1,25 +1,68 @@
import { describe, expect, it } from 'vitest'
-import type { CategoryWithData } from '~/components/stat/types'
-
-import { sortCategoriesByAmount } from '~/components/stat/utils'
-
-describe('sortCategoriesByAmount', () => {
- it('sort multiple values in correct order', () => {
- const categories: CategoryWithData[] = [
- { id: 'a', trnsIds: [], value: 100 },
- { id: 'b', trnsIds: [], value: 300 },
- { id: 'c', trnsIds: [], value: 200 },
- { id: 'd', trnsIds: [], value: -200 },
- { id: 'e', trnsIds: [], value: -400 },
- ]
-
- expect(categories.sort(sortCategoriesByAmount)).toEqual([
- { id: 'b', trnsIds: [], value: 300 },
- { id: 'c', trnsIds: [], value: 200 },
- { id: 'a', trnsIds: [], value: 100 },
- { id: 'e', trnsIds: [], value: -400 },
- { id: 'd', trnsIds: [], value: -200 },
- ])
+import { getSelectedType, getSelectedTypeForSum, getTypesToShow } from '~/components/stat/utils'
+
+describe('getSelectedType', () => {
+ it('returns filteredType for summary tab', () => {
+ expect(getSelectedType('summary', 'expense', 'income')).toBe('expense')
+ expect(getSelectedType('summary', 'netIncome', undefined)).toBe('netIncome')
+ })
+
+ it('returns type for split tab', () => {
+ expect(getSelectedType('split', 'netIncome', 'expense')).toBe('expense')
+ })
+
+ it('falls back to filteredType for split when type is undefined', () => {
+ expect(getSelectedType('split', 'income', undefined)).toBe('income')
+ })
+
+ it('returns statTab for expense/income tabs', () => {
+ expect(getSelectedType('expense', 'netIncome', 'income')).toBe('expense')
+ expect(getSelectedType('income', 'expense', undefined)).toBe('income')
+ })
+})
+
+describe('getSelectedTypeForSum', () => {
+ it('returns summary for summary tab', () => {
+ expect(getSelectedTypeForSum('summary', 'expense')).toBe('summary')
+ })
+
+ it('returns type for split tab', () => {
+ expect(getSelectedTypeForSum('split', 'income')).toBe('income')
+ })
+
+ it('returns statTab for expense/income tabs', () => {
+ expect(getSelectedTypeForSum('expense', 'income')).toBe('expense')
+ expect(getSelectedTypeForSum('income', undefined)).toBe('income')
+ })
+})
+
+describe('getTypesToShow', () => {
+ it('returns both types for summary+netIncome', () => {
+ expect(getTypesToShow('summary', 'netIncome', undefined)).toEqual(['income', 'expense'])
+ })
+
+ it('returns single type for summary+income', () => {
+ expect(getTypesToShow('summary', 'income', undefined)).toEqual(['income'])
+ })
+
+ it('returns single type for summary+expense', () => {
+ expect(getTypesToShow('summary', 'expense', undefined)).toEqual(['expense'])
+ })
+
+ it('returns statTab for expense tab', () => {
+ expect(getTypesToShow('expense', 'netIncome', 'income')).toEqual(['expense'])
+ })
+
+ it('returns statTab for income tab', () => {
+ expect(getTypesToShow('income', 'netIncome', undefined)).toEqual(['income'])
+ })
+
+ it('returns type for split tab', () => {
+ expect(getTypesToShow('split', 'netIncome', 'expense')).toEqual(['expense'])
+ })
+
+ it('falls back to both types for split without type', () => {
+ expect(getTypesToShow('split', 'netIncome', undefined)).toEqual(['income', 'expense'])
})
})
diff --git a/app/components/stat/utils.ts b/app/components/stat/utils.ts
index 8a987c29..7ed3806d 100644
--- a/app/components/stat/utils.ts
+++ b/app/components/stat/utils.ts
@@ -1,26 +1,7 @@
-import type { CategoryWithData, StatTabSlug } from '~/components/stat/types'
+import type { SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import { TrnType } from '~/components/trns/types'
-export function sortCategoriesByAmount(a: CategoryWithData, b: CategoryWithData) {
- if (!a || !b)
- return 0
-
- if (a.value === 0)
- return 1
- if (b.value === 0)
- return -1
-
- const isP = a.value > 0 && b.value > 0
- const isN = a.value < 0 && b.value < 0
-
- if (isP)
- return b.value - a.value
- if (isN)
- return a.value - b.value
- return a.value > 0 ? -1 : 1
-}
-
export function getTypesMapping(slug: StatTabSlug): TrnType[] | undefined {
const typeMapping: Record<StatTabSlug, TrnType[]> = {
expense: [TrnType.Expense, TrnType.Transfer],
@@ -31,3 +12,55 @@ export function getTypesMapping(slug: StatTabSlug): TrnType[] | undefined {
return typeMapping[slug] ?? [TrnType.Expense, TrnType.Income, TrnType.Transfer]
}
+
+/**
+ * Resolve the selected stat type from tab and user filter.
+ */
+export function getSelectedType(
+ statTab: StatTabSlug,
+ filteredType: SeriesSlugSelected,
+ type: SeriesSlugSelected | undefined,
+): SeriesSlugSelected | StatTabSlug {
+ if (statTab === 'summary')
+ return filteredType
+ if (statTab === 'split')
+ return type ?? filteredType
+ return statTab
+}
+
+/**
+ * Resolve the type used for sum display.
+ */
+export function getSelectedTypeForSum(
+ statTab: StatTabSlug,
+ type: SeriesSlugSelected | undefined,
+): 'summary' | SeriesSlugSelected | StatTabSlug {
+ if (statTab === 'summary')
+ return 'summary'
+ if (statTab === 'split')
+ return type ?? 'netIncome'
+ return statTab
+}
+
+/**
+ * Determine which chart series types to render.
+ */
+export function getTypesToShow(
+ statTab: StatTabSlug,
+ filteredType: SeriesSlugSelected,
+ type: SeriesSlugSelected | undefined,
+): string[] {
+ if (statTab === 'summary') {
+ if (filteredType === 'netIncome')
+ return ['income', 'expense']
+ if (filteredType === 'income')
+ return ['income']
+ if (filteredType === 'expense')
+ return ['expense']
+ }
+
+ if (statTab === 'expense' || statTab === 'income')
+ return [statTab]
+
+ return type ? [type] : ['income', 'expense']
+}
diff --git a/app/components/trns/itemWrap.vue b/app/components/trns/itemWrap.vue
index c7c8e8cd..1798825b 100644
--- a/app/components/trns/itemWrap.vue
+++ b/app/components/trns/itemWrap.vue
@@ -4,6 +4,8 @@ import type { TrnId, TrnItemFull } from '~/components/trns/types'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
+defineOptions({ inheritAttrs: false })
+
const props = defineProps<{
alt?: boolean
date?: string
@@ -53,7 +55,7 @@ function handleDeleteConfirm() {
</script>
<template>
- <UContextMenu :items="contextMenuItems">
+ <UContextMenu v-bind="$attrs" :items="contextMenuItems">
<TrnsItem
:alt="props.alt"
:trnItem
diff --git a/convex/wallets.ts b/convex/wallets.ts
index edeea413..bc45be38 100644
--- a/convex/wallets.ts
+++ b/convex/wallets.ts
@@ -3,8 +3,8 @@ import { v } from 'convex/values'
import { internal } from './_generated/api'
import { action, internalMutation, mutation, query } from './_generated/server'
import { CREDIT_LIMIT_MAX, getAuthUser, getOwnEntity, requireAuthUser, validateNumberRange, validateStringLength } from './shared'
-import { walletTypeValidator } from './validators'
import { removeTrnsFromHash } from './trnsHash'
+import { walletTypeValidator } from './validators'
export const list = query({
args: {},