Ejemplo n.º 1
0
        public async Task CreateAsync(PurchaseMessage message)
        {
            var numbersDropped = new List <DropCopyNumberMessage>();

            var order = await _db.Orders
                        .Include(x => x.Items)
                        .ThenInclude(x => x.Book)
                        .Include(x => x.Customer)
                        .FirstOrDefaultAsync(x => x.Number == message.Number);

            if (order == null)
            {
                order = new Order
                {
                    Number     = message.Number,
                    Status     = StatusOrder.Opened,
                    CreateDate = DateTime.UtcNow,
                    Customer   = await _db.Customers.FirstOrDefaultAsync(x => x.DocumentId == message.CustomerId)
                };

                if (order.Customer == null)
                {
                    order.Customer = new Customer
                    {
                        DocumentId = message.CustomerId,
                        Name       = message.CustomerName
                    };
                }

                order.Items = new List <OrderItem>();

                foreach (var item in message.Items)
                {
                    var orderItem = await GetItemAsync(_db, item);

                    if (IntegrationWithLibrary.Get())
                    {
                        numbersDropped.Add(new DropCopyNumberMessage()
                        {
                            Number = item.Number
                        });
                    }

                    order.Items.Add(orderItem);
                }

                await _db.AddAsync(order);
            }
            else
            {
                order.Items = new List <OrderItem>();

                foreach (var item in message.Items)
                {
                    var orderItem = await GetItemAsync(_db, item);

                    if (IntegrationWithLibrary.Get())
                    {
                        numbersDropped.Add(new DropCopyNumberMessage()
                        {
                            Number = item.Number
                        });
                    }

                    order.Items.Add(orderItem);
                }

                _db.Update(order);
            }

            await _db.SaveChangesAsync();

            if (IntegrationWithLibrary.Get())
            {
                await _bus.PublishAllAsync(QueueNames.Library, numbersDropped);
            }

            var dto = new ShippingDtoMessage
            {
                OrderId = order.Id
            };

            await _bus.PublishAsync(QueueNames.Bookstore, dto);
        }