public void Execute(int databaseId) { try { Logger.Info($"{GetType().Name} - [Common Background Tasks] Starting job for organization with database id: {databaseId}"); //should get older background tasks with status new and one by one to try processing it before processing try to change status and after processing update status //processing itself should happen like listener.Process method var org = _orgManager.GetById(databaseId); if (!string.IsNullOrEmpty(org.ConnectionString)) { IBackgroundTaskManager taskManager = new BackgroundTaskManager(org.ConnectionString, Process.GetCurrentProcess().ProcessName); var repo = new Common.Repository.PricingRepository(org.ConnectionString, Constants.TIMEOUT_MSMQ_EXEC_STOREDPROC); var engine = new PriceEngine(repo, Logger); var tasks = taskManager.ListTasks(Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.New, null, null, false, 100, 0); BackgroundTaskProcessor processor = new BackgroundTaskProcessor(databaseId, org.ConnectionString, _databaseManager, engine, Logger); foreach (var t in tasks) { try { Logger.Info($"Task {t.Id} Processing"); var res = taskManager.UpdateTaskStatus(t.Id, t.Status, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.InProgress, string.Empty).Result; processor.ProcessMessage(t); res = taskManager.UpdateTaskStatus(t.Id, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.InProgress, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.Completed, string.Empty).Result; Logger.Info($"Task {t.Id} Processing Complete"); } catch (Exception ex) { var res = taskManager.UpdateTaskStatus(t.Id, null, Fourth.StarChef.Invariables.Enums.BackgroundTaskStatus.Failed, ex.Message).Result; } } } else { Logger.Warn($"OrganizationId {databaseId} not found"); } Logger.Info($"{GetType().Name} - [Common Background Tasks] Finishing job for organization with database id: {databaseId}"); } catch (Exception ex) { var errorMessage = new StringBuilder(); errorMessage.AppendFormat($"{GetType().Name} - [Common Background Tasks] error for organization with database id: {databaseId} "); if (!string.IsNullOrEmpty(ex.Message)) { errorMessage.AppendFormat($"Exception message is: {ex.Message} "); } if (ex.InnerException != null && (!string.IsNullOrEmpty(ex.InnerException.Message))) { errorMessage.AppendFormat($"Inner Exception message is: {ex.InnerException.Message}"); } Logger.Error(errorMessage.ToString()); } }
public void SkipPriceRecalculationEndTime() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); int logIdResult = 123; string actionExpected = "Dish Pricing Calculation Skipped"; string actionResult = string.Empty; DateTime dtResult = DateTime.MinValue; int productIdResult; DateTime messageTime = DateTime.UtcNow; repo.Setup(x => x.GetLastMsmqStartTime(0)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { EndTime = DateTime.UtcNow.AddHours(1) })); }); repo.Setup(x => x.CreateMsmqLog(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <DateTime>())).Callback <string, int, int, int, int, int, DateTime>((string action, int productId, int groupid, int pbandId, int setid, int unitId, DateTime dt) => { actionResult = action; dtResult = dt; productIdResult = productId; }).Returns(() => { return(Task.FromResult <int>(logIdResult)); }); IPriceEngine engine = new PriceEngine(repo.Object); var result = engine.GlobalRecalculation(true, messageTime).Result; Assert.Empty(result); Assert.Equal(actionExpected, actionResult); Assert.Equal(messageTime, dtResult); Assert.Equal(messageTime, dtResult); }
public async virtual void ProductPriceRecalculation(ITestOutputHelper output, int productId) { IPriceEngine engine = new PriceEngine(_pricingRepository); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); var result = _customerDbRepository.ExecutePriceRecalculation(productId, 0, 0, 0, 0); sw.Stop(); output.WriteLine($"Old price recalculation takes {sw.Elapsed.TotalSeconds} seconds."); //acknoledge sw.Restart(); var dbPrices = result.ToList(); var dt = System.DateTime.UtcNow; //act var prices = await engine.Recalculation(productId, false, dt); sw.Stop(); output.WriteLine($"New price recalculation takes {sw.Elapsed.TotalSeconds} seconds."); //Assert.Equal(dbPrices.Count, prices.Count()); var priceToUpdate = engine.ComparePrices(dbPrices, prices).ToList(); Assert.Empty(priceToUpdate); var pricesToDelete = engine.ComparePrices(prices, dbPrices).ToList(); Assert.Empty(pricesToDelete); output.WriteLine($"Total Prices {prices.Count() }"); }
public void PriceRecalculationStoreSaveFailed() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); int logIdResult = 123; string actionExpected = "Dish Pricing Calculation"; string actionResult = string.Empty; DateTime dtResult = DateTime.MinValue; int productIdResult; DateTime messageTime = DateTime.UtcNow; repo.Setup(x => x.GetLastMsmqStartTime(0)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { StartTime = DateTime.UtcNow.AddHours(-1) })); }); repo.Setup(x => x.CreateMsmqLog(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <DateTime>())).Callback <string, int, int, int, int, int, DateTime>((string action, int productId, int groupid, int pbandId, int setid, int unitId, DateTime dt) => { actionResult = action; dtResult = dt; productIdResult = productId; }).Returns(() => { return(Task.FromResult <int>(logIdResult)); }); List <ProductGroupPrice> privateItems = new List <ProductGroupPrice>(); privateItems.Add(new ProductGroupPrice() { GroupId = 0, Price = 123.321m, ProductId = 1122 }); List <DbPrice> expectedPrices = new List <DbPrice>(); expectedPrices.Add(new DbPrice() { ProductId = 1122, Price = 123.321m }); List <Product> products = new List <Product>(); products.Add(new Product() { ScopeId = 3, ProductId = 1122 }); repo.Setup(x => x.GetProducts()).Returns(() => { return(Task.FromResult <IEnumerable <Product> >(products)); }); repo.Setup(x => x.GetProductParts()).Returns(() => { return(Task.FromResult <IEnumerable <ProductPart> >(new List <ProductPart>())); }); repo.Setup(x => x.GetGroupProductPricesByGroup(It.IsAny <int>())).Returns(() => { return(Task.FromResult <IEnumerable <ProductGroupPrice> >(privateItems)); }); repo.Setup(x => x.InsertPrices(It.IsAny <Dictionary <int, decimal> >(), It.Is <int?>(g => !g.HasValue), It.Is <int>(l => l == 123), It.Is <DateTime>(d => d == messageTime))).Returns(false); bool expectedSave = false; bool currentSave = true; repo.Setup(x => x.UpdateMsmqLog(It.IsAny <DateTime>(), It.Is <int>(l => l == 123), It.Is <bool>(b => !b))).Returns(() => Task.FromResult <int>(1)).Callback((DateTime dt, int logid, bool success) => { currentSave = success; }); IPriceEngine engine = new PriceEngine(repo.Object); var result = engine.GlobalRecalculation(true, messageTime).Result; Assert.Equal(expectedSave, currentSave); Assert.Equal(actionExpected, actionResult); Assert.NotEmpty(result); Assert.Equal(expectedPrices, result); }
public void PriceRecalculationPriceComparison() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); IPriceEngine engine = new PriceEngine(repo.Object); List <DbPrice> existingPrices = new List <DbPrice>(); existingPrices.Add(new DbPrice() { GroupId = 1, ProductId = 1, Price = 1m }); existingPrices.Add(new DbPrice() { GroupId = 2, ProductId = 1, Price = 1m }); List <DbPrice> newPrices = new List <DbPrice>(); newPrices.Add(new DbPrice() { GroupId = 1, ProductId = 1, Price = 1m }); newPrices.Add(new DbPrice() { GroupId = 2, ProductId = 1, Price = 1m }); var result = engine.ComparePrices(existingPrices, newPrices); Assert.Empty(result); newPrices.Add(new DbPrice() { GroupId = 3, ProductId = 1, Price = 1m }); result = engine.ComparePrices(existingPrices, newPrices); Assert.Single(result); existingPrices.Add(new DbPrice() { GroupId = 3, ProductId = 1, Price = 1.1m }); result = engine.ComparePrices(existingPrices, newPrices); Assert.Single(result); existingPrices.Add(new DbPrice() { GroupId = 4, ProductId = 1, Price = 1m }); result = engine.ComparePrices(existingPrices, newPrices); Assert.Single(result); result = engine.ComparePrices(newPrices, existingPrices); Assert.Equal(2, result.Count()); }
public async Task ItFailsIfNoQuotesReturned() { var priceEngine = new PriceEngine(CreatePriceRequestValidatorMock().Object, new List <IQuotationSystem>()); var priceResult = await priceEngine.GetPrice(new PriceRequest()); Assert.False(priceResult.Success); Assert.Equal("QUOTATION", priceResult.Error.First().Key); Assert.Equal("Failed to fetch a quote", priceResult.Error.First().Value.First()); }
public void PriceRecalculationEnabled() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); repo.Setup(x => x.GetDbSetting(It.IsAny <string>())).Returns(() => { return(Task.FromResult <string>("1")); }); IPriceEngine engine = new PriceEngine(repo.Object); var result = engine.IsEngineEnabled().Result; Assert.True(result); }
public void PriceRecalculationPriceComparisonA() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); IPriceEngine engine = new PriceEngine(repo.Object); List <DbPrice> existingPrices = new List <DbPrice>(); existingPrices.Add(new DbPrice() { GroupId = 1, ProductId = 1, Price = 1m }); existingPrices.Add(new DbPrice() { GroupId = 1, ProductId = 2, Price = 2m }); List <DbPrice> newPrices = new List <DbPrice>(); newPrices.Add(new DbPrice() { GroupId = 1, ProductId = 1, Price = 1m }); newPrices.Add(new DbPrice() { GroupId = 1, ProductId = 2, Price = 2m }); var existingPrices_dict = existingPrices.GroupBy(g => g.GroupId).ToDictionary(k => k.Key, v => v.ToList()); ConcurrentBag <DbPrice> bag = new ConcurrentBag <DbPrice>(); engine.GetPriceDifferences(existingPrices_dict, bag, 1, newPrices); Assert.Empty(bag); newPrices.Add(new DbPrice() { GroupId = 1, ProductId = 3, Price = 1.1m }); bag = new ConcurrentBag <DbPrice>(); engine.GetPriceDifferences(existingPrices_dict, bag, 1, newPrices); Assert.Single(bag); newPrices = new List <DbPrice>(); newPrices.Add(new DbPrice() { GroupId = 1, ProductId = 1, Price = 1.1m }); bag = new ConcurrentBag <DbPrice>(); engine.GetPriceDifferences(existingPrices_dict, bag, 1, newPrices); Assert.Single(bag); }
public async Task ItReturnsLowestQuotePrice() { var quotationSystems = new List <IQuotationSystem> { CreateQuotationSystemMock(3).Object, CreateQuotationSystemMock(2).Object, CreateQuotationSystemMock(4).Object }; var priceEngine = new PriceEngine(CreatePriceRequestValidatorMock().Object, quotationSystems); var priceResult = await priceEngine.GetPrice(new PriceRequest()); Assert.True(priceResult.Success); Assert.Equal(2, priceResult.Value.Price); }
public async virtual void GlobalPriceRecalculationNoStorage(ITestOutputHelper output) { IPriceEngine engine = new PriceEngine(_pricingRepository); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); _customerDbRepository.ClearPrices(); //act var prices = await engine.GlobalRecalculation(false, System.DateTime.UtcNow); sw.Stop(); output.WriteLine($"Total Prices {prices.Count() }"); output.WriteLine($"Total Seconds {sw.Elapsed.TotalSeconds }"); }
public void BasketTotalAmount_GivenBasket_BaksetTotalAmountShouldBe10() { //Arrange var expected = 10; IPriceEngine priceEngine = new PriceEngine(); ICheckout checkout = new Checkout(priceEngine); var basket = new Basket(); var itemA = new BasketItem("A"); basket.Add(itemA); //Act var total = checkout.BasketTotalAmount(basket.basketItems); //Assert Assert.That(total, Is.EqualTo(expected)); }
public void PriceRecalculationNoStore() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); DateTime messageTime = DateTime.UtcNow; repo.Setup(x => x.GetLastMsmqStartTime(0)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { StartTime = DateTime.UtcNow.AddHours(-1) })); }); repo.Setup(x => x.GetProducts()).Returns(() => { return(Task.FromResult <IEnumerable <Product> >(new List <Product>())); }); repo.Setup(x => x.GetProductParts()).Returns(() => { return(Task.FromResult <IEnumerable <ProductPart> >(new List <ProductPart>())); }); repo.Setup(x => x.GetGroupProductPricesByGroup(It.IsAny <int>())).Returns(() => { return(Task.FromResult <IEnumerable <ProductGroupPrice> >(new List <ProductGroupPrice>())); }); IPriceEngine engine = new PriceEngine(repo.Object); var result = engine.GlobalRecalculation(false, messageTime).Result; Assert.Empty(result); }
public async virtual void GlobalPriceRecalculation(ITestOutputHelper output) { IPriceEngine engine = new PriceEngine(_pricingRepository); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); //var result = _pricingRepository.GetPrices().Where(g => g.GroupId == 225); //var prices = engine.GlobalRecalculation().Where(g => g.GroupId == 225).ToList(); _customerDbRepository.ClearPrices(); //var result = await _pricingRepository.GetPrices(); var result = _customerDbRepository.ExecutePriceRecalculation(0, 0, 0, 0, 0); sw.Stop(); output.WriteLine($"Old price recalculation takes {sw.Elapsed.TotalSeconds} seconds."); //acknoledge sw.Restart(); var dbPrices = result.ToList(); //act var prices = await engine.GlobalRecalculation(false, System.DateTime.UtcNow); sw.Stop(); output.WriteLine($"New price recalculation takes {sw.Elapsed.TotalSeconds} seconds."); Assert.Equal(dbPrices.Count, prices.Count()); var priceToUpdate = engine.ComparePrices(dbPrices, prices).ToList(); Assert.Empty(priceToUpdate); var pricesToDelete = engine.ComparePrices(prices, dbPrices).ToList(); Assert.Empty(pricesToDelete); output.WriteLine($"Total Prices {prices.Count() }"); }
static void Main(string[] args) { //var cnStr = "Initial Catalog=SCNET_Tish_Price_Test;Data Source=ie1scqaidb01.northeurope.cloudapp.azure.com;User ID=sl_web_user; Password=reddevil;"; //var cnStr = "Initial Catalog=SCNET_trg;Data Source=ie1scqaidb01.northeurope.cloudapp.azure.com;User ID=sl_web_user; Password=reddevil;"; //var cnStr = "Initial Catalog=SCNET_marstons;Data Source=ie1scqaidb01.northeurope.cloudapp.azure.com;User ID=sl_web_user; Password=reddevil;"; //var cnStr = "Initial Catalog=SCNET_trg;Data Source=.\\sqlexpress;User ID=sl_web_user; Password=reddevil;"; var cnStr = "Initial Catalog=SCNET_marstons;Data Source=.\\sqlexpress;User ID=sl_web_user; Password=reddevil;"; //var t = new RecalculationTests(cnStr); //t.RecipePriceRecalculations(); //return; Common.Repository.PricingRepository pr = new Common.Repository.PricingRepository(cnStr, 360); //var groupPrices2 = pr.GetGroupProductPricesByProduct(0, 455751, 0, 0, 0); //var prices = pr.GetPrices(); IPriceEngine engine = new PriceEngine(pr); //var prices = engine.CalculatePrices(0, 152596, 0, 0, 0); //var prices = engine.CalculatePrices(0, 0, 0, 1, 0); //var prices = engine.CalculatePrices(0, 0, 0, 0, 369); var prices = engine.GlobalRecalculation(false, System.DateTime.UtcNow).Result; //var prices = engine.CalculatePrices(0, 0, 0, 0, 0).ToList(); var taskPrices = pr.GetPrices().Result; var dbPrices = taskPrices.OrderBy(x => x.ProductId).ToList(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); var priceToUpdate = engine.ComparePrices(dbPrices, prices).ToList(); var pricesToDelete = engine.ComparePrices(prices, dbPrices).ToList(); sw.Stop(); System.Diagnostics.Trace.WriteLine($"prices to update - {priceToUpdate.Count}"); System.Diagnostics.Trace.WriteLine($"prices to delete - {pricesToDelete.Count}"); System.Diagnostics.Trace.WriteLine($"Total Comparison time - {sw.Elapsed.TotalSeconds}"); }
public void Setup() { _engine = new DummyPriceEngineInitializer().Load(); }
public void RecalculationStore() { Mock <IPricingRepository> repo = new Mock <IPricingRepository>(); int logIdResult = 123; string actionExpected = "Dish Pricing Calculation"; string actionExpectedSkipped = "Dish Pricing Calculation Skipped"; string actionResult = string.Empty; DateTime dtResult = DateTime.MinValue; int productIdResult; DateTime messageTime = DateTime.UtcNow; int productId = 1122; bool isSuccessStatusUpdate = false; repo.Setup(x => x.GetLastMsmqStartTime(productId)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { StartTime = DateTime.UtcNow.AddHours(-1) })); }); repo.Setup(x => x.CreateMsmqLog(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <DateTime>())).Callback <string, int, int, int, int, int, DateTime>((string action, int product_Id, int groupid, int pbandId, int setid, int unitId, DateTime dt) => { actionResult = action; dtResult = dt; productIdResult = product_Id; }).Returns(() => { return(Task.FromResult <int>(logIdResult)); }); List <ProductGroupPrice> privateItems = new List <ProductGroupPrice>(); privateItems.Add(new ProductGroupPrice() { GroupId = 0, Price = 123.321m, ProductId = productId }); List <DbPrice> expectedPrices = new List <DbPrice>(); expectedPrices.Add(new DbPrice() { ProductId = productId, Price = 123.321m }); List <Product> products = new List <Product>(); products.Add(new Product() { ScopeId = 3, ProductId = productId }); repo.Setup(x => x.GetProducts()).Returns(() => { return(Task.FromResult(products.AsEnumerable())); }); repo.Setup(x => x.GetProductParts()).Returns(() => { return(Task.FromResult(new List <ProductPart>().AsEnumerable())); }); var res = new Tuple <IEnumerable <Product>, IEnumerable <ProductPart> >(products, new List <ProductPart>()); repo.Setup(x => x.GetProductsAndParts(It.IsAny <int>())).Returns(() => { return(Task.FromResult(res)); }); repo.Setup(x => x.GetGroupProductPricesByProduct(It.IsAny <int>())).Returns(() => { return(Task.FromResult <IEnumerable <ProductGroupPrice> >(privateItems)); }); repo.Setup(x => x.UpdatePrices(It.IsAny <Dictionary <int, decimal> >(), It.Is <int?>(g => !g.HasValue), It.Is <int>(l => l == 123), It.Is <DateTime>(d => d == messageTime))).Returns(true); repo.Setup(x => x.UpdateMsmqLog(It.IsAny <DateTime>(), It.Is <int>(l => l == 123), It.IsAny <bool>())).Callback <DateTime, int, bool>((DateTime dt, int product_Id, bool isSuccess) => { isSuccessStatusUpdate = isSuccess; dtResult = dt; productIdResult = product_Id; }).Returns(() => Task.FromResult <int>(1)); IPriceEngine engine = new PriceEngine(repo.Object); var result = engine.Recalculation(productId, true, messageTime).Result; Assert.Equal(actionExpected, actionResult); Assert.NotEmpty(result); Assert.Equal(expectedPrices, result); Assert.True(isSuccessStatusUpdate); repo.Setup(x => x.GetLastMsmqStartTime(productId)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { StartTime = DateTime.UtcNow.AddHours(1) })); }); engine = new PriceEngine(repo.Object); result = engine.Recalculation(productId, true, messageTime).Result; Assert.Equal(actionExpectedSkipped, actionResult); Assert.Empty(result); repo.Setup(x => x.GetLastMsmqStartTime(productId)).Returns(() => { return(Task.FromResult <MsmqLog>(new MsmqLog() { StartTime = DateTime.UtcNow.AddHours(-1) })); }); repo.Setup(x => x.UpdatePrices(It.IsAny <Dictionary <int, decimal> >(), It.Is <int?>(g => !g.HasValue), It.Is <int>(l => l == 123), It.Is <DateTime>(d => d == messageTime))).Returns(false); engine = new PriceEngine(repo.Object); result = engine.Recalculation(productId, true, messageTime).Result; Assert.Equal(actionExpected, actionResult); Assert.NotEmpty(result); Assert.Equal(expectedPrices, result); Assert.False(isSuccessStatusUpdate); }
public PricingController(PriceEngine priceEngine) { _priceEngine = priceEngine; }
public BooksController(BookDbContext bookContext, PriceEngine priceEngine, RatingEngine ratingEngine) { _bookContext = bookContext; _priceEngine = priceEngine; _ratingEngine = ratingEngine; }
public void Setup() { priceEngine = new PriceEngine(); }