Beispiel #1
0
        public async Task <OperationResult <SaleOrderDto> > CreateSaleAsync(CreateSaleInput input)
        {
            var validationResult = await _saleValidator.CreateSaleAsync(input);

            if (validationResult.IsSuccess)
            {
                IEnumerable <Product> products = _productRepository.GetAvailableProducts(input.Products.Select(x => x.ProductId));

                Customer customer = await _customerRepository.GetCustomer(input.CustomerEmail);

                AddressCustomer addressCustomer = await _addressRepository.GetByCustomerAsync(input.CustomerEmail);

                Address address = addressCustomer.Addresses.Single(x => x.Id == input.AddressId);

                CouponCode couponCode = null;

                if (!string.IsNullOrWhiteSpace(input.CouponCode))
                {
                    couponCode = await _couponCodeRepository.GetCouponAsync(input.CouponCode);
                }

                Order order = new()
                {
                    Status        = OrderStatus.Created,
                    CreationDate  = DateTime.Now,
                    CustomerEmail = input.CustomerEmail,
                    Type          = OrderType.ProductSale,
                    TotalAmount   = CalculateTotalAmount(couponCode, products, customer)
                };

                order = await _orderRepository.CreateAsync(order);

                Sale sale = new()
                {
                    CouponCode = input.CouponCode,
                    OrderId    = order.Id,
                    Products   = products.Select(x => x.Id),
                    Status     = SaleStatus.PendingPayment
                };

                sale = await _saleRepository.CreateAsync(sale);

                SaleDetail saleDetail = new()
                {
                    SaleId   = sale.Id,
                    Products = input.Products
                };

                saleDetail = await _saleDetailRepository.CreateAsync(saleDetail);

                IPaymentProvider paymentProvider = _paymentProviderFactory.CreatePaymentProvider(input.PaymentProvider);

                Invoice invoice = await paymentProvider.CreateInvoice(order);

                invoice = await _invoiceRepository.CreateAsync(invoice);

                Delivery delivery = new()
                {
                    AddressId = input.AddressId,
                    OrderId   = order.Id,
                    Status    = DeliveryStatus.Created
                };

                delivery = await _deliveryRepository.CreateAsync(delivery);

                return(OperationResult <SaleOrderDto> .Success(new(sale.ConvertToDto(), order.ConvertToDto(), invoice.ConvertToDto())));
            }

            return(OperationResult <SaleOrderDto> .Fail(validationResult));
        }

        private static decimal CalculateTotalAmount(CouponCode couponCode, IEnumerable <Product> products, Customer customer)
        {
            decimal totalAmount = products.Sum(x => x.Price);

            if (couponCode is null)
            {
                return(totalAmount);
            }

            if (totalAmount < couponCode.MinAmount || totalAmount > couponCode.MaxAmount)
            {
                return(totalAmount);
            }

            if (DateTime.Today < couponCode.DateStart || DateTime.Today > couponCode.DateExpire)
            {
                return(totalAmount);
            }

            List <Product> productsToOff = new();


            if (couponCode.Customers?.Contains(customer.Email) ?? false)
            {
                productsToOff.AddRange(products);
            }
            else
            {
                if (couponCode.Categories?.Any() ?? false)
                {
                    productsToOff.AddRange(products.Where(x => couponCode.Categories.Contains(x.Category)));
                }

                if (couponCode.SubCategories?.Any() ?? false)
                {
                    productsToOff.AddRange(products.Where(x => couponCode.SubCategories.Any(y => y.Category == x.Category && y.SubCategory == x.SubCategory)));
                }

                if (couponCode.Products?.Any() ?? false)
                {
                    productsToOff.AddRange(products.Where(x => couponCode.Products.Contains(x.Id)));
                }
            }

            decimal valueOff = couponCode.Type switch
            {
                CouponCodeOffType.Percentage => (couponCode.Value / productsToOff.Sum(x => x.Price)) * 100,
                CouponCodeOffType.SpecificAmount => productsToOff.Sum(x => x.Price) - couponCode.Value,
                _ => throw new ArgumentException("CouponCodeOffType invalido.", nameof(couponCode))
            };


            return(totalAmount - valueOff);
        }
    }
}
Beispiel #2
0
        public async Task <ValidationResult> CreateSaleAsync(CreateSaleInput input)
        {
            ValidationResult validationResult = new();

            if (!Enum.IsDefined(input.PaymentProvider))
            {
                validationResult.Messages.Add(new(nameof(CreateSaleInput.PaymentProvider), "El proveedor de pago no es valido."));
            }

            if (string.IsNullOrWhiteSpace(input.CustomerEmail))
            {
                validationResult.Messages.Add(new(nameof(CreateSaleInput.CustomerEmail), "Debe indicar un cliente."));
            }
            else
            {
                Customer customer = await _customerRepository.GetCustomer(input.CustomerEmail);

                if (customer is null)
                {
                    validationResult.Messages.Add(new(nameof(CreateSaleInput.CustomerEmail), "No existe el cliente."));
                }
                else
                {
                    AddressCustomer addressCustomer = await _addressRepository.GetByCustomerAsync(input.CustomerEmail);

                    Address address = addressCustomer.Addresses?.SingleOrDefault(x => x.Id == input.AddressId);

                    if (address is null)
                    {
                        validationResult.Messages.Add(new(nameof(CreateSaleInput.AddressId), "La dirección no existe."));
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(input.CouponCode))
            {
                CouponCode couponCode = await _couponCodeRepository.GetCouponAsync(input.CouponCode);

                if (couponCode is null)
                {
                    validationResult.Messages.Add(new(nameof(CreateSaleInput.CouponCode), "El código de cupón no existe."));
                }
            }

            if (input.Products is null)
            {
                validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), "Debe seleccionar productos."));
            }
            else
            {
                foreach (ProductDefinitive productDefinitive in input.Products)
                {
                    Product product = await _productRepository.GetAsync(productDefinitive.ProductId);

                    if (product is null)
                    {
                        validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), $"El producto con Id {productDefinitive.ProductId} no existe."));
                    }
                    else if (!product.IsActive)
                    {
                        validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), $"El producto {product.Name} no esta activo."));
                    }
                    else if (product.Stock <= 0)
                    {
                        validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), $"El producto {product.Name} no tiene stock."));
                    }
                    else
                    {
                        if (productDefinitive.Variants is not null)
                        {
                            IEnumerable <ProductVariant> variants = await _productVariantRepository.GetByProduct(product);

                            if (variants is not null)
                            {
                                foreach (ProductVariantPair variantPair in productDefinitive.Variants)
                                {
                                    ProductVariant productVariant = variants.SingleOrDefault(x => x.Name == variantPair.Name);

                                    if (productVariant is null)
                                    {
                                        validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), $"El producto {product.Name} no tiene variaciones de {variantPair.Name}."));
                                    }
                                    else if (!productVariant.Values.Contains(variantPair.Value))
                                    {
                                        validationResult.Messages.Add(new(nameof(CreateSaleInput.Products), $"El producto {product.Name} no tiene una variación de {variantPair.Name} con el valor {variantPair.Value}."));
                                    }
                                }
                            }
                        }
                    }
                }
            }



            return(validationResult);
        }
Beispiel #3
0
        public async Task <IActionResult> Create(CreateSaleInput input)
        {
            var result = await _saleService.CreateSaleAsync(input);

            return(new OperationActionResult(result));
        }