Skip to content

Commit 92c5c20

Browse files
committed
#35, #356 fixed circular nesting bug in product categories
1 parent 4fa2769 commit 92c5c20

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Modules/SimplCommerce.Module.Catalog/Controllers/CategoryApiController.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,12 @@ public async Task<IActionResult> Put(long id, CategoryForm model)
104104
category.IncludeInMenu = model.IncludeInMenu;
105105
category.IsPublished = model.IsPublished;
106106

107+
if (category.ParentId.HasValue && await HaveCircularNesting(category.Id, category.ParentId.Value))
108+
{
109+
ModelState.AddModelError("ParentId", "Parent category cannot be itself children");
110+
return BadRequest(ModelState);
111+
}
112+
107113
await SaveCategoryImage(category, model);
108114
await _categoryService.Update(category);
109115

@@ -207,5 +213,23 @@ private async Task<string> SaveFile(IFormFile file)
207213
await _mediaService.SaveMediaAsync(file.OpenReadStream(), fileName, file.ContentType);
208214
return fileName;
209215
}
216+
217+
private async Task<bool> HaveCircularNesting(long childId, long parentId)
218+
{
219+
var category = await _categoryRepository.Query().FirstOrDefaultAsync(x => x.Id == parentId);
220+
var parentCategoryId = category.ParentId;
221+
while (parentCategoryId.HasValue)
222+
{
223+
if(parentCategoryId.Value == childId)
224+
{
225+
return true;
226+
}
227+
228+
var parentCategory = await _categoryRepository.Query().FirstAsync(x => x.Id == parentCategoryId);
229+
parentCategoryId = parentCategory.ParentId;
230+
}
231+
232+
return false;
233+
}
210234
}
211235
}

0 commit comments

Comments
 (0)