public async Task <IEnumerable <DbPrice> > GlobalRecalculation(bool storePrices, int groupId, int pbandId, int setId, int unitId, DateTime?arrivedTime) { List <DbPrice> prices = new List <DbPrice>(); DateTime dt = DateTime.UtcNow; if (arrivedTime.HasValue) { dt = arrivedTime.Value; } var lastRecalculationTime = await _pricingRepo.GetLastMsmqStartTime(0); var canRecalculate = CanRecalculate(lastRecalculationTime, dt); //validate is it last recalculation more actual that current request date if (!canRecalculate) { var logId = await _pricingRepo.CreateMsmqLog("Dish Pricing Calculation Skipped", 0, groupId, pbandId, setId, unitId, dt); await _pricingRepo.UpdateMsmqLog(dt, logId, true); } else { var products = await _pricingRepo.GetProducts(); var parts = await _pricingRepo.GetProductParts(); bool restictBySupplier = await _pricingRepo.IsIngredientAccess(); IEnumerable <IngredientAlternate> alternates = new List <IngredientAlternate>(); if (restictBySupplier) { alternates = await _pricingRepo.GetIngredientAlternates(null); } ProductForest pf = new ProductForest(products.ToList(), parts.ToList(), alternates.ToList()); pf.BuildForest(); var groupPrices = await _pricingRepo.GetGroupProductPricesByGroup(0); Dictionary <int, ProductForest.CalculatedPrices> result = pf.CalculatePrice(groupPrices.ToList(), restictBySupplier); if (storePrices) { var logId = await _pricingRepo.CreateMsmqLog("Dish Pricing Calculation", 0, groupId, pbandId, setId, unitId, dt); bool isSuccess = true; foreach (var group in result) { var calculatedGroupId = group.Key == 0 ? new Nullable <int>() : group.Key; var msgStart = $"Start saving group {group.Key} total prices {group.Value.Prices.Count} at {DateTime.UtcNow}"; DebugLog(msgStart); //clear prices for group only if we do not have any if (!group.Value.Prices.Any()) { await _pricingRepo.ClearPrices(calculatedGroupId); } //in all other cases insert prices will clear old prices and will insert new one bool saveResult = _pricingRepo.InsertPrices(group.Value.Prices, calculatedGroupId, logId, dt); ErrorLog(group.Value.Errors.ToString()); var msgEnd = $"End saving group {group.Key} total prices {group.Value.Prices.Count} at {DateTime.UtcNow}"; DebugLog(msgEnd); if (!saveResult) { isSuccess = false; } } await _pricingRepo.UpdateMsmqLog(DateTime.UtcNow, logId, isSuccess); } foreach (var group in result) { foreach (var productPrice in group.Value.Prices) { prices.Add(new DbPrice() { GroupId = group.Key, ProductId = productPrice.Key, Price = productPrice.Value }); } } } return(prices); }