Exemple #1
0
        public async Task <RatingServiceSelectionResponse> GetRatings(GetUpsRatingsParameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (parameter.Credentials == null)
            {
                throw new ArgumentNullException(nameof(parameter.Credentials));
            }

            var client   = _httpClientFactory.GetHttpClient();
            var security = new AccessRequestType
            {
                AccessLicenseNumber = parameter.Credentials.LicenseNumber,
                Password            = parameter.Credentials.Password,
                UserId = parameter.Credentials.UserName
            };
            var request = new RatingServiceSelectionRequest
            {
                Request = new RatingServiceSelectionRequestBody
                {
                    RequestAction        = "Rate",
                    RequestOption        = "Rate",
                    TransactionReference = new TransactionReference
                    {
                        CustomerContext = "Your Test Case Summary Description",
                        XpciVersion     = "1.0014"
                    }
                },
                Shipment = new Shipment
                {
                    Service = new TypeParameter
                    {
                        Code = _mappingServices.First(kvp => kvp.Key == parameter.UpsService).Value
                    },
                    ShipmentIndicationType = new TypeParameter
                    {
                        Code        = "02",
                        Description = "UPS Access Point™ Delivery"
                    },
                    Package = new Package
                    {
                        PackagingType = new TypeParameter
                        {
                            Code = "02"
                        }
                    }
                }
            };

            if (parameter.AlternateDeliveryAddress != null)
            {
                request.Shipment.AlternateDeliveryAddress = new AlternateDeliveryAddress
                {
                    Name = parameter.AlternateDeliveryAddress.Name
                };

                if (parameter.AlternateDeliveryAddress.Address != null)
                {
                    request.Shipment.AlternateDeliveryAddress.Address = new Address
                    {
                        AddressLine1 = parameter.AlternateDeliveryAddress.Address.AddressLine,
                        City         = parameter.AlternateDeliveryAddress.Address.City,
                        CountryCode  = parameter.AlternateDeliveryAddress.Address.Country,
                        PostalCode   = parameter.AlternateDeliveryAddress.Address.PostalCode
                    };
                }
            }

            if (parameter.Shipper != null)
            {
                request.Shipment.Shipper = new Shipper
                {
                    Name          = parameter.Shipper.Name,
                    ShipperNumber = parameter.Shipper.ShipperNumber
                };

                if (parameter.Shipper.Address != null)
                {
                    request.Shipment.Shipper.Address = new Address
                    {
                        AddressLine1 = parameter.Shipper.Address.AddressLine,
                        City         = parameter.Shipper.Address.City,
                        CountryCode  = parameter.Shipper.Address.Country,
                        PostalCode   = parameter.Shipper.Address.PostalCode
                    };
                }
            }

            if (parameter.ShipTo != null)
            {
                request.Shipment.ShipTo = new Ship
                {
                    Name = parameter.Shipper.Name,
                };

                if (parameter.ShipTo.Address != null)
                {
                    request.Shipment.ShipTo.Address = new Address
                    {
                        AddressLine1 = parameter.ShipTo.Address.AddressLine,
                        City         = parameter.ShipTo.Address.City,
                        CountryCode  = parameter.ShipTo.Address.Country,
                        PostalCode   = parameter.ShipTo.Address.PostalCode
                    };
                }
            }

            if (parameter.ShipFrom != null)
            {
                request.Shipment.ShipFrom = new Ship
                {
                    Name = parameter.Shipper.Name,
                };

                if (parameter.ShipFrom.Address != null)
                {
                    request.Shipment.ShipFrom.Address = new Address
                    {
                        AddressLine1 = parameter.ShipFrom.Address.AddressLine,
                        City         = parameter.ShipFrom.Address.City,
                        CountryCode  = parameter.ShipFrom.Address.Country,
                        PostalCode   = parameter.ShipFrom.Address.PostalCode
                    };
                }
            }

            if (parameter.Package != null)
            {
                request.Shipment.Package.Dimensions = new Dimensions
                {
                    UnitOfMeasurement = new UnitOfMeasurement
                    {
                        Code        = "CM",
                        Description = "cm"
                    },
                    Length = parameter.Package.Length,
                    Height = parameter.Package.Height,
                    Width  = parameter.Package.Width
                };
                request.Shipment.Package.PackageWeight = new PackageWeight
                {
                    UnitOfMeasurement = new UnitOfMeasurement
                    {
                        Code        = "KGS",
                        Description = "kgs"
                    },
                    Weight = parameter.Package.Weight
                };
            }

            var serializerSecurity = new XmlSerializer(typeof(AccessRequestType));
            var serializerBody     = new XmlSerializer(typeof(RatingServiceSelectionRequest));
            var xmlSecurity        = "";
            var xmlBody            = "";

            using (var sww = new StringWriter())
            {
                using (var writer = XmlWriter.Create(sww))
                {
                    serializerSecurity.Serialize(writer, security);
                    xmlSecurity = sww.ToString();
                }
            }

            using (var sww = new StringWriter())
            {
                using (var writer = XmlWriter.Create(sww))
                {
                    serializerBody.Serialize(writer, request);
                    xmlBody = sww.ToString();
                }
            }

            var xml  = xmlSecurity + "" + xmlBody;
            var body = new StringContent(xml);
            var req  = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                Content    = body,
                RequestUri = new Uri(_rateUrl)
            };
            var serializedContent = await client.SendAsync(req).ConfigureAwait(false);

            var res = await serializedContent.Content.ReadAsStringAsync();

            var deserializer = new XmlSerializer(typeof(RatingServiceSelectionResponse));

            using (TextReader reader = new StringReader(res))
            {
                return((RatingServiceSelectionResponse)deserializer.Deserialize(reader));
            }
        }
        public async Task <UpdateOrderValidationResult> Validate(UpdateOrderCommand order, string subject)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }

            var record = await _orderRepository.Get(order.Id);

            if (record == null)
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderDoesntExist));
            }

            if (record.Status == OrderAggregateStatus.Received) // Cannot update received order.
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheReceivedOrderCannotBeUpdated));
            }

            if (record.Status != OrderAggregateStatus.Created && record.Status == order.Status) // Confirmed & received order cannot be updated.
            {
                return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderCannotBeUpdatedBecauseOfItsState, Enum.GetName(typeof(OrderAggregateStatus), order.Status))));
            }

            if (record.Status != order.Status)
            {
                if (record.Status == OrderAggregateStatus.Created && order.Status != OrderAggregateStatus.Confirmed) // created => confirmed.
                {
                    return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderStateCannotBeUpdated, Enum.GetName(typeof(OrderAggregateStatus), record.Status), Enum.GetName(typeof(OrderAggregateStatus), order))));
                }

                if (record.Status == OrderAggregateStatus.Confirmed && order.Status != OrderAggregateStatus.Received) // confirmed => received
                {
                    return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderStateCannotBeUpdated, Enum.GetName(typeof(OrderAggregateStatus), record.Status), Enum.GetName(typeof(OrderAggregateStatus), order))));
                }
            }

            if (order.TransportMode == OrderTransportModes.Manual && order.Status == OrderAggregateStatus.Received && record.Subject != subject)  // Only the creator can confirm the order.
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderReceptionCanBeConfirmedOnlyByItsCreator));
            }

            IEnumerable <ProductAggregate> prods = null;

            if (order.OrderLines != null && order.OrderLines.Any()) // Check the lines.
            {
                var productIds = order.OrderLines.Select(o => o.ProductId);
                var products   = await _productRepository.Search(new SearchProductsParameter { ProductIds = productIds });

                if (products.Content.Count() != productIds.Count())
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineProductIsInvalid));
                }

                if (order.OrderLines.Any(o => o.Quantity <= 0))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineQuantityIsInvalid));
                }

                foreach (var orderLine in order.OrderLines)
                {
                    var product = products.Content.First(p => p.Id == orderLine.ProductId);
                    if (orderLine.Quantity > product.AvailableInStock && product.AvailableInStock.HasValue)
                    {
                        return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineQuantityIsTooMuch));
                    }
                }

                prods = products.Content;
                var discountCodes = order.OrderLines.Select(o => o.DiscountCode).Where(dc => !string.IsNullOrEmpty(dc));
                if (discountCodes.Any()) // Check discounts.
                {
                    var discounts = await _discountRepository.Search(new SearchDiscountsParameter
                    {
                        IsPagingEnabled = false,
                        DiscountCodes   = discountCodes
                    });

                    if (discounts.Content == null || !discounts.Content.Any() || discounts.Content.Count() != discountCodes.Count())
                    {
                        return(new UpdateOrderValidationResult(ErrorDescriptions.TheDiscountCodesAreNotValid));
                    }

                    foreach (var orderLine in order.OrderLines)
                    {
                        if (string.IsNullOrWhiteSpace(orderLine.DiscountCode))
                        {
                            continue;
                        }

                        var discount = discounts.Content.First(c => c.Code == orderLine.DiscountCode);
                        if (discount.Products == null || !discount.Products.Any(p => p.ProductId == orderLine.ProductId)) // Check discount is valid for the product.
                        {
                            return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheDiscountCannotBeUsedForThisProduct, orderLine.ProductId)));
                        }

                        if (!discount.IsValid()) // Check discount is valid.
                        {
                            return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheProductDiscountIsInvalid, orderLine.DiscountCode)));
                        }

                        orderLine.DiscountId = discount.Id;
                    }
                }
            }

            double shippingPrice = 0;
            string payerEmail    = string.Empty;
            string sellerEmail   = string.Empty;

            if (order.Status == OrderAggregateStatus.Confirmed && order.TransportMode == OrderTransportModes.Packet)
            {
                if (order.OrderParcel == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheParcelDoesntExist));
                }

                var payer = await _openidClient.GetPublicClaims(_settingsProvider.GetBaseOpenidUrl(), subject);

                if (payer == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.ThePayerPaypalAccountNotExist));
                }

                var seller = await _openidClient.GetPublicClaims(_settingsProvider.GetBaseOpenidUrl(), record.SellerId);

                if (seller == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheSellerPaypalAccountNotExist));
                }

                var paypalBuyer  = payer.Claims.FirstOrDefault(c => c.Type == "paypal_email");
                var paypalSeller = seller.Claims.FirstOrDefault(c => c.Type == "paypal_email");
                if (paypalBuyer == null || string.IsNullOrWhiteSpace(paypalBuyer.Value))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.ThePayerPaypalAccountNotExist));
                }

                if (paypalSeller == null || string.IsNullOrWhiteSpace(paypalSeller.Value))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheSellerPaypalAccountNotExist));
                }

                if (order.OrderParcel.Transporter == Transporters.Dhl)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheTransporterDhlIsNotSupported));
                }

                if (order.OrderParcel.Transporter == Transporters.Ups)
                {
                    var buyerName  = payer.Claims.First(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Name).Value;
                    var sellerName = seller.Claims.First(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Name).Value;
                    var parameter  = new GetUpsRatingsParameter
                    {
                        Credentials = new UpsCredentials
                        {
                            LicenseNumber = _settingsProvider.GetUpsLicenseNumber(),
                            Password      = _settingsProvider.GetUpsPassword(),
                            UserName      = _settingsProvider.GetUpsUsername()
                        },
                        Shipper = new UpsShipperParameter
                        {
                            Name    = buyerName,
                            Address = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.BuyerAddressLine,
                                City        = order.OrderParcel.BuyerCity,
                                Country     = order.OrderParcel.BuyerCountryCode,
                                PostalCode  = order.OrderParcel.BuyerPostalCode.ToString()
                            }
                        },
                        ShipFrom = new UpsShipParameter
                        {
                            Name          = buyerName,
                            AttentionName = buyerName,
                            CompanyName   = buyerName,
                            Address       = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.BuyerAddressLine,
                                City        = order.OrderParcel.BuyerCity,
                                Country     = order.OrderParcel.BuyerCountryCode,
                                PostalCode  = order.OrderParcel.BuyerPostalCode.ToString()
                            }
                        },
                        ShipTo = new UpsShipParameter
                        {
                            Name          = sellerName,
                            AttentionName = sellerName,
                            CompanyName   = sellerName,
                            Address       = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.SellerAddressLine,
                                City        = order.OrderParcel.SellerCity,
                                Country     = order.OrderParcel.SellerCountryCode,
                                PostalCode  = order.OrderParcel.SellerPostalCode.ToString()
                            }
                        },
                        Package = new UpsPackageParameter
                        {
                            Height = Constants.PackageInfo.Height,
                            Length = Constants.PackageInfo.Length,
                            Weight = Constants.PackageInfo.Weight,
                            Width  = Constants.PackageInfo.Width
                        },
                        AlternateDeliveryAddress = new UpsAlternateDeliveryAddressParameter
                        {
                            Name    = order.OrderParcel.ParcelShopName,
                            Address = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.ParcelShopAddressLine,
                                City        = order.OrderParcel.ParcelShopCity,
                                Country     = order.OrderParcel.ParcelShopCountryCode,
                                PostalCode  = order.OrderParcel.ParcelShopPostalCode.ToString()
                            }
                        },
                        UpsService = CommonBuilder.MappingBothUpsServices.First(kvp => kvp.Key == order.OrderParcel.UpsServiceCode).Value
                    };
                    var ratingsResponse = await _upsClient.GetRatings(parameter);

                    if (ratingsResponse.Response.Error != null)
                    {
                        return(new UpdateOrderValidationResult(ratingsResponse.Response.Error.ErrorDescription));
                    }

                    shippingPrice = ratingsResponse.RatedShipment.TotalCharges.MonetaryValue;
                    payerEmail    = paypalBuyer.Value;
                    sellerEmail   = paypalSeller.Value;
                }
            }

            return(new UpdateOrderValidationResult(record, prods, payerEmail, sellerEmail, shippingPrice));
        }