예제 #1
0
        public IActionResult Delete(EntityViewModel vm)
        {
            bool errorMessageSet = false;
            var  userID          = User.FindFirstValue(ClaimTypes.NameIdentifier);

            //Check for absorption category selection.
            if (vm.AbsorptionEntity.EntityID != 0)
            {
                //Make sure user owns both the absorbed and absorbing categories
                if (!_categoryRepository.UserOwnsCategory(vm.EntityOfInterest.EntityID, userID) ||
                    !_categoryRepository.UserOwnsCategory(vm.AbsorptionEntity.EntityID, userID))
                {
                    //TODO: Perhaps a more specific message to the user?
                    return(NotFound());
                }

                //Convert the VMCategories to DBCategories
                Category absorbedCategory  = _categoryRepository.Get(vm.EntityOfInterest.EntityID, userID);
                Category absorbingCategory = _categoryRepository.Get(vm.AbsorptionEntity.EntityID, userID);

                //Ensure that the deleted category is not default.
                if (!absorbedCategory.IsDefault)
                {
                    //Make sure the absorbing category and the deleting category are not the same.
                    if (absorbedCategory.CategoryID != absorbingCategory.CategoryID)
                    {
                        //Update all transactions that currently point to the category being deleted to instead point to the absorbing category.
                        _categoryRepository.Absorption(absorbedCategory.CategoryID, absorbingCategory.CategoryID, userID);

                        //Delete the category to be deleted.
                        _categoryRepository.Delete(absorbedCategory.CategoryID);

                        TempData["Message"] = "Category successfully deleted.";

                        return(RedirectToAction("Index"));
                    }
                    SetErrorMessage(vm, "Category being deleted and category absorbing cannot be the same.", errorMessageSet);
                    errorMessageSet = true;
                }
                SetErrorMessage(vm, "Deleting a default category is not allowed.", errorMessageSet);
                errorMessageSet = true;
            }
            SetErrorMessage(vm, "You must select a category to absorb transactions related to the category being deleted.", errorMessageSet);

            EntityViewModel failureStateVM = new EntityViewModel();

            failureStateVM.EntityOfInterest   = vm.EntityOfInterest;
            failureStateVM.CategorySelectList = failureStateVM.InitCategorySelectList(_categoryRepository, userID);
            return(View(failureStateVM));
        }