Ejemplo n.º 1
0
        /// <summary>
        /// Sends Enrollment Welcome Message To Customer
        /// Template:
        /// SendEnrollmentWelcomeTemplate
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public int SendEnrollmentWelcomeMessage(OrderPlacedEvent result)
        {
            var messageTemplate = GetActiveMessageTemplate(SendEnrollmentWelcomeTemplate, _store.Id);

            if (messageTemplate == null)
            {
                return(0);
            }

            if (result == null || result.Order == null || result.Order.CustomerId == 0)
            {
                return(0);
            }


            Order    order        = result.Order;
            Customer customer     = _customerService.GetCustomerById(order.CustomerId);
            bool     isEnrollment = order.OrderItems.Any(item => Utilities.IsEnrollment(item.ProductId));

            // make sure product was successfully ordered !!
            if (
                !isEnrollment ||
                order.CaptureTransactionResult.ToLower() != "success" ||
                customer == null

                )
            {
                return(0);
            }


            return(SendCustomerEmail(customer, messageTemplate));
        }
Ejemplo n.º 2
0
        public async Task DeductFromRunningTotal_timeout_is_requested()
        {
            var saga = new OrderDiscountPolicy()
            {
                Data = new OrderDiscountPolicy.OrderDiscountData()
                {
                    CustomerId = 123
                }
            };
            var context = new TestableMessageHandlerContext();

            int expectedOrderTotalAmount = 100;
            var orderPlaced = new OrderPlacedEvent()
            {
                CustomerId       = 123,
                OrderId          = 789,
                OrderTotalAmount = expectedOrderTotalAmount
            };

            await saga.Handle(orderPlaced, context);

            var deductFromRunningTotalTimeout = context.SentMessages.SingleOrDefault(m => m.Message.GetType() == typeof(OrderDiscountPolicy.DeductFromRunningTotal));

            Assert.IsNotNull(deductFromRunningTotalTimeout);
            Assert.AreEqual(expectedOrderTotalAmount, deductFromRunningTotalTimeout.Message <OrderDiscountPolicy.DeductFromRunningTotal>().OrderTotalAmount);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Handle order placed event
 /// </summary>
 /// <param name="eventMessage">Event message</param>
 public void HandleEvent(OrderPlacedEvent eventMessage)
 {
     if (eventMessage?.Order != null)
     {
         _facebookPixelService.PreparePurchaseScript(eventMessage.Order);
     }
 }
Ejemplo n.º 4
0
        private void NotifySubscriber()
        {
            var orderPlacedEvent = new OrderPlacedEvent
            {
                Product = this._product
            };

            try
            {
                using (var queue = new MessageQueue("FormatName:MULTICAST=234.1.1.1:8001"))
                {
                    var message = new Message
                    {
                        BodyStream  = orderPlacedEvent.ToJsonStream(),
                        Label       = orderPlacedEvent.GetMessageType(),
                        Recoverable = true
                    };
                    queue.Send(message);
                }
            }
            catch (Exception)
            {
                Debugger.Break();
            }
        }
        public void PlaceOrder_WhenAtLeastOneProductIsAdded_IsSuccessful()
        {
            // Arrange
            Customer customer = CustomerFactory.Create();

            List <OrderProductData> orderProductsData = new List <OrderProductData>();

            orderProductsData.Add(new OrderProductData(SampleProducts.Product1Id, 2));

            List <ProductPriceData> allProductPrices = new List <ProductPriceData>
            {
                SampleProductPrices.Product1EUR, SampleProductPrices.Product1USD
            };

            const string          currency        = "EUR";
            List <ConversionRate> conversionRates = GetConversionRates();

            // Act
            customer.PlaceOrder(
                orderProductsData,
                allProductPrices,
                currency,
                conversionRates);

            // Assert
            OrderPlacedEvent orderPlaced = AssertPublishedDomainEvent <OrderPlacedEvent>(customer);

            Assert.That(orderPlaced.Value, Is.EqualTo(MoneyValue.Of(200, "EUR")));
        }
Ejemplo n.º 6
0
        public async Task <Order> SaveOrder(Order order)
        {
            if (string.IsNullOrEmpty(order.Id))
            {
                await _orderRepository.Add(order);

                var message = new OrderPlacedEvent()
                {
                    Name       = order.Name,
                    OrderId    = order.Id,
                    OrderItems = order.OrderItems
                                 .Select(i => new OrderPlacedItem()
                    {
                        MenuItemId   = i.Id.ToString(),
                        MenuItemName = i.MenuOption.Name,
                        Quantity     = i.Quantity
                    })
                                 .ToArray()
                };
                await _serviceBus.PublishAsync(message);
            }
            else
            {
                await _orderRepository.Update(order);
            }

            return(order);
        }
Ejemplo n.º 7
0
        public async Task No_discount_is_applied()
        {
            var saga = new OrderDiscountPolicy()
            {
                Data = new OrderDiscountPolicy.OrderDiscountData()
                {
                    CustomerId = 123
                }
            };
            var context = new TestableMessageHandlerContext();

            var orderPlaced = new OrderPlacedEvent()
            {
                CustomerId       = 123,
                OrderId          = 789,
                OrderTotalAmount = 100
            };

            await saga.Handle(orderPlaced, context);

            var processOrderMessage = context.SentMessages.SingleOrDefault(m => m.Message.GetType() == typeof(ProcessOrder));

            Assert.IsNotNull(processOrderMessage);
            Assert.AreEqual(0, processOrderMessage.Message <ProcessOrder>().Discount);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Handle order placed event
 /// </summary>
 /// <param name="eventMessage">Event message</param>
 public async Task HandleEventAsync(OrderPlacedEvent eventMessage)
 {
     if (eventMessage?.Order != null)
     {
         await _facebookPixelService.PreparePurchaseScriptAsync(eventMessage.Order);
     }
 }
Ejemplo n.º 9
0
        public async Task <Document> SaveOrder(Order order)
        {
            if (String.IsNullOrEmpty(order.Id))
            {
                var result = await this.repo.CreateItemAsync(order);

                var message = new OrderPlacedEvent()
                {
                    Name       = order.Name,
                    OrderId    = order.Id,
                    OrderItems = order.OrderItems
                                 .Select(i => new OrderPlacedItem()
                    {
                        MenuItemId   = i.MenuOption.Id,
                        MenuItemName = i.MenuOption.Name,
                        Quantity     = i.Quantity
                    })
                                 .ToArray()
                };
                await serviceBus.PublishAsync(message);

                return(result);
            }

            return(await this.repo.UpdateItemAsync(order.Id, order));
        }
Ejemplo n.º 10
0
 public void Handle(OrderPlacedEvent orderPlacedEvent)
 {
     OrderStatisticsModule.OrderReceived();
     OrderStatisticsModule.AddItemCount(orderPlacedEvent
                                        .Lines
                                        .ToDictionary(x => x.ItemId, x => x.Quantity));
     OrderStatisticsModule.LogState();
 }
Ejemplo n.º 11
0
 private void Apply(OrderPlacedEvent e, bool isNew)
 {
     AddEvent(e, isNew);
     this.Description = e.Description;
     this.OrderNumber = e.OrderNumber;
     this.Status      = State.Active;
     this.Lines       = e.Lines.Select(ToDomainLine).ToList();
 }
Ejemplo n.º 12
0
        public void HandleOrderPlacedEvent(OrderPlacedEvent orderPlacedEvent)
        {
            // Do something to handle event here

            Console.WriteLine($"Address: {orderPlacedEvent.DeliveryAddress}");
            Console.WriteLine($"Total price: {orderPlacedEvent.TotalPrice}");
            Console.WriteLine("Products:");
            orderPlacedEvent.Products.ForEach(productName => Console.WriteLine(productName));
        }
Ejemplo n.º 13
0
 private void Handle(OrderPlacedEvent evnt)
 {
     _total                     = evnt.OrderTotal;
     _status                    = OrderStatus.Placed;
     _userId                    = evnt.UserId;
     _registrantId              = evnt.UserId;
     _payInfo                   = new PayInfo(0, 0);
     _expressAddressInfo        = evnt.ExpressAddressInfo;
     _reservationExpirationDate = evnt.ReservationExpirationDate;
 }
Ejemplo n.º 14
0
 private void Handle(OrderPlacedEvent evnt)
 {
     _id                        = evnt.AggregateRootId;
     _total                     = evnt.OrderTotal;
     _status                    = OrderStatus.Placed;
     _userId                    = evnt.UserId;
     _registrantId              = evnt.UserId;
     _expressAddressInfo        = evnt.ExpressAddressInfo;
     _reservationExpirationDate = evnt.ReservationExpirationDate;
 }
Ejemplo n.º 15
0
        public async Task Handle(OrderPlacedEvent message)
        {
            logger.LogInformation($"Shipping received OrderPlacedEvent, OrderId = {message.OrderId}");

            //Simulate processing time
            Thread.Sleep(rnd.Next(0, 2000));

            Data.OrderId     = message.OrderId;
            Data.OrderPlaced = true;
            await Task.CompletedTask;
        }
Ejemplo n.º 16
0
        public void OrderPlaced(OrderPlacedEvent args)
        {
            foreach (var orderItem in args.Items)
            {
                var item = _inventory.Single(x => x.Value.GetType() == orderItem.GetType());
                _inventory.Remove(item);
                _inventory.Add(new KeyValuePair <int, Dish>(item.Key - 1, item.Value));

                EventManager.Raise(new ItemMovedToKitchenEvent(item.Value));
            }
        }
Ejemplo n.º 17
0
        async void PlaceOrders()
        {
            while (running)
            {
                OrderEventArgs nextOrder = CreateNewOrder();
                //Console.WriteLine("Placing order: " + nextOrder.Order.Item.Name);
                OrderPlacedEvent?.Invoke(this, nextOrder);

                double delay = ExpCdfInv(Rng.NextDouble(), lambda);
                //Console.WriteLine("\tDelay: " + delay);
                await Task.Delay(Convert.ToInt32(delay * 1000)).ConfigureAwait(false);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task HandleEventAsync(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order is null)
            {
                return;
            }

            if (!await _shippingPluginManager.IsPluginActiveAsync(EasyPostDefaults.SystemName))
            {
                return;
            }

            await _easyPostService.SaveShipmentAsync(eventMessage.Order);
        }
        public static OrderPlacedEvent ToOrderPlacedEvent(
            this Order order,
            int quantityBeforeReduction)
        {
            var result = new OrderPlacedEvent
            {
                Id       = order.Id,
                Name     = order.Name,
                Quantity = order.Quantity,
                QuantityBeforeReduction = quantityBeforeReduction
            };

            return(result);
        }
Ejemplo n.º 20
0
        public Task Handle(PlaceOrderCommand message, IMessageHandlerContext context)
        {
            logger.Info($"Received PlaceOrderCommand, OrderId = { message.OrderId }");
            // Task.CompletedTask requires .NET 4.6.1

            // This is normally where some business logic would occur

            var orderPlaced = new OrderPlacedEvent
            {
                OrderId = message.OrderId
            };

            return(context.Publish(orderPlaced));
        }
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order == null)
            {
                return;
            }

            //ensure that Avalara tax provider is active
            if (_taxService.LoadActiveTaxProvider(eventMessage.Order.Customer) is AvalaraTaxProvider taxProvider)
            {
                //create tax transaction
                taxProvider.CreateOrderTaxTransaction(eventMessage.Order, true);
            }
        }
Ejemplo n.º 22
0
        protected override Task <OrderPlacedEvent> GetNextOrderPlacedEventAsync(CancellationToken cancellationToken)
        {
            var filePath = Directory.GetFiles(OrderQueueDirectory).FirstOrDefault();

            if (string.IsNullOrEmpty(filePath))
            {
                return(Task.FromResult <OrderPlacedEvent>(null));
            }

            OrderPlacedEvent @event = JsonConvert.DeserializeObject <OrderPlacedEvent>(File.ReadAllText(filePath));

            File.Delete(filePath);

            return(Task.FromResult(@event));
        }
Ejemplo n.º 23
0
        // Public operations
        public Order(
            Guid orderNumber,
            string description,
            List <OrderLine> lines)
        {
            var e = new OrderPlacedEvent()
            {
                OrderNumber = orderNumber,
                Description = description,
                Version     = 0,
                Lines       = lines.Select(ToEventLine).ToList()
            };

            this.Apply(e, true);
        }
Ejemplo n.º 24
0
        public Task Handle(PlaceOrderCommand message, IMessageHandlerContext context)
        {
            log.Info($"Received PlaceOrder, OrderId = {message.OrderId}, OrderData = {message.OrderData}");
            //throw new Exception("BOOM");
            if (random.Next(0, 5) == 0)
            {
                //throw new Exception("Oops");
            }
            var orderPlacedEvent = new OrderPlacedEvent
            {
                OrderId = message.OrderId
            };

            return(context.Publish(orderPlacedEvent));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order == null)
            {
                return;
            }

            //ensure that Avalara tax provider is active
            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName))
            {
                return;
            }

            //create tax transaction
            _avalaraTaxManager.CreateOrderTaxTransaction(eventMessage.Order);
        }
Ejemplo n.º 26
0
        public async Task PostAsync([FromBody] CustomerOrderModel order)
        {
            _log.LogInformation("Order received for {description}", order.Description);

            // Save order to database generating OrderId
            var orderId = new Random().Next(1, 100);

            var message = new OrderPlacedEvent
            {
                OrderId     = orderId,
                Description = order.Description
            };

            await _publisher.PublishAsync(message);

            _log.LogInformation("Order {orderId} placed", orderId);
        }
Ejemplo n.º 27
0
        public async Task PlaceOrder(string deliveryAddress, decimal totalPrice, List <string> products)
        {
            // Do something to place the order here

            var orderPlacedEvent = new OrderPlacedEvent
            {
                DeliveryAddress = deliveryAddress,
                TotalPrice      = totalPrice,
                Products        = products
            };

            Console.WriteLine("Publishing order.placed event");

            await _eventPublisher.SendEventAsync(orderPlacedEvent, "order.placed");

            Console.WriteLine("Done publishing order.placed event");
        }
Ejemplo n.º 28
0
        public void event_should_be_send_to_consumer()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var orderPlacedEvent = new OrderPlacedEvent {
                OrderId = 1
            };

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            The <IMessageBus>().Publish(orderPlacedEvent);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
        }
Ejemplo n.º 29
0
        public PerformanceTests()
        {
            _model = TypeModel.Create();
            _model.Add(typeof(Event), true);
            _stream = new MemoryStream();

            for (var i = 0; i < 1000 * 1000; i++)
            {
                var id = Guid.NewGuid();
                var item = new OrderPlacedEvent(id,
                    "Ordered by customer number" + i.ToString(CultureInfo.InvariantCulture),
                    new[] { new OrderItem("Test product", i) });
                var shipment = new OrderShippedEvent(id, DateTime.Now);

                _model.SerializeWithLengthPrefix(_stream, item, typeof(Event), Prefix, 0);
                _model.SerializeWithLengthPrefix(_stream, shipment, typeof(Event), Prefix, 0);
            }
        }
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order == null)
            {
                return;
            }

            //ensure that Avalara tax provider is active
            var customer = _customerService.GetCustomerById(eventMessage.Order.CustomerId);

            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName, customer, eventMessage.Order.StoreId))
            {
                return;
            }

            //create tax transaction
            _avalaraTaxManager.CreateOrderTaxTransaction(eventMessage.Order);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Handle order placed event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task HandleEventAsync(OrderPlacedEvent eventMessage)
        {
            if (eventMessage.Order == null)
            {
                return;
            }

            //ensure that Avalara tax provider is active for the passed customer, since it's the event from the public area
            var customer = await _customerService.GetCustomerByIdAsync(eventMessage.Order.CustomerId);

            if (!await _taxPluginManager.IsPluginActiveAsync(AvalaraTaxDefaults.SystemName, customer))
            {
                return;
            }

            //create tax transaction
            await _avalaraTaxManager.CreateOrderTaxTransactionAsync(eventMessage.Order);
        }