Skip to content

Open source personal finance application

refactor(stat): extract pure category grouping logic and add tests

Ilya Komichev911c71237778
diff --git a/app/components/stat/categories/collectAndGroup.test.ts b/app/components/stat/categories/collectAndGroup.test.ts
new file mode 100644
index 00000000..f072ab7e
--- /dev/null
+++ b/app/components/stat/categories/collectAndGroup.test.ts
@@ -0,0 +1,244 @@
+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'
+
+const categories: Categories = {
+ food: { color: 'red', name: 'Food', order: 0, parentId: 0 },
+ groceries: { color: 'green', name: 'Groceries', order: 0, parentId: 'food' },
+ restaurants: { color: 'blue', name: 'Restaurants', order: 0, parentId: 'food' },
+ salary: { color: 'yellow', name: 'Salary', order: 0, parentId: 0 },
+ transport: { color: 'orange', name: 'Transport', order: 0, parentId: 0 },
+}
+
+const trnsItems = {
+ t1: { categoryId: 'groceries' },
+ t2: { categoryId: 'groceries' },
+ t3: { categoryId: 'restaurants' },
+ t4: { categoryId: 'salary' },
+ t5: { categoryId: 'transport' },
+ t6: { categoryId: 'transfer' },
+ t7: { categoryId: 'groceries' },
+}
+
+describe('collectCategoriesByTrns', () => {
+ it('collects categories from transactions', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ trnsIds: ['t1', 't2', 't3', 't4', 't5'],
+ trnsItems,
+ })
+
+ expect(result.groceries.trnsIds).toEqual(['t1', 't2'])
+ expect(result.restaurants.trnsIds).toEqual(['t3'])
+ expect(result.salary.trnsIds).toEqual(['t4'])
+ expect(result.transport.trnsIds).toEqual(['t5'])
+ })
+
+ it('skips transfer category', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ trnsIds: ['t6'],
+ trnsItems,
+ })
+
+ expect(Object.keys(result)).toEqual([])
+ })
+
+ it('skips transactions with missing categories', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ trnsIds: ['t1'],
+ trnsItems: { t1: { categoryId: 'nonexistent' } },
+ })
+
+ expect(Object.keys(result)).toEqual([])
+ })
+
+ it('skips transactions without categoryId', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ trnsIds: ['t1'],
+ trnsItems: { t1: {} },
+ })
+
+ expect(Object.keys(result)).toEqual([])
+ })
+
+ it('adds preCategoriesIds even without matching transactions', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ preCategoriesIds: ['transport', 'salary'],
+ trnsIds: ['t1'],
+ trnsItems,
+ })
+
+ expect(result.transport).toBeDefined()
+ expect(result.transport.trnsIds).toEqual([])
+ expect(result.salary.trnsIds).toEqual([])
+ expect(result.groceries.trnsIds).toEqual(['t1'])
+ })
+
+ it('preCategoriesIds does not overwrite existing data', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ preCategoriesIds: ['groceries'],
+ trnsIds: ['t1', 't2'],
+ trnsItems,
+ })
+
+ expect(result.groceries.trnsIds).toEqual(['t1', 't2'])
+ })
+
+ it('returns empty for empty trnsIds', () => {
+ const result = collectCategoriesByTrns({
+ categoriesItems: categories,
+ trnsIds: [],
+ trnsItems,
+ })
+
+ expect(Object.keys(result)).toEqual([])
+ })
+})
+
+describe('flattenCategoriesWithValues', () => {
+ const collected: CategoriesWithData = {
+ groceries: { id: 'groceries', name: 'Groceries', trnsIds: ['t1', 't2'], value: 0 },
+ salary: { id: 'salary', name: 'Salary', trnsIds: ['t4'], value: 0 },
+ transport: { id: 'transport', name: 'Transport', trnsIds: ['t5'], value: 0 },
+ }
+
+ it('computes values using computeValue callback', () => {
+ const values: Record<string, number> = { t1: -50, t2: -30, t4: 1000, t5: -20 }
+ const computeValue = (ids: string[]) => ids.reduce((sum, id) => sum + (values[id] ?? 0), 0)
+
+ const result = flattenCategoriesWithValues(collected, computeValue)
+
+ expect(result.find(c => c.id === 'groceries')?.value).toBe(-80)
+ expect(result.find(c => c.id === 'salary')?.value).toBe(1000)
+ expect(result.find(c => c.id === 'transport')?.value).toBe(-20)
+ })
+
+ it('sorts by amount: positive first descending, then negative ascending', () => {
+ const data2: CategoriesWithData = {
+ high: { id: 'high', name: 'High', trnsIds: ['h'], value: 0 },
+ low: { id: 'low', name: 'Low', trnsIds: ['l'], value: 0 },
+ neg: { id: 'neg', name: 'Neg', trnsIds: ['n'], value: 0 },
+ }
+
+ const result2 = flattenCategoriesWithValues(data2, (ids) => {
+ const map: Record<string, number> = { h: 500, l: 200, n: -100 }
+ return map[ids[0]] ?? 0
+ })
+
+ expect(result2[0].value).toBe(500)
+ expect(result2[1].value).toBe(200)
+ expect(result2[2].value).toBe(-100)
+ })
+
+ it('puts zero-value categories at the end', () => {
+ const data: CategoriesWithData = {
+ empty: { id: 'empty', name: 'Empty', trnsIds: [], value: 0 },
+ full: { id: 'full', name: 'Full', trnsIds: ['x'], value: 0 },
+ }
+
+ const result = flattenCategoriesWithValues(data, ids => ids.length > 0 ? 100 : 0)
+
+ expect(result[0].id).toBe('full')
+ expect(result[1].id).toBe('empty')
+ })
+})
+
+describe('groupCategoriesWithValues', () => {
+ it('groups child categories under parent', () => {
+ const collected: CategoriesWithData = {
+ groceries: { id: 'groceries', name: 'Groceries', trnsIds: ['t1', 't2'], value: 0 },
+ restaurants: { id: 'restaurants', name: 'Restaurants', trnsIds: ['t3'], value: 0 },
+ }
+
+ const computeValue = (ids: string[]) => ids.length * -50
+
+ const result = groupCategoriesWithValues(collected, categories, computeValue)
+
+ expect(result).toHaveLength(1)
+ expect(result[0].id).toBe('food')
+ expect(result[0].name).toBe('Food')
+ expect(result[0].value).toBe(-150) // -100 + -50
+ expect(result[0].trnsIds).toEqual(['t1', 't2', 't3'])
+ expect(result[0].categories).toHaveLength(2)
+ })
+
+ it('keeps root categories without parent as standalone', () => {
+ const collected: CategoriesWithData = {
+ salary: { id: 'salary', name: 'Salary', trnsIds: ['t4'], value: 0 },
+ transport: { id: 'transport', name: 'Transport', trnsIds: ['t5'], value: 0 },
+ }
+
+ const computeValue = (ids: string[]) => ids.length * 100
+
+ const result = groupCategoriesWithValues(collected, categories, computeValue)
+
+ expect(result).toHaveLength(2)
+ expect(result.map(c => c.id)).toContain('salary')
+ expect(result.map(c => c.id)).toContain('transport')
+ expect(result.find(c => c.id === 'salary')?.categories).toEqual([])
+ })
+
+ it('mixes parent groups and standalone categories', () => {
+ const collected: CategoriesWithData = {
+ groceries: { id: 'groceries', name: 'Groceries', trnsIds: ['t1'], value: 0 },
+ transport: { id: 'transport', name: 'Transport', trnsIds: ['t5'], value: 0 },
+ }
+
+ const computeValue = (ids: string[]) => ids.length * -100
+
+ const result = groupCategoriesWithValues(collected, categories, computeValue)
+
+ expect(result).toHaveLength(2)
+ const foodGroup = result.find(c => c.id === 'food')
+ const transportItem = result.find(c => c.id === 'transport')
+
+ expect(foodGroup).toBeDefined()
+ expect(foodGroup?.categories).toHaveLength(1)
+ expect(transportItem).toBeDefined()
+ expect(transportItem?.categories).toEqual([])
+ })
+
+ it('sorts child categories by amount', () => {
+ const collected: CategoriesWithData = {
+ groceries: { id: 'groceries', name: 'Groceries', trnsIds: ['t1'], value: 0 },
+ restaurants: { id: 'restaurants', name: 'Restaurants', trnsIds: ['t3', 't3b'], value: 0 },
+ }
+
+ const computeValue = (ids: string[]) => ids.length * -50
+
+ const result = groupCategoriesWithValues(collected, categories, computeValue)
+ const foodGroup = result[0]
+
+ // restaurants: -100, groceries: -50 → restaurants first (larger absolute negative)
+ expect(foodGroup.categories![0].id).toBe('restaurants')
+ expect(foodGroup.categories![1].id).toBe('groceries')
+ })
+
+ it('sorts parent groups by total amount', () => {
+ const collected: CategoriesWithData = {
+ groceries: { id: 'groceries', name: 'Groceries', trnsIds: ['t1'], value: 0 },
+ transport: { id: 'transport', name: 'Transport', trnsIds: ['t5', 't5b', 't5c'], value: 0 },
+ }
+
+ const computeValue = (ids: string[]) => ids.length * -100
+
+ const result = groupCategoriesWithValues(collected, categories, computeValue)
+
+ // transport: -300, food(groceries): -100 → transport first
+ expect(result[0].id).toBe('transport')
+ expect(result[1].id).toBe('food')
+ })
+
+ it('handles empty input', () => {
+ const result = groupCategoriesWithValues({}, categories, () => 0)
+ expect(result).toEqual([])
+ })
+})
diff --git a/app/components/stat/categories/collectAndGroup.ts b/app/components/stat/categories/collectAndGroup.ts
new file mode 100644
index 00000000..ad702fad
--- /dev/null
+++ b/app/components/stat/categories/collectAndGroup.ts
@@ -0,0 +1,110 @@
+import type { Categories, CategoryId } from '~/components/categories/types'
+import type { CategoriesWithData, CategoryWithData } from '~/components/stat/types'
+import type { TrnId } from '~/components/trns/types'
+
+import { getParentCategoryIdOrUndefined } from '~/components/categories/utils'
+import { sortCategoriesByAmount } from '~/components/stat/utils'
+
+export function collectCategoriesByTrns(params: {
+ categoriesItems: Categories
+ preCategoriesIds?: CategoryId[]
+ trnsIds: TrnId[]
+ trnsItems: Record<TrnId, { categoryId?: string }>
+}): CategoriesWithData {
+ const { categoriesItems, preCategoriesIds, trnsIds, trnsItems } = params
+
+ const result: CategoriesWithData = {}
+
+ for (const trnId of trnsIds) {
+ const categoryId = trnsItems[trnId]?.categoryId
+ const category = categoryId && categoriesItems[categoryId]
+
+ if (!categoryId || !category || categoryId === 'transfer')
+ continue
+
+ result[categoryId] ??= {
+ id: categoryId,
+ name: category.name,
+ trnsIds: [],
+ value: 0,
+ }
+ result[categoryId].trnsIds.push(trnId)
+ }
+
+ if (preCategoriesIds) {
+ for (const catId of preCategoriesIds) {
+ const category = categoriesItems[catId]
+ if (!category)
+ continue
+
+ result[catId] ??= {
+ id: catId,
+ name: category.name,
+ trnsIds: [],
+ value: 0,
+ }
+ }
+ }
+
+ return result
+}
+
+export function flattenCategoriesWithValues(
+ categoriesByTrns: CategoriesWithData,
+ computeValue: (trnsIds: TrnId[]) => number,
+): CategoryWithData[] {
+ return Object.values(categoriesByTrns)
+ .map(cat => ({
+ ...cat,
+ value: computeValue(cat.trnsIds),
+ }))
+ .sort(sortCategoriesByAmount)
+}
+
+export function groupCategoriesWithValues(
+ categoriesByTrns: CategoriesWithData,
+ categoriesItems: Categories,
+ computeValue: (trnsIds: TrnId[]) => number,
+): CategoryWithData[] {
+ const grouped: CategoriesWithData = {}
+
+ for (const cat of Object.values(categoriesByTrns)) {
+ const parentId = getParentCategoryIdOrUndefined(categoriesItems, cat.id)
+ const parentCategory = parentId && categoriesItems[parentId]
+ const catTotal = computeValue(cat.trnsIds)
+
+ if (!parentId || !parentCategory) {
+ grouped[cat.id] ??= {
+ categories: [],
+ id: cat.id,
+ name: cat.name,
+ trnsIds: cat.trnsIds,
+ value: catTotal,
+ }
+ continue
+ }
+
+ grouped[parentId] ??= {
+ categories: [],
+ id: parentId,
+ name: parentCategory.name,
+ trnsIds: [],
+ value: 0,
+ }
+
+ grouped[parentId].categories ??= []
+ grouped[parentId].categories.push({
+ ...cat,
+ value: catTotal,
+ })
+ grouped[parentId].trnsIds.push(...cat.trnsIds)
+ grouped[parentId].value += catTotal
+ }
+
+ for (const group of Object.values(grouped)) {
+ if (group.categories && group.categories.length > 1)
+ group.categories.sort(sortCategoriesByAmount)
+ }
+
+ return Object.values(grouped).sort(sortCategoriesByAmount)
+}
diff --git a/app/components/stat/categories/useStatCategories.ts b/app/components/stat/categories/useStatCategories.ts
index 5d2d5df3..eb9eecc5 100644
--- a/app/components/stat/categories/useStatCategories.ts
+++ b/app/components/stat/categories/useStatCategories.ts
@@ -1,11 +1,10 @@
import type { CategoryId } from '~/components/categories/types'
-import type { CategoriesWithData, CategoryWithData } from '~/components/stat/types'
+import type { CategoryWithData } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import { useAmount } from '~/components/amount/useAmount'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { getParentCategoryIdOrUndefined } from '~/components/categories/utils'
-import { sortCategoriesByAmount } from '~/components/stat/utils'
+import { collectCategoriesByTrns, flattenCategoriesWithValues, groupCategoriesWithValues } from '~/components/stat/categories/collectAndGroup'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
export function useStatCategories() {
@@ -13,103 +12,19 @@ export function useStatCategories() {
const trnsStore = useTrnsStore()
const { getTotalOfTrnsIds } = useAmount()
- function collectCategoriesByTrns(trnsIds: TrnId[], preCategoriesIds?: CategoryId[]): CategoriesWithData {
- const categoriesByTrns = trnsIds.reduce((acc, trnId) => {
- const categoryId = trnsStore.items?.[trnId]?.categoryId
- const category = categoryId && categoriesStore.items[categoryId]
-
- if (!categoryId || !category || categoryId === 'transfer')
- return acc
-
- acc[categoryId] ??= {
- id: categoryId,
- name: category.name,
- trnsIds: [],
- value: 0,
- }
- acc[categoryId].trnsIds.push(trnId)
- return acc
- }, {} as CategoriesWithData)
-
- // Add preCategoriesIds to categoriesByTrns
- if (preCategoriesIds) {
- preCategoriesIds.forEach((catId) => {
- const category = categoriesStore.items[catId]
- if (!category)
- return
-
- categoriesByTrns[catId] = categoriesByTrns[catId] ?? {
- id: catId,
- name: category.name,
- trnsIds: [],
- value: 0,
- }
- })
- }
-
- return categoriesByTrns
- }
-
- function flattenCategories(categoriesByTrns: CategoriesWithData): CategoryWithData[] {
- return Object.values(categoriesByTrns)
- .map(cat => ({
- ...cat,
- value: getTotalOfTrnsIds(cat.trnsIds).sum,
- }))
- .sort(sortCategoriesByAmount)
- }
-
- function groupCategories(categoriesByTrns: CategoriesWithData): CategoryWithData[] {
- const groupedCategories = Object.values(categoriesByTrns).reduce((acc, cat) => {
- const parentId = getParentCategoryIdOrUndefined(categoriesStore.items, cat.id)
- const parentCategory = parentId && categoriesStore.items[parentId]
- const catTotal = getTotalOfTrnsIds(cat.trnsIds).sum
-
- if (!parentId || !parentCategory) {
- acc[cat.id] ??= {
- categories: [],
- id: cat.id,
- name: cat.name,
- trnsIds: cat.trnsIds,
- value: catTotal,
- }
- return acc
- }
-
- acc[parentId] ??= {
- categories: [],
- id: parentId,
- name: parentCategory.name,
- trnsIds: [],
- value: 0,
- }
-
- acc[parentId].categories ??= []
- acc[parentId].categories.push({
- ...cat,
- value: catTotal,
- })
- acc[parentId].trnsIds.push(...cat.trnsIds)
- acc[parentId].value += catTotal
-
- return acc
- }, {} as CategoriesWithData)
-
- // Sort child categories after grouping (not inside the loop)
- for (const group of Object.values(groupedCategories)) {
- if (group.categories?.length > 1)
- group.categories.sort(sortCategoriesByAmount)
- }
-
- return Object.values(groupedCategories).sort(sortCategoriesByAmount)
- }
+ const computeValue = (trnsIds: TrnId[]) => getTotalOfTrnsIds(trnsIds).sum
function getCategoriesWithData(trnsIds: TrnId[], isGrouped?: boolean, preCategoriesIds?: CategoryId[]): CategoryWithData[] {
- const categoriesByTrns = collectCategoriesByTrns(trnsIds, preCategoriesIds)
+ const collected = collectCategoriesByTrns({
+ categoriesItems: categoriesStore.items,
+ preCategoriesIds,
+ trnsIds,
+ trnsItems: trnsStore.items ?? {},
+ })
return isGrouped
- ? groupCategories(categoriesByTrns)
- : flattenCategories(categoriesByTrns)
+ ? groupCategoriesWithValues(collected, categoriesStore.items, computeValue)
+ : flattenCategoriesWithValues(collected, computeValue)
}
return {