public async Task Execute(ReopenOrderCommand command)
        {
            OrderAggregate aggregate = await Retrieve(command.EntityId);

            aggregate.Reopen(command.NewCount);
            await session.Commit(command.EntityId);
        }
        public async Task Execute(SetOrderResponsibleCommand command)
        {
            OrderAggregate aggregate = await Retrieve(command.EntityId);

            aggregate.SetResponsible(command.ResponsibleId);
            await session.Commit(command.EntityId);
        }
Beispiel #3
0
        public static Order ToModel(this OrderAggregate order)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var orderParcel  = order.OrderParcel == null ? null : order.OrderParcel.ToModel();
            var orderPayment = order.OrderPayment == null ? null : order.OrderPayment.ToModel();

            return(new Order
            {
                Id = order.Id,
                CreateDateTime = order.CreateDateTime,
                IsLabelPurchased = order.IsLabelPurchased,
                Status = (int)order.Status,
                TransportMode = (int)order.TransportMode,
                Subject = order.Subject,
                TotalPrice = order.TotalPrice,
                UpdateDateTime = order.UpdateDateTime,
                ShopId = order.ShopId,
                ShippingPrice = order.ShippingPrice,
                OrderLines = order.OrderLines == null ? new List <OrderLine>() : order.OrderLines.Select(o => o.ToModel()).ToList(),
                OrderParcel = orderParcel,
                OrderPayment = orderPayment,
                TrackingNumber = order.TrackingNumber,
                ShipmentDigest = order.ShipmentDigest
            });
        }
        public async Task Execute(OpenOrderCommand command)
        {
            OrderAggregate aggregate = new OrderAggregate(command.EntityId, command.Position, command.Count);
            await session.Add(aggregate);

            await session.Commit(command.EntityId);
        }
        public void Test_Order_AcceptProducesProductReserveEvents()
        {
            var tx = new OrderRequest
            {
                UserID    = Guid.NewGuid().ToString(),
                CreatedOn = (ulong)DateTime.UtcNow.Ticks,
                TaxRate   = 5
            };

            tx.LineItems.Add(new LineItem {
                SKU = "ABC123", UnitPrice = 12, Quantity = 1
            });
            tx.LineItems.Add(new LineItem {
                SKU = "SOAP12", UnitPrice = 200, Quantity = 5
            });

            var oa = new OrderAggregate("order-2-1");

            var productAggregates = FakeAggs();

            var evts = oa.Accept(tx, productAggregates);

            Assert.Equal(3, evts.Count);
            Assert.IsType <OrderAcceptedEvent>(evts[0]);
            Assert.IsType <InventoryReservedEvent>(evts[1]);
            Assert.IsType <InventoryReservedEvent>(evts[2]);
            var evt = (InventoryReservedEvent)evts[2];

            Assert.Equal <uint>(5, evt.Quantity);
        }
        public async Task Enrich(IHalResponseBuilder halResponseBuilder, OrderAggregate order)
        {
            if (halResponseBuilder == null)
            {
                throw new ArgumentNullException(nameof(halResponseBuilder));
            }

            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            if (order.Status == OrderAggregateStatus.Created)
            {
                await _orderPriceCalculatorHelper.Update(order);
            }

            halResponseBuilder.AddEmbedded(e => e.AddObject(_responseBuilder.GetOrder(order),
                                                            (l) =>
            {
                l.AddOtherItem("shop", new Dtos.Link("/" + Constants.RouteNames.Shops + "/" + order.ShopId));
                l.AddOtherItem("user", new Dtos.Link("/" + Constants.RouteNames.Users + "/" + order.Subject));
                l.AddSelf(Constants.RouteNames.Orders + "/" + order.Id);
            }));
        }
 public ConfirmOrderLabelPurchaseValidationResult(OrderAggregate order, UserResult payer, UserResult seller)
 {
     Order   = order;
     Payer   = payer;
     Seller  = seller;
     IsValid = true;
 }
        private Dictionary <Guid, List <IEvent> > AddOrderLines(OrderAggregate orderAggregate, IEnumerable <OrderLineDto> orderLines)
        {
            IEnumerable <WarehouseView> warehouses = repository.Query <WarehouseView, WarehouseView>((w) => new WarehouseView {
                Id = w.Id, Items = w.Items
            });
            var events = new Dictionary <Guid, List <IEvent> >();

            foreach (OrderLineDto orderLine in orderLines)
            {
                WarehouseView warehouse = warehouses.FirstOrDefault(w => w.Items.Any(item => item.ProductId == orderLine.ProductNumber && item.Quantity >= orderLine.Quantity));

                var orderItem = new OrderLine
                {
                    ProductId = orderLine.ProductNumber,
                    Quantity  = orderLine.Quantity
                };

                if (warehouse != null)
                {
                    WarehouseAggregate warehouseAggregate = repository.Load <WarehouseAggregate>(warehouse.Id);
                    warehouseAggregate.SubstractItemQuantity(orderLine.ProductNumber, orderLine.Quantity);
                    AddAggEvents(events, warehouseAggregate.Id, warehouseAggregate.PendingEvents.ToList());
                    orderItem.WarehouseId = warehouseAggregate.Id;
                }
                else
                {
                    orderItem.Status = OrderLineStatus.OutOfStock.ToString();
                }

                orderAggregate.AddLine(orderItem);

                AddAggEvents(events, orderAggregate.Id, orderAggregate.PendingEvents.ToList());
            }
            return(events);
        }
        public async Task <bool> Insert(OrderAggregate orderAggregate)
        {
            if (orderAggregate == null)
            {
                throw new ArgumentNullException(nameof(orderAggregate));
            }

            using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                try
                {
                    var record = orderAggregate.ToModel();
                    _context.Orders.Add(record);
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                    return(true);
                }
                catch
                {
                    transaction.Rollback();
                    return(false);
                }
            }
        }
        public async Task <bool> Remove(OrderAggregate orderAggregate)
        {
            if (orderAggregate == null)
            {
                throw new ArgumentNullException(nameof(orderAggregate));
            }

            using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                var record = await _context.Orders.FirstOrDefaultAsync(s => s.Id == orderAggregate.Id);

                if (record == null)
                {
                    transaction.Rollback();
                    return(false);
                }

                try
                {
                    _context.Orders.Remove(record);
                    await _context.SaveChangesAsync();

                    transaction.Commit();
                    return(true);
                }
                catch
                {
                    transaction.Rollback();
                    return(false);
                }
            }
        }
        public async Task Execute(CloseOrderCommand command)
        {
            OrderAggregate aggregate = await Retrieve(command.EntityId);

            aggregate.Close();
            await session.Commit(command.EntityId);
        }
Beispiel #12
0
        public override Task <OrderResponse> SubmitOrder(OrderRequest request, grpc::ServerCallContext context)
        {
            logger.LogInformation("Handling Order Request Submission");
            var response = new OrderResponse();

            if (!isValidRequest(request))
            {
                response.Accepted = false;
                return(Task.FromResult(response));
            }

            try
            {
                var agg = new OrderAggregate(Guid.NewGuid().ToString());
                var productAggregates = GetProductAggregates(request.LineItems.ToArray());
                var evts = agg.Accept(request, productAggregates);
                foreach (var evt in evts)
                {
                    this.eventEmitter.Emit(evt);
                }
                response.Accepted = true;
                response.OrderID  = agg.OrderID;
                return(Task.FromResult(response));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to submit order");
                response.Accepted = false;
                return(Task.FromResult(response));
            }
        }
Beispiel #13
0
        protected OrderAggregate CreateNewOrder()
        {
            DateTimeUtil.MockNow(createdOn);
            var sut = new OrderAggregate();

            sut.Create(orderId, customerId, senderId);
            return(sut);
        }
 public async Task Handle(CreateOrderCommand command)
 {
     var aggregateId = new OrderAggregateId();
     var order       = new OrderAggregate(aggregateId, command.customerId, command.orderDate, command.orderStatus);
     IDomainEventPublisher <OrderAggregateId>            publisher = new InMemoryDomainEventPublisher <OrderAggregateId>();
     IWriteRepository <OrderAggregate, OrderAggregateId> repo      = new InMemoryWriteRepository <OrderAggregate, OrderAggregateId>(publisher);
     await repo.SaveAsync(order);
 }
Beispiel #15
0
            public void Handle(DeleteOrderCommand instance)
            {
                OrderAggregate orderAggregate = _unitOfWork
                                                .GetRepository <OrderAggregate>()
                                                .GetById(instance.EntityId);

                orderAggregate.Delete();
                _unitOfWork.GetRepository <OrderAggregate>().Add(orderAggregate);
            }
 public PurchaseOrderLabelValidationResult(OrderAggregate order, string payerPaypalEmail, string sellerPaypalEmail, double shippingPrice, string shipmentDigest)
 {
     Order             = order;
     PayerPaypalEmail  = payerPaypalEmail;
     SellerPaypalEmail = sellerPaypalEmail;
     ShippingPrice     = shippingPrice;
     IsValid           = true;
     ShipmentDigest    = shipmentDigest;
 }
 public UpdateOrderValidationResult(OrderAggregate order, IEnumerable <ProductAggregate> products, string payerPaypalEmail, string sellerPaypalEmail, double shippingPrice)
 {
     Order             = order;
     Products          = products;
     PayerPaypalEmail  = payerPaypalEmail;
     SellerPaypalEmail = sellerPaypalEmail;
     ShippingPrice     = shippingPrice;
     IsValid           = true;
 }
Beispiel #18
0
            public void Handle(ChangeOrderDateCommand instance)
            {
                OrderAggregate orderAggregate = _unitOfWork
                                                .GetRepository <OrderAggregate>()
                                                .GetById(instance.EntityId);

                orderAggregate.ChangeDate(instance.Date);
                _unitOfWork.GetRepository <OrderAggregate>().Add(orderAggregate);
            }
        public async Task Handle(CreateOrderCommand command)
        {
            var aggregateId = new OrderAggregateId();
            var order       = new OrderAggregate(aggregateId, command.customerId, command.orderDate, command.orderStatus);
            IDomainEventPublisher <OrderAggregateId>            publisher = new InMemoryDomainEventPublisher <OrderAggregateId>();
            IWriteRepository <OrderAggregate, OrderAggregateId> repo      = new InMemoryWriteRepository <OrderAggregate, OrderAggregateId>(publisher);
            await repo.SaveAsync(order);

            // foreach (var pe in InMemoryPersistance.publishedEvents) Helpers.SimpleLogger.Log(pe.ToString());
        }
Beispiel #20
0
 public void Handle(AddOrderLineRequest command)
 {
     using (IUnitOfWork uow = this.CreateUnitOfWork <OrderAggregate>())
     {
         IOrderRepository repository = IoC.Container.Resolve <IOrderRepository>(uow);
         OrderAggregate   order      = repository.GetById(command.OrderId.ToString(), "OrderLines");
         order.AddOrderLineItem(command.ProductId, command.ProductName, command.Quantity, command.Price);
         repository.Update(order);
         uow.Commit();
         order.PublishEvents();
     }
 }
        public void Test_Order_CancelProducesProductReleaseEvents()
        {
            OrderAggregate oa = new OrderAggregate("order-1-1");

            var productAggs = FakeAggs();
            var evts        = oa.Cancel("tester", productAggs);

            Assert.Equal(3, evts.Count);
            Assert.IsType <OrderCanceledEvent>(evts[0]);
            Assert.IsType <InventoryReleasedEvent>(evts[1]);
            Assert.IsType <InventoryReleasedEvent>(evts[2]);
        }
Beispiel #22
0
 public void Handle(ActivateOrder command)
 {
     using (IUnitOfWork uow = this.CreateUnitOfWork <OrderAggregate>())
     {
         IOrderRepository repository = IoC.Container.Resolve <IOrderRepository>(uow);
         OrderAggregate   order      = repository.GetById(command.OrderId.ToString(), "OrderLines");
         order.Activate();
         repository.Update(order);
         uow.Commit();
         order.PublishEvents();
     }
 }
Beispiel #23
0
        protected override async Task Handle(AddOrderCommand request, CancellationToken cancellationToken)
        {
            Log.Information("Order will be saved to the database");
            var order = new OrderAggregate(DateTime.UtcNow, orderItems: request.OrderItems.Select(ToOrderItem).ToList());

            orderRepository.AddOrder(order);
            await orderRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            Log.Information("Order has been saved");

            OrderItem ToOrderItem(AddOrderCommand.AddOrderItemModel source) => new OrderItem(source.Count, source.Description);
        }
Beispiel #24
0
        public void Handle(CreateOrderRequest command)
        {
            OrderAggregate order = AggregateFactory.Create <OrderAggregate>();

            order.AddCustomerDetail(command.CustomerDetail);
            order.AddOrderLineItems(command.OrderLines);
            using (IUnitOfWork uow = this.CreateUnitOfWork <OrderAggregate>())
            {
                IOrderRepository repository = IoC.Container.Resolve <IOrderRepository>(uow);
                repository.Add(order);
                uow.Commit();
                order.AddEvent(new OnOrderCreated(order.Id));
            }
            order.PublishEvents();
        }
Beispiel #25
0
 internal static OrderModel FromAggregate(OrderAggregate agg)
 {
     return(new OrderModel
     {
         Id = agg.AggregateId,
         State = agg.State.ToString(),
         Lines = agg.OrderLines.Select(LineModel.FromAggregate).ToList(),
         ShippingAddress = new AddressModel
         {
             StreetAndNumber = agg.ShippingAddress.StreetAndNumber,
             ZipAndCity = agg.ShippingAddress.ZipAndCity,
             StateOrProvince = agg.ShippingAddress.StateOrProvince,
             Country = agg.ShippingAddress.Country
         }
     });
 }
Beispiel #26
0
        public async Task <OrderAggregate> CreateOrderAsync(string buyerEmail, string basketId)
        {
            // get basket from the repo
            var basket = await _basketRepo.GetBasketAsync(basketId);

            // get items from the product repo
            var items = new List <MenuItem>();

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Menu>().GetByIdAsync(item.Id);

                var itemOrdered = new MenuItemOrdered(productItem.Id, productItem.FoodFirst, productItem.Day, productItem.Month, productItem.Year, item.SchoolName, item.DinnerTime);
                var orderItem   = new MenuItem(itemOrdered, productItem.Price);
                items.Add(orderItem);
            }


            // calc subtotal
            var subtotal = items.Sum(item => item.Price);

            // check to see if order exists
            var spec          = new OrderByPaymentIntentIdSpecification(basket.PaymentIntentId);
            var existingOrder = await _unitOfWork.Repository <OrderAggregate>().GetEntityWithSpec(spec);

            if (existingOrder != null)
            {
                _unitOfWork.Repository <OrderAggregate>().Delete(existingOrder);
                await _paymentService.CreateOrUpdatePaymentIntent(basket.PaymentIntentId);
            }

            // create order
            var order = new OrderAggregate(items, subtotal, buyerEmail, basket.PaymentIntentId);

            _unitOfWork.Repository <OrderAggregate>().Add(order);

            // save to db
            var result = await _unitOfWork.Complete();

            if (result <= 0)
            {
                return(null);
            }

            // return order
            return(order);
        }
Beispiel #27
0
        public void Given_A_Valid_Order_When_The_Order_Is_Received_Then_The_Order_Is_Placed()
        {
            // Arrange
            const int    orderId      = 1234;
            const int    customerId   = 5678;
            OrderDetails orderDetails = new OrderDetails();

            orderDetails.OrderItems.Add(new OrderItem(1, "desc", 9.99m, 2));
            IOrderAggregate orderAggregate = new OrderAggregate(orderId.ToString(CultureInfo.InvariantCulture));

            // Act
            orderAggregate.PlaceOrder(orderId, customerId, orderDetails);

            // Assert
            Assert.Equal(1, orderAggregate.UncommittedEvents.Count);
            Assert.True(orderAggregate.UncommittedEvents.FirstEventIs(typeof(IOrderPlacedV1)));
        }
Beispiel #28
0
        public void should_create_and_save_order_aggregate()
        {
            var customerId       = Guid.NewGuid();
            var senderId         = Guid.NewGuid();
            var agg              = new OrderAggregate();
            var repository       = new Mock <IRepository>();
            var eventsDispatcher = new Mock <IEventDispatcher>();

            repository.Setup(r => r.Get <OrderAggregate>(It.IsAny <Guid>())).Returns(agg);
            var sut = new OrderApplicationService(repository.Object, eventsDispatcher.Object);

            sut.When(new CreateOrder {
                CustomerId = customerId, SenderId = senderId
            });

            repository.Verify(x => x.Save(It.IsAny <OrderAggregate>()), Times.Once);
        }
        private async Task UpdateDiscount(OrderAggregate order, bool addQuantity)
        {
            if (order.OrderLines == null || !order.OrderLines.Any())
            {
                return;
            }

            var orderLines = order.OrderLines.Where(ol => ol.OrderLineDiscount != null);

            if (!orderLines.Any())
            {
                return;
            }

            var discountIds = orderLines.Select(ol => ol.OrderLineDiscount.Id);
            var discounts   = await _discountRepository.Search(new SearchDiscountsParameter
            {
                DiscountIds = discountIds
            });

            var tasks = new List <Task>();

            foreach (var orderLine in orderLines)
            {
                var discount = discounts.Content.FirstOrDefault(d => d.Id == orderLine.OrderLineDiscount.Id);
                if (discount == null || discount.Validity == DiscountAggregateValidities.Timer)
                {
                    continue;
                }

                if (addQuantity)
                {
                    discount.Counter += 1;
                }
                else
                {
                    discount.Counter -= 1;
                }

                tasks.Add(_discountRepository.Update(discount));
            }

            await Task.WhenAll(tasks);
        }
        private async Task UpdateProductStock(OrderAggregate order, bool addQuantity)
        {
            if (order.OrderLines == null || !order.OrderLines.Any())
            {
                return;
            }

            var products = await _productRepository.Search(new SearchProductsParameter
            {
                ProductIds      = order.OrderLines.Select(o => o.ProductId),
                IsPagingEnabled = false
            });

            var tasks = new List <Task>();

            if (products.Content != null)
            {
                foreach (var orderLine in order.OrderLines)
                {
                    var product = products.Content.FirstOrDefault(c => c.Id == orderLine.ProductId);
                    if (product == null)
                    {
                        continue;
                    }

                    if (product.AvailableInStock.HasValue) // Update the available stock.
                    {
                        if (addQuantity)
                        {
                            product.AvailableInStock = product.AvailableInStock + orderLine.Quantity;
                        }
                        else
                        {
                            product.AvailableInStock = product.AvailableInStock - orderLine.Quantity;
                        }

                        tasks.Add(_productRepository.Update(product));
                    }
                }
            }

            await Task.WhenAll(tasks);
        }