Add support for deep category nesting

This commit is contained in:
Jonas Lochmann
2020-06-29 02:00:00 +02:00
parent 7c90b05f21
commit d08987ee5d
@@ -1,6 +1,6 @@
/* /*
* server component for the TimeLimit App * server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann * Copyright (C) 2019 - 2020 Jonas Lochmann
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as * it under the terms of the GNU Affero General Public License as
@@ -35,33 +35,44 @@ export async function dispatchSetParentCategory ({ action, cache }: {
} }
if (action.parentCategory !== '') { if (action.parentCategory !== '') {
const parentCategoryEntry = await cache.database.category.findOne({ const categoriesByUserId = (await cache.database.category.findAll({
where: { where: {
familyId: cache.familyId, familyId: cache.familyId,
categoryId: action.parentCategory,
childId: categoryEntry.childId childId: categoryEntry.childId
}, },
attributes: ['categoryId', 'parentCategoryId'],
transaction: cache.transaction transaction: cache.transaction
}) })).map((item) => ({
categoryId: item.categoryId,
parentCategoryId: item.parentCategoryId
}))
if (!parentCategoryEntry) { if (categoriesByUserId.find((item) => item.categoryId === action.parentCategory) === undefined) {
throw new Error('tried to set parent category to non existent category') throw new Error('selected parent category does not exist')
} }
if (parentCategoryEntry.parentCategoryId !== '') { const childCategoryIds = new Set<string>()
throw new Error('tried to set a category as parent which itself has got a parent')
{
const processedCategoryIds = new Set<string>()
const handle = (currentCategoryId: string) => {
if (processedCategoryIds.has(currentCategoryId)) return
processedCategoryIds.add(currentCategoryId)
const childCategories = categoriesByUserId.filter((item) => item.parentCategoryId === currentCategoryId)
childCategories.forEach((childCategory) => {
childCategoryIds.add(childCategory.categoryId)
handle(childCategory.categoryId)
})
}
handle(action.categoryId)
} }
const countChildCategories = await cache.database.category.findAndCountAll({ if (childCategoryIds.has(action.parentCategory) || action.parentCategory === action.categoryId) {
where: { throw new Error('can not set a category as parent which is a child of the category')
familyId: cache.familyId,
parentCategoryId: action.categoryId
},
transaction: cache.transaction
})
if (countChildCategories.count > 0) {
throw new Error('tried to make category a child category altough it is already a parent category')
} }
} }