using BankContracts.BindingModels; using BankContracts.BusinessLogicsContracts; using BankContracts.SearchModels; using BankContracts.StoragesContracts; using BankContracts.ViewModels; using Microsoft.Extensions.Logging; namespace BankBusinessLogic.BusinessLogics { public class AdditionsLogic : IAdditionsLogic { private readonly ILogger _logger; private readonly IAdditionsPlanStorage _additionsStorage; public AdditionsLogic(ILogger logger, IAdditionsPlanStorage mealPlanStorage) { _logger = logger; _additionsStorage = mealPlanStorage; } public bool Create(AdditionsBindingModel model) { CheckModel(model); if (_additionsStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); return false; } return true; } public bool Delete(AdditionsBindingModel model) { CheckModel(model, false); _logger.LogInformation("Delete. Id:{Id}", model.Id); if (_additionsStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); return false; } return true; } public AdditionsViewModel? ReadElement(AdditionsSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } _logger.LogInformation("ReadElement. MealPlanName:{MealPlanName}.Id:{Id}", model.AdditionsName, model.Id); var element = _additionsStorage.GetElement(model); if (element == null) { _logger.LogWarning("ReadElement element not found"); return null; } _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } public List? ReadList(AdditionsSearchModel? model) { _logger.LogInformation("ReadList. MealPlanName:{MealPlanName}.Id:{ Id}", model?.AdditionsName, model?.Id); var list = model == null ? _additionsStorage.GetFullList() : _additionsStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } public bool Update(AdditionsBindingModel model) { CheckModel(model); if (_additionsStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); return false; } return true; } private void CheckModel(AdditionsBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (!withParams) { return; } if (string.IsNullOrEmpty(model.AdditionsName)) { throw new ArgumentNullException("Нет названия плана питания", nameof(model.AdditionsName)); } if (model.AdditionsPrice<0) { throw new ArgumentNullException("Стоимость плана питания не может быть меньше 0", nameof(model.AdditionsPrice)); } _logger.LogInformation("MealPlan. MealPlanName:{MealPlanName}.MealPlanPrice:{ MealPlanPrice}. Id: { Id}", model.AdditionsName, model.AdditionsPrice, model.Id); var element = _additionsStorage.GetElement(new AdditionsSearchModel { AdditionsName = model.AdditionsName }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("План питания с таким названием уже есть"); } } } }