예제 #1
0
        public async Task <Result> AddAsync(SaleAddClientModel dto)
        {
            var result = new Result();
            // customer
            var existCustomer = await GetCustomer(dto);

            // sale-person
            var existPerson = await GetSalePerson(dto);

            var newSale = await GetExistSaleAsync(dto, existCustomer.Id, existPerson.Id);

            if (newSale == null)
            {
                // sale
                newSale              = dto.Create();
                newSale.CustomerId   = existCustomer.Id;
                newSale.SalePersonId = existPerson.Id;
                var createSale = await _saleRepository.AddAsync(newSale);

                await _saleRepository.CompleteAsync();

                // sale event
                var sale_added_event = AbstractDomainEvent <SaleAddClientModel> .Create(_serviceProvider);

                await sale_added_event.RaiseAsync(createSale);

                // order
                var order = new Order()
                {
                    SaleId = createSale.Id
                };
                var createdOrder = await _orderRepository.AddAsync(order);

                await _orderRepository.CompleteAsync();

                //sale event
                var orderAddedEvent = AbstractDomainEvent <OrderAddClientModel> .Create(_serviceProvider);

                await orderAddedEvent.RaiseAsync(createdOrder);

                // product
                dto.ProductIds.ForEach(p =>
                {
                    var existProducts = _productRepository.Find(x => x.ProductId == p);
                    var existProduct  = existProducts.FirstOrDefault();
                    if (existProduct == null)
                    {
                        _productRepository.Add(dto.Product(p));
                    }
                    // order-product
                    var orderProduct       = dto.CreateOrderProduct(createdOrder.Id, existProduct.Id);
                    var createOrderProduct = _orderProductRepository.Add(orderProduct);
                });

                await _productRepository.CompleteAsync();

                await _orderProductRepository.CompleteAsync();

                result.Value = newSale.ToString();
            }
            else
            {
                result.IsError   = true;
                result.Message   = "Sale does exist";
                result.StatuCode = 400;
            }

            return(result);
        }