public async Task<IActionResult> UpdateCompoundDish(int id, UpdateCompoundDishRequest dish) { var loggedUser = User.GetUserIdFromToken(); var result = await _compoundDishService.UpdateCompoundDishAsync(loggedUser, id, dish); var mapped = _mapper.Map<CompoundDishResponse>(result); return Ok(new ApiOkResponse(mapped)); }
private async Task AuxUpdateCompountDishAsync(CompoundDish compoundDish, UpdateCompoundDishRequest dish) { compoundDish.Name = dish.Name; compoundDish.ModifiedAt = DateTime.UtcNow; if (dish.Image != null) { if (!string.IsNullOrEmpty(compoundDish.Image)) { await _fileService.DeleteFileAsync(compoundDish.Image); } string guid = Guid.NewGuid().ToString(); await _fileService.UploadFileAsync(dish.Image, guid); compoundDish.Image = guid; compoundDish.ImageMimeType = dish.Image.ContentType; } // delete previous dishes foreach (var item in compoundDish.DishCompoundDishes) { _uow.DishCompoundDishRepository.Delete(item); } if (dish.Dishes != null) { foreach (var item in dish.Dishes) { var dComDish = new DishCompoundDish { CompoundDishId = compoundDish.Id, DishId = item.DishId, DishQty = item.Qty }; await _uow.DishCompoundDishRepository.AddAsync(dComDish); } } _uow.CompoundDishRepository.Update(compoundDish); }
public async Task <CompoundDish> UpdateCompoundDishAsync(int ownerId, int id, UpdateCompoundDishRequest dish) { if (dish.Dishes == null) { throw new InvalidDataException(ExceptionConstants.INVALID_DATA, "Dishes"); } var compoundDish = await _uow.CompoundDishRepository.GetAll().Where(c => c.Id == id && !c.IsDeleted) .Include(c => c.CreatedBy) .Include(c => c.DishCompoundDishes) .Include(c => c.EatCompoundDishes) .Include(d => d.FavoriteDishes) .Include(d => d.LackSelfControlDishes) .FirstOrDefaultAsync(); if (compoundDish == null) { throw new NotFoundException(ExceptionConstants.NOT_FOUND, "Dish"); } var existName = await _uow.CompoundDishRepository.FindByAsync(c => c.UserId == ownerId && c.Id != id && c.Name == dish.Name && !c.IsDeleted); if (existName.Count > 0) { throw new InvalidDataException(ExceptionConstants.INVALID_DATA, "Dish name"); } var isInUse = compoundDish.EatCompoundDishes.Count() > 0; if (isInUse) { // Duplicate and return the new one, mark the old one as deleted var cd = await AuxCreateCompoundDishAsync(ownerId, dish, compoundDish); compoundDish.DeletedAt = DateTime.UtcNow; compoundDish.IsDeleted = true; await _uow.CompoundDishRepository.UpdateAsync(compoundDish, compoundDish.Id); await _uow.CommitAsync(); // After create the new one then update with new values await AuxUpdateCompountDishAsync(cd, dish); await _uow.CommitAsync(); return(cd); } else { // It is not in use so update it as usually await AuxUpdateCompountDishAsync(compoundDish, dish); await _uow.CommitAsync(); return(compoundDish); } }