Skip to content

Open source personal finance application

refactor(categories): remove denormalized childIds, compute children from parentId

Ilya Komichevf97308c67111
diff --git a/app/components/categories/CommandPalette.vue b/app/components/categories/CommandPalette.vue
index ad006b8d..4ee9ce37 100644
--- a/app/components/categories/CommandPalette.vue
+++ b/app/components/categories/CommandPalette.vue
@@ -19,7 +19,6 @@ const cats = computed(() => {
const adjustmentCategory = categoriesStore.items.adjustment
const adjustmentGroup = {
...adjustmentCategory,
- childIds: undefined,
id: 'adjustment',
items: [{
id: 'adjustment',
@@ -32,8 +31,9 @@ const cats = computed(() => {
const rootGroups = categoriesStore.categoriesRootIds.map((id) => {
const category = categoriesStore.items[id]!
- const items = category?.childIds?.length
- ? categoriesStore.getChildrenIds(id).map(childId => ({
+ const children = categoriesStore.getChildrenIds(id)
+ const items = children.length
+ ? children.map(childId => ({
id: childId,
...categoriesStore.items[childId],
suffix: category.name,
@@ -46,7 +46,6 @@ const cats = computed(() => {
return {
...category,
- childIds: undefined,
id,
items,
slot: 'category',
diff --git a/app/components/categories/types.ts b/app/components/categories/types.ts
index 642c8193..582842df 100644
--- a/app/components/categories/types.ts
+++ b/app/components/categories/types.ts
@@ -18,7 +18,6 @@ export const categoryFormSchema = z.object({
export type CategoryForm = z.infer<typeof categoryFormSchema>
export type CategoryItem = CategoryForm & {
- childIds?: CategoryId[]
updatedAt?: number
}
diff --git a/app/components/categories/useCategoriesStore.test.ts b/app/components/categories/useCategoriesStore.test.ts
index d3df6765..84f74495 100644
--- a/app/components/categories/useCategoriesStore.test.ts
+++ b/app/components/categories/useCategoriesStore.test.ts
@@ -188,13 +188,13 @@ describe('useCategoriesStore', () => {
...store.items,
child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),
child2: makeCategory({ color: '#f00', name: 'Child 2', parentId: 'parent1' }),
- parent1: makeCategory({ childIds: ['child1', 'child2'], color: '#f00', name: 'Parent' }),
+ parent1: makeCategory({ color: '#f00', name: 'Parent' }),
}
store.saveCategory({
id: 'parent1',
isUpdateChildCategoriesColor: true,
- values: makeCategory({ childIds: ['child1', 'child2'], color: '#00f', name: 'Parent' }),
+ values: makeCategory({ color: '#00f', name: 'Parent' }),
})
expect(store.items.child1.color).toBe('#00f')
@@ -207,7 +207,7 @@ describe('useCategoriesStore', () => {
store.items = {
...store.items,
child1: makeCategory({ color: '#f00', name: 'Child 1', parentId: 'parent1' }),
- parent1: makeCategory({ childIds: ['child1'], color: '#f00', name: 'Parent' }),
+ parent1: makeCategory({ color: '#f00', name: 'Parent' }),
}
store.saveCategory({
@@ -222,13 +222,13 @@ describe('useCategoriesStore', () => {
)
})
- it('syncs childIds when parentId changes', () => {
+ it('computes children correctly after parentId change', () => {
const store = useCategoriesStore()
store.items = {
...store.items,
c1: makeCategory({ name: 'Child', parentId: 'oldParent' }),
newParent: makeCategory({ name: 'New Parent' }),
- oldParent: makeCategory({ childIds: ['c1'], name: 'Old Parent' }),
+ oldParent: makeCategory({ name: 'Old Parent' }),
}
store.saveCategory({
@@ -237,8 +237,8 @@ describe('useCategoriesStore', () => {
values: makeCategory({ name: 'Child', parentId: 'newParent' }),
})
- expect(store.items.oldParent.childIds).toBeUndefined()
- expect(store.items.newParent.childIds).toEqual(['c1'])
+ expect(store.getChildrenIds('oldParent')).toEqual([])
+ expect(store.getChildrenIds('newParent')).toEqual(['c1'])
})
it('shows toast on mutation failure', async () => {
@@ -350,17 +350,18 @@ describe('useCategoriesStore', () => {
})
})
- it('syncs parent childIds on delete', () => {
+ it('parent has no deleted child in getChildrenIds', () => {
const store = useCategoriesStore()
store.items = {
...store.items,
- c1: makeCategory({ name: 'Child', parentId: 'parent1' }),
- parent1: makeCategory({ childIds: ['c1', 'c2'], name: 'Parent' }),
+ c1: makeCategory({ name: 'Child 1', parentId: 'parent1' }),
+ c2: makeCategory({ name: 'Child 2', parentId: 'parent1' }),
+ parent1: makeCategory({ name: 'Parent' }),
}
store.deleteCategory('c1')
- expect(store.items.parent1.childIds).toEqual(['c2'])
+ expect(store.getChildrenIds('parent1')).toEqual(['c2'])
})
})
})
diff --git a/app/components/categories/useCategoriesStore.ts b/app/components/categories/useCategoriesStore.ts
index bf10c7f9..5f61484a 100644
--- a/app/components/categories/useCategoriesStore.ts
+++ b/app/components/categories/useCategoriesStore.ts
@@ -13,7 +13,6 @@ import { createDebouncedPersist, handleMutationResult, mergeOfflineOps, pushDele
import { createLogger } from '~/utils/logger'
const adjustment: CategoryItem = {
- childIds: [],
color: 'var(--text-4)',
icon: 'mdi:plus-minus',
name: 'Adjustment',
@@ -23,7 +22,6 @@ const adjustment: CategoryItem = {
}
const transfer: CategoryItem = {
- childIds: [],
color: 'var(--text-4)',
icon: 'mdi:repeat',
name: 'Transfer',
@@ -154,7 +152,7 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
return categoriesIds.value.filter((id) => {
if (id === 'transfer')
return false
- return !items.value[id]?.childIds?.length
+ return !hasChildren(id)
})
})
@@ -190,18 +188,20 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!category || category.parentId !== 0)
return false
- return !!category.childIds?.length
+ return Object.keys(items.value).some(id => items.value[id]?.parentId === categoryId)
}
function getChildrenIds(categoryId: CategoryId) {
if (!hasItems.value)
return []
- const category = items.value[categoryId]
- if (!category?.childIds?.length)
+ const children = Object.keys(items.value)
+ .filter(id => items.value[id]?.parentId === categoryId)
+
+ if (!children.length)
return []
- return [...category.childIds]
+ return children
.sort((a, b) => compareCategoriesByParentAndName(items.value[a]!, items.value[b]!, items.value))
}
@@ -209,10 +209,9 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
if (!hasItems.value)
return []
- const category = items.value[categoryId]
- return category?.childIds?.length
- ? [...category.childIds]
- : [categoryId]
+ const children = Object.keys(items.value)
+ .filter(id => items.value[id]?.parentId === categoryId)
+ return children.length ? children : [categoryId]
}
function getTransactibleIds(ids?: CategoryId[]) {
@@ -223,30 +222,10 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
return transactibleIdsSet.value.has(categoryId)
}
- function syncOptimisticParentChildIds(categories: Categories, id: CategoryId, oldParentId: CategoryId | 0, newParentId: CategoryId | 0) {
- if (oldParentId === newParentId)
- return
-
- if (oldParentId && oldParentId !== 0) {
- const pId = String(oldParentId)
- if (categories[pId]) {
- const filtered = (categories[pId].childIds ?? []).filter(cid => cid !== id)
- categories[pId] = { ...categories[pId], childIds: filtered.length ? filtered : undefined }
- }
- }
-
- if (newParentId && newParentId !== 0) {
- const pId = String(newParentId)
- if (categories[pId])
- categories[pId] = { ...categories[pId], childIds: [...(categories[pId].childIds ?? []), id] }
- }
- }
-
function applyOptimisticUpdate(id: CategoryId, categoryValues: CategoryItem, isUpdateChildCategoriesColor: boolean, categoryChildIds: CategoryId[]) {
- const existingChildIds = items.value?.[id]?.childIds
const updatedItems: Categories = {
...(items.value ?? {}),
- [id]: existingChildIds ? { ...categoryValues, childIds: existingChildIds } : categoryValues,
+ [id]: categoryValues,
}
if (isUpdateChildCategoriesColor && categoryChildIds.length > 0) {
@@ -256,8 +235,6 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
}
}
- syncOptimisticParentChildIds(updatedItems, id, items.value?.[id]?.parentId ?? 0, categoryValues.parentId)
-
setCategories(updatedItems)
}
@@ -315,15 +292,6 @@ export const useCategoriesStore = defineStore('categories', (): CategoriesStore
// Optimistic UI
const categories = { ...(items.value ?? {}) }
- const category = categories[id]
- if (category?.parentId && category.parentId !== 0) {
- const pId = String(category.parentId)
- const parent = categories[pId]
- if (parent) {
- const filtered = (parent.childIds ?? []).filter(cid => cid !== id)
- categories[pId] = { ...parent, childIds: filtered.length ? filtered : undefined }
- }
- }
delete categories[id]
setCategories(categories)
diff --git a/app/components/categories/utils.test.ts b/app/components/categories/utils.test.ts
index 5a36562d..9ac48f69 100644
--- a/app/components/categories/utils.test.ts
+++ b/app/components/categories/utils.test.ts
@@ -42,7 +42,6 @@ export const mockCategories: Categories = {
parentId: 0,
},
withChilds: {
- childIds: ['child1', 'child2'],
color: 'red',
icon: 'home',
name: 'No Selectable with childs',
@@ -68,9 +67,6 @@ const mockCategories2: Categories = {
showInQuickSelector: false,
},
'241120_k27ehb': {
- childIds: [
- '241120_7fxrno',
- ],
color: '#701a75',
icon: 'mdi:truck-delivery',
name: 'Auto',
@@ -79,7 +75,6 @@ const mockCategories2: Categories = {
showInQuickSelector: false,
},
'transfer': {
- childIds: [],
color: 'var(--ui-primary)',
icon: 'mdi:repeat',
name: 'Transfer',
diff --git a/app/components/categories/utils.ts b/app/components/categories/utils.ts
index 7abdfc70..e643a1de 100644
--- a/app/components/categories/utils.ts
+++ b/app/components/categories/utils.ts
@@ -1,13 +1,25 @@
import type { Categories, CategoryId, CategoryItem } from '~/components/categories/types'
export function getTransactibleCategoriesIds(items: Categories, ids?: CategoryId[]) {
+ const childrenMap = new Map<CategoryId, CategoryId[]>()
+ for (const id of Object.keys(items ?? {})) {
+ const parentId = items[id]?.parentId
+ if (parentId && parentId !== 0) {
+ const pid = String(parentId)
+ if (!childrenMap.has(pid))
+ childrenMap.set(pid, [])
+ childrenMap.get(pid)!.push(id)
+ }
+ }
+
const seen = new Set<CategoryId>()
const result: CategoryId[] = []
for (const id of ids ?? Object.keys(items ?? [])) {
const category = items?.[id]
- if (category?.parentId === 0 && category?.childIds?.length) {
- for (const childId of category.childIds) {
+ const children = childrenMap.get(id)
+ if (category?.parentId === 0 && children?.length) {
+ for (const childId of children) {
if (!seen.has(childId)) {
seen.add(childId)
result.push(childId)
diff --git a/convex/migrate.ts b/convex/migrate.ts
index 73f70ddd..924cd2b6 100644
--- a/convex/migrate.ts
+++ b/convex/migrate.ts
@@ -108,26 +108,17 @@ export const insertCategories = internalMutation({
},
handler: async (ctx, { categories, userId }) => {
const idMap: Record<string, string> = {}
- const inserts: Array<{ id: string, oldChildIds?: string[], oldParentId?: string }> = []
+ const inserts: Array<{ id: string, oldParentId?: string }> = []
- for (const { oldChildIds, oldId, oldParentId, ...data } of categories) {
+ for (const { oldChildIds: _oldChildIds, oldId, oldParentId, ...data } of categories) {
const id = await ctx.db.insert('categories', { ...data, userId })
idMap[oldId] = id
- inserts.push({ id, oldChildIds, oldParentId })
+ inserts.push({ id, oldParentId })
}
- for (const { id, oldChildIds, oldParentId } of inserts) {
- const patch: Record<string, unknown> = {}
+ for (const { id, oldParentId } of inserts) {
if (oldParentId && idMap[oldParentId]) {
- patch.parentId = idMap[oldParentId]
- }
- if (oldChildIds && oldChildIds.length > 0) {
- const mapped = oldChildIds.filter((cid: string) => idMap[cid]).map((cid: string) => idMap[cid])
- if (mapped.length > 0)
- patch.childIds = mapped
- }
- if (Object.keys(patch).length > 0) {
- await ctx.db.patch(id as any, patch)
+ await ctx.db.patch(id as any, { parentId: idMap[oldParentId] })
}
}
diff --git a/convex/schema.ts b/convex/schema.ts
index 3884be6c..532bb18c 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -5,7 +5,6 @@ import { TrnType, walletTypeValidator } from './validators'
export default defineSchema({
categories: defineTable({
- childIds: v.optional(v.array(v.id('categories'))),
color: v.string(),
icon: v.string(),
name: v.string(),