Beispiel #1
0
        protected void btnEstimateShipping_Click(object sender, EventArgs e)
        {
            ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(StoreContext.CurrentStore.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

            IPostalAddress origin      = StoreContext.CurrentStore.Address.ToPostalAddress();
            IPostalAddress destination = new PostalAddress()
            {
                PostalCode = txtShippingEstimateZip.Text.Trim(), IsResidential = !chkShippingAddressIsBusiness.Checked
            };

            var shipmentPackages = checkoutOrderInfo.Cart.GetCartItemsAsShipmentPackages(shipmentPackagingStrategy);
            var shippingRates    = new List <IShippingRate>();
            var shippingServices = StoreContext.CurrentStore.GetEnabledShippingProviders(null, checkoutOrderInfo.Cart.Id);

            foreach (var shipper in shippingServices)
            {
                //if(shipper is UpsShippingService)
                //{
                // NOTE: UPS is silly and requires PostalCode AND State/Region - Now being used for all shipping estimates for a more accurate estimate
                IGeocodeRequest request  = new GoogleGeocodeRequest(destination.PostalCode);
                IGeocodeService service  = new GoogleGeocoderV3();
                var             response = service.Geocode(request) as GoogleGeocodeResponse;
                if (response.Success && response.Results.Length > 0)
                {
                    string region = response.Results[0].Address_Components.Where(x => x.Types.Contains(AddressComponentType.administrative_area_level_1)).Select(x => x.Short_Name).FirstOrDefault();
                    if (!string.IsNullOrEmpty(region))
                    {
                        destination.Region = region;
                    }

                    string countryCode = response.Results[0].Address_Components.Where(x => x.Types.Contains(AddressComponentType.country)).Select(x => x.Short_Name).FirstOrDefault();
                    if (!string.IsNullOrEmpty(countryCode))
                    {
                        destination.CountryCode = countryCode;
                    }
                }
                //}
                try
                {
                    shippingRates.AddRange(shipper.GetRates(origin, destination, shipmentPackages));
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                    ShowFlash(ex.Message);
                }
            }

            //rptShippingRateEstimates.DataSource = shippingRates;
            //rptShippingRateEstimates.DataBind();

            rblShippingRateEstimates.Items.Clear();
            shippingRates.ForEach(x => rblShippingRateEstimates.Items.Add(new ListItem()
            {
                Value = string.Format(@"{0}||{1}||{2}", x.ServiceType, x.ServiceTypeDescription, x.Rate),
                Text  = string.Format(@"{0} - {1}", ((ShippingRate)x).DisplayName, HttpUtility.HtmlDecode(StoreContext.CurrentStore.FormatCurrency(x.Rate)))
            }));
        }
Beispiel #2
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            int storeId = StoreContext.CurrentStore.Id.Value;

            ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(StoreContext.CurrentStore.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

            ddlShipmentPackaging.SelectedValue = shipmentPackagingStrategy.ToString();

            //---- Custom Shipping
            shippingTablesService = DataModel.ShippingService.FindOrCreateNew(storeId, ShippingProviderType.CustomShipping);
            if (shippingTablesService.ShippingServiceRateTypeCollectionByShippingServiceId.Count == 0)
            {
                var defaultRateType = shippingTablesService.ShippingServiceRateTypeCollectionByShippingServiceId.AddNew();
                defaultRateType.Name        = "FREE Shipping";
                defaultRateType.DisplayName = "FREE Shipping";
                defaultRateType.IsEnabled   = true;
                defaultRateType.SortOrder   = 1;

                var defaultRate = defaultRateType.ShippingServiceRateCollectionByRateTypeId.AddNew();
                defaultRate.WeightMin = 0;
                defaultRate.WeightMax = 999999;
                defaultRate.Cost      = 0;

                shippingTablesService.Save();
            }
            //shippingTablesProvider = ShippingProviderFactory.Get(storeId, ShippingProviderType.CustomShipping);

            //--- FedEx
            fedExService = DataModel.ShippingService.FindOrCreateNew(storeId, ShippingProviderType.FedEx);
            //fedExProvider = ShippingProviderFactory.Get(storeId, ShippingProviderType.FedEx);
            // FedEx - Add RateTypes for this service if they don't exist
            List <ShippingServiceRateType> rateTypes = fedExService.GetAllRateTypes();

            string[] allRateTypes = WA.Enum <WA.Shipping.FedExServiceType> .GetNames();

            foreach (string rateType in allRateTypes)
            {
                if (!rateTypes.Exists(x => x.Name == rateType))
                {
                    var newRateType = fedExService.ShippingServiceRateTypeCollectionByShippingServiceId.AddNew();
                    newRateType.Name        = rateType;
                    newRateType.DisplayName = rateType;
                    newRateType.IsEnabled   = true;
                    newRateType.SortOrder   = 99;
                }
            }
            fedExService.Save();

            //--- UPS
            upsService = DataModel.ShippingService.FindOrCreateNew(storeId, ShippingProviderType.UPS);
            upsService.Save();
        }
        protected void btnGetShippingTrackingLabels_Click(object sender, EventArgs e)
        {
            if (LoadOrder())
            {
                ShipmentPackagingStrategy packagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(ddlPackageGrouping.SelectedValue, ShipmentPackagingStrategy.SingleBox);

                var    orderController = new OrderController(StoreContext);
                var    shipResult      = orderController.GetTrackingNumberAndLabels(order, packagingStrategy);
                string flashMsg        = shipResult.Success ? "Tracking Number and Shipping Labels updated" : shipResult.ErrorMessages.ToDelimitedString("<br />");

                Response.Redirect(StoreUrls.Admin(ModuleDefs.Admin.Views.ViewOrder, "id=" + order.Id, "flash=" + HttpUtility.UrlPathEncode(flashMsg)));
            }
        }
Beispiel #4
0
        protected void btnBulkProcessShipments_Click(object sender, EventArgs e)
        {
            List <string> bulkErrors = new List <string>();

            // TODO - get the packaging strategy from the user
            ShipmentPackagingStrategy packagingStrategy = ShipmentPackagingStrategy.SingleBox;

            string[] orderNos = Request.Form.GetValues("orderNumber");
            if (orderNos != null && orderNos.Length > 0)
            {
                var orderController = new OrderController(StoreContext);

                List <Order> orders = OrderCollection.FindOrdersByOrderNumber(StoreContext.CurrentStore.Id.Value, new List <string>(orderNos));
                foreach (var order in orders)
                {
                    var orderToShip = Order.GetOrder(order.Id.Value);

                    var result = orderController.GetTrackingNumberAndLabels(orderToShip, packagingStrategy);
                    if (!result.Success)
                    {
                        bulkErrors.AddRange(result.ErrorMessages);
                    }
                }
            }
            else
            {
                bulkErrors.Add("No orders selected");
            }

            var flashHtml = new StringBuilder();

            if (bulkErrors.Count == 0)
            {
                flashHtml.AppendFormat("Shipments Processed Successfully");
            }
            else
            {
                bulkErrors.ForEach(s => flashHtml.AppendFormat("{0}<br />", s));
            }

            processShipmentMessages.InnerHtml = flashHtml.ToString();
            processShipmentMessages.Visible   = true;
            pnlSearch.Visible       = false;
            pnlOrderResults.Visible = false;
            flash.Visible           = false;
        }
Beispiel #5
0
        private void FillListControls()
        {
            //---- Shipping Options
            IPostalAddress            origin      = StoreContext.CurrentStore.Address.ToPostalAddress();
            IPostalAddress            destination = checkoutOrderInfo.ShippingAddress.ToPostalAddress();
            ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(StoreContext.CurrentStore.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

            var shipmentPackages = checkoutOrderInfo.Cart.GetCartItemsAsShipmentPackages(shipmentPackagingStrategy);
            var shippingRates    = new List <IShippingRate>();
            var shippingServices = StoreContext.CurrentStore.GetEnabledShippingProviders(null, checkoutOrderInfo.Cart.Id);

            foreach (var shipper in shippingServices)
            {
                try
                {
                    shippingRates.AddRange(shipper.GetRates(origin, destination, shipmentPackages));
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                    ShowFlash(ex.Message);
                }
            }
            ddlShippingOption.Items.Clear();
            shippingRates.ForEach(x => ddlShippingOption.Items.Add(new ListItem()
            {
                Value = string.Format(@"{0}||{1}||{2}", x.ServiceType, x.ServiceTypeDescription, x.Rate),
                Text  = string.Format(@"{0} - {1}", ((ShippingRate)x).DisplayName, HttpUtility.HtmlDecode(StoreContext.CurrentStore.FormatCurrency(x.Rate)))
            }));

            var    rate = shippingRates.Where(x => checkoutOrderInfo.ShippingRate.ServiceType == x.ServiceType).FirstOrDefault();
            string selectedShippingRate = String.Empty;

            if (rate != null)
            {
                selectedShippingRate = string.Format(@"{0}||{1}||{2}", rate.ServiceType, rate.ServiceTypeDescription, rate.Rate);
            }

            ddlShippingOption.TrySetSelectedValue(selectedShippingRate);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int?deleteId = WA.Parser.ToInt(Request.QueryString["delete"]);
                if (deleteId.HasValue)
                {
                    Order toDelete = new Order();
                    if (toDelete.LoadByPrimaryKey(deleteId.Value))
                    {
                        //--- SOFT Delete
                        toDelete.IsDeleted   = true;
                        toDelete.OrderStatus = OrderStatusName.Deleted;
                        toDelete.Save();

                        Response.Redirect(StoreUrls.Admin(ModuleDefs.Admin.Views.Orders));
                    }
                }

                if (LoadOrder())
                {
                    FillListControls();

                    IShippingService shippingService = null;
                    if (order.ShippingServiceProvider.Contains("UPS", false))
                    {
                        shippingService = ShippingServiceFactory.Get(order.StoreId.Value, ShippingProviderType.UPS, order.Id, order.CreatedFromCartId);
                    }
                    else if (order.ShippingServiceProvider.Contains("FedEx", false))
                    {
                        shippingService = ShippingServiceFactory.Get(order.StoreId.Value, ShippingProviderType.FedEx, order.Id, order.CreatedFromCartId);
                    }
                    bool shipperSupportsTrackingNumbers = (shippingService != null) && ((shippingService is FedExShippingService) || (shippingService is UpsShippingService));

                    ddlOrderStatus.SelectedValue   = order.OrderStatus.ToString();
                    ddlPaymentStatus.SelectedValue = order.PaymentStatus.ToString();

                    txtShippingTrackingNumber.Text = order.ShippingServiceTrackingNumber;
                    if (!string.IsNullOrEmpty(order.ShippingServiceTrackingNumber))
                    {
                        btnSaveTrackingNumber.Visible     = false;
                        txtShippingTrackingNumber.Visible = false;
                    }

                    rptShippingLog.DataSource = order.GetShippingLogEntries();
                    rptShippingLog.DataBind();
                    rptShippingLog.Visible = (rptShippingLog.Items.Count > 0);

                    rptPaymentTransactions.DataSource = order.GetPaymentTransactionsOldestFirst();
                    rptPaymentTransactions.DataBind();
                    rptPaymentTransactions.Visible = (rptPaymentTransactions.Items.Count > 0);

                    rptOrderItems.DataSource = order.OrderItemCollectionByOrderId;
                    rptOrderItems.DataBind();

                    //if(order.PaymentStatus != PaymentStatusName.Completed && StoreContext.CurrentStore.IsPaymentProviderEnabled(PaymentProviderName.OfflinePayment) && order.Total.GetValueOrDefault(0) > 0)
                    if (order.PaymentStatus != PaymentStatusName.Completed && order.Total.GetValueOrDefault(0) > 0)
                    {
                        btnMarkOfflinePaid.Visible = true;
                    }

                    btnGetShippingTrackingLabels.Visible = false;
                    btnSendShippingEmail.Visible         = false;
                    btnMarkShipped.Visible = false;

                    if (!string.IsNullOrEmpty(order.ShippingServiceTrackingNumber))
                    {
                        btnGetShippingTrackingLabels.CssClass += " ok";
                    }

                    switch (order.OrderStatus)
                    {
                    case OrderStatusName.Processing:
                        btnMarkShipped.Visible = true;
                        btnGetShippingTrackingLabels.Visible = order.HasShippableItems;
                        break;

                    case OrderStatusName.Completed:
                        btnSendShippingEmail.Visible = order.HasShippableItems;
                        if (string.IsNullOrEmpty(order.ShippingServiceTrackingNumber))
                        {
                            btnGetShippingTrackingLabels.Visible = order.HasShippableItems;
                        }
                        break;
                    }

                    if (!shipperSupportsTrackingNumbers)
                    {
                        btnGetShippingTrackingLabels.Visible = false;
                    }
                    divShipmentPackaging.Visible = btnGetShippingTrackingLabels.Visible;

                    ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(StoreContext.CurrentStore.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

                    ddlPackageGrouping.SelectedValue = shipmentPackagingStrategy.ToString();
                }
            }
        }
        internal ProcessShipmentResult GetTrackingNumberAndLabels(Order order, ShipmentPackagingStrategy packagingStrategy)
        {
            IShippingService shippingService = null;

            if (order.ShippingServiceProvider == ShippingProviderType.FedEx.ToString())
            {
                shippingService = ShippingServiceFactory.Get(storeContext.CurrentStore.Id.Value, ShippingProviderType.FedEx, order.Id, order.CreatedFromCartId);
            }
            else if (order.ShippingServiceProvider == ShippingProviderType.UPS.ToString())
            {
                shippingService = ShippingServiceFactory.Get(storeContext.CurrentStore.Id.Value, ShippingProviderType.UPS, order.Id, order.CreatedFromCartId);
            }
            else if (order.ShippingServiceProvider == ShippingProviderType.CustomShipping.ToString())
            {
                shippingService = ShippingServiceFactory.Get(storeContext.CurrentStore.Id.Value, ShippingProviderType.CustomShipping);
            }
            if (shippingService == null)
            {
                return(new ProcessShipmentResult()
                {
                    Success = false,
                    ErrorMessages = new List <string>()
                    {
                        string.Format(@"{0} was not processed because '{1}' is an un-supported shipping provider.", order.OrderNumber, order.ShippingServiceProvider)
                    }
                });
            }

            var store = storeContext.CurrentStore;
            var shipmentLabelRequest = new ShipmentLabelRequest();

            shipmentLabelRequest.SenderAddress = store.Address.ToPostalAddress();
            shipmentLabelRequest.SenderContact = new Contact()
            {
                FirstName   = store.Address.FirstName,
                LastName    = store.Address.LastName,
                CompanyName = store.Name,
                Phone       = store.GetSetting(StoreSettingNames.StorePhoneNumber)
            };
            shipmentLabelRequest.RecipientAddress = new PostalAddress()
            {
                Address1    = order.ShipAddress1,
                Address2    = order.ShipAddress2,
                City        = order.ShipCity,
                Region      = order.ShipRegion,
                PostalCode  = order.ShipPostalCode,
                CountryCode = order.ShipCountryCode
            };
            shipmentLabelRequest.RecipientContact = new Contact()
            {
                FirstName   = order.CustomerFirstName,
                LastName    = order.CustomerLastName,
                CompanyName = order.ShipRecipientBusinessName,
                Phone       = order.ShipTelephone
            };
            shipmentLabelRequest.ServiceType = order.ShippingServiceType;
            shipmentLabelRequest.Packages    = order.GetOrderItemsAsShipmentPackages(packagingStrategy);

            var response = shippingService.GetShipmentLabels(shipmentLabelRequest);

            if (response.Labels.Count > 0)
            {
                // save tracking #
                if (!string.IsNullOrEmpty(response.MasterTrackingNumber))
                {
                    order.ShippingServiceTrackingNumber = response.MasterTrackingNumber;
                }

                List <string> trackingNumbers = new List <string>();
                List <string> labelFilenames  = new List <string>();
                foreach (var label in response.Labels)
                {
                    // save shipping label file(s)
                    if (label.LabelFile != null && label.LabelFile.Length > 0)
                    {
                        string labelDirPath = storeUrls.ShippingLabelFolderFileRoot;
                        if (!Directory.Exists(labelDirPath))
                        {
                            Directory.CreateDirectory(labelDirPath);
                        }

                        string fileExt  = "." + label.LabelFileType.ToString().ToLower();
                        string filename = Guid.NewGuid().ToString();
                        if (label.PackageDetail != null && !string.IsNullOrEmpty(label.PackageDetail.ReferenceCode))
                        {
                            filename = label.PackageDetail.ReferenceCode;
                        }
                        string filePath = Path.Combine(labelDirPath, filename + fileExt);
                        if (File.Exists(filePath) && label.PackageDetail != null && !string.IsNullOrEmpty(label.PackageDetail.ReferenceCode))
                        {
                            filename = label.PackageDetail.ReferenceCode + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmssZ");
                            filePath = Path.Combine(labelDirPath, filename + fileExt);
                        }

                        File.WriteAllBytes(filePath, label.LabelFile);
                        labelFilenames.Add(Path.GetFileName(filePath));
                        if (!string.IsNullOrEmpty(label.TrackingNumber))
                        {
                            trackingNumbers.Add(label.TrackingNumber);
                        }
                    }
                }
                order.ShippingServiceLabelFile = string.Join(",", labelFilenames.ToArray());
                if (trackingNumbers.Count > 0)
                {
                    order.ShippingServiceTrackingNumber = string.Join(",", trackingNumbers.ToArray());
                }
                order.Save();

                //// update order status to 'Completed'
                //UpdateOrderStatus(order, OrderStatusName.Completed, order.PaymentStatus);
            }

            return(new ProcessShipmentResult()
            {
                Success = true,
                ErrorMessages = new List <string>(),
                ShippingLabels = response
            });
        }
Beispiel #8
0
        public List <IShipmentPackageDetail> GetOrderItemsAsShipmentPackages(ShipmentPackagingStrategy packagingStrategy)
        {
            var orderItems = this.OrderItemCollectionByOrderId;

            if (packagingStrategy == ShipmentPackagingStrategy.SingleBox)
            {
                decimal maxWeight = orderItems.Max(x => x.WeightTotal.GetValueOrDefault(1));
                decimal maxLength = orderItems.Max(x => x.Length.GetValueOrDefault(1));
                decimal maxWidth  = orderItems.Max(x => x.Width.GetValueOrDefault(1));
                decimal maxHeight = orderItems.Max(x => x.Height.GetValueOrDefault(1));

                return(new List <IShipmentPackageDetail>()
                {
                    new ShipmentPackageDetail()
                    {
                        Weight = maxWeight,
                        Length = maxLength,
                        Width = maxWidth,
                        Height = maxHeight,
                        ReferenceCode = this.OrderNumber
                    }
                });
            }
            else if (packagingStrategy == ShipmentPackagingStrategy.BoxPerProductType)
            {
                var shipmentPackages = new List <IShipmentPackageDetail>();
                foreach (var item in orderItems)
                {
                    shipmentPackages.Add(new ShipmentPackageDetail()
                    {
                        Weight        = item.WeightTotal.GetValueOrDefault(1),
                        Length        = item.Length.GetValueOrDefault(1),
                        Width         = item.Width.GetValueOrDefault(1),
                        Height        = item.Height.GetValueOrDefault(1),
                        ReferenceCode = string.Format(@"{0}-{1}", this.OrderNumber, item.Sku)
                    });
                }
                return(shipmentPackages);
            }
            else if (packagingStrategy == ShipmentPackagingStrategy.BoxPerItem)
            {
                var shipmentPackages = new List <IShipmentPackageDetail>();
                int itemNum          = 1;
                foreach (var item in orderItems)
                {
                    decimal itemWeight = item.WeightTotal.GetValueOrDefault(0) / item.Quantity.GetValueOrDefault(1);
                    int     qtyIndex   = 1;
                    while (qtyIndex <= item.Quantity)
                    {
                        shipmentPackages.Add(new ShipmentPackageDetail()
                        {
                            Weight        = itemWeight,
                            Length        = item.Length.GetValueOrDefault(1),
                            Width         = item.Width.GetValueOrDefault(1),
                            Height        = item.Height.GetValueOrDefault(1),
                            ReferenceCode = string.Format(@"{0}-{1}-{2}", this.OrderNumber, item.Sku, qtyIndex)
                        });
                        qtyIndex++;
                    }
                    itemNum++;
                }
                return(shipmentPackages);
            }
            else
            {
                throw new ArgumentException("Unknown ShipmentPackagingStrategy", "packagingStrategy");
            }
        }
Beispiel #9
0
        public List <IShipmentPackageDetail> GetCartItemsAsShipmentPackages(ShipmentPackagingStrategy packagingStrategy)
        {
            var cartContents = GetCartItemsWithProductInfo().Where(p => p.DeliveryMethod == ProductDeliveryMethod.Shipped);

            if (cartContents.Count() == 0)
            {
                return(new List <IShipmentPackageDetail>());
            }

            if (packagingStrategy == ShipmentPackagingStrategy.SingleBox)
            {
                var cartProducts = cartContents.Select(x => x.GetProduct());

                decimal totalWeight           = cartContents.Sum(x => x.GetWeightForQuantity());
                decimal maxLength             = cartProducts.Max(x => x.Length.GetValueOrDefault(1));
                decimal maxWidth              = cartProducts.Max(x => x.Width.GetValueOrDefault(1));
                decimal maxHeight             = cartProducts.Max(x => x.Height.GetValueOrDefault(1));
                decimal additionalHandlingFee = cartProducts.Sum(x => x.ShippingAdditionalFeePerItem).GetValueOrDefault(0);


                return(new List <IShipmentPackageDetail>()
                {
                    new ShipmentPackageDetail()
                    {
                        Weight = totalWeight,
                        Length = maxLength,
                        Width = maxWidth,
                        Height = maxHeight,
                        AdditionalHandlingFee = additionalHandlingFee
                    }
                });
            }
            else if (packagingStrategy == ShipmentPackagingStrategy.BoxPerProductType)
            {
                var cartProducts = cartContents.Select(x => x.GetProduct());
                return((from item in cartContents
                        let product = item.GetProduct()
                                      select new ShipmentPackageDetail()
                {
                    Weight = item.GetWeightForQuantity(), Length = product.Length.GetValueOrDefault(1), Width = product.Width.GetValueOrDefault(1), Height = product.Height.GetValueOrDefault(1), AdditionalHandlingFee = product.ShippingAdditionalFeePerItem.GetValueOrDefault(0) * item.Quantity.GetValueOrDefault(1)
                }).Cast <IShipmentPackageDetail>().ToList());
            }
            else if (packagingStrategy == ShipmentPackagingStrategy.BoxPerItem)
            {
                var shipmentPackages = new List <IShipmentPackageDetail>();
                foreach (var item in cartContents)
                {
                    var product  = item.GetProduct();
                    int qtyIndex = 1;
                    while (qtyIndex <= item.Quantity)
                    {
                        shipmentPackages.Add(new ShipmentPackageDetail()
                        {
                            Weight = product.Weight.GetValueOrDefault(1),
                            Length = product.Length.GetValueOrDefault(1),
                            Width  = product.Width.GetValueOrDefault(1),
                            Height = product.Height.GetValueOrDefault(1),
                            AdditionalHandlingFee = product.ShippingAdditionalFeePerItem.GetValueOrDefault(0)
                        });
                        qtyIndex++;
                    }
                }
                return(shipmentPackages);
            }
            else
            {
                throw new ArgumentException("Unknown ShipmentPackagingStrategy", "packagingStrategy");
            }
        }
Beispiel #10
0
        public void ProcessRequest(HttpContext context)
        {
            response = context.Response;
            request  = context.Request;

            //response.ContentType = "text/plain";
            response.ContentType = "application/json"; // jQuery 1.4.2 requires this now!

            try
            {
                StoreContext storeContext = new StoreContext(request);
                StoreUrls    storeUrls    = new StoreUrls(storeContext);

                string  action    = request.Params["action"];
                int?    productId = WA.Parser.ToInt(request.Params["productId"]);
                Product product   = null;
                if (productId.HasValue)
                {
                    product = Product.GetProduct(productId.Value);
                }

                switch (action)
                {
                case "updateShippingRateTypeName":
                    int?shippingRateTypeId = WA.Parser.ToInt(request.Params["shippingServiceRateTypeId"]);
                    if (shippingRateTypeId.HasValue)
                    {
                        string shippingName = request.Params["name"];
                        DataModel.ShippingServiceRateType shippingMethod = DataModel.ShippingServiceRateType.Get(shippingRateTypeId.Value);
                        if (shippingMethod != null)
                        {
                            shippingMethod.DisplayName = shippingName;
                            shippingMethod.Save();

                            RespondWithSuccess();
                        }
                    }
                    break;

                case "getShippingRatesJson":
                    DataModel.ShippingServiceRateType rateType = DataModel.ShippingServiceRateType.Get(WA.Parser.ToShort(request.Params["shippingServiceRateTypeId"]).GetValueOrDefault(-1));
                    if (rateType != null)
                    {
                        List <ShippingServiceRate>     rates     = rateType.GetRates();
                        List <JsonShippingServiceRate> jsonRates = rates.ConvertAll(
                            r =>
                            new JsonShippingServiceRate()
                        {
                            RateTypeId  = rateType.Id.Value,
                            CountryCode = r.CountryCode,
                            Region      = r.Region,
                            MinWeight   = r.WeightMin,
                            MaxWeight   = r.WeightMax,
                            Cost        = r.Cost
                        }
                            );
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonRates);
                        response.Write(json);
                    }
                    break;
                //case "applyShippingRate":
                //    string shippingRate = request.Params["shippingServiceRateTypeId"];
                //    if (shippingRate != null)
                //    {

                //        var store = storeContext.CurrentStore;

                //        var checkoutOrderInfo = HttpContext.Current.Session[storeContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo;

                //        string[] rateParts = shippingRate.Split("||");
                //        checkoutOrderInfo.ShippingRate.ServiceType = rateParts[0];
                //        checkoutOrderInfo.ShippingRate.ServiceTypeDescription = rateParts[1];
                //        checkoutOrderInfo.ShippingRate.Rate = Convert.ToDecimal(rateParts.Length == 3 ? rateParts[2] : rateParts[1]);
                //        checkoutOrderInfo.ReCalculateOrderTotals();

                //        Session[StoreContext.SessionKeys.CheckoutOrderInfo] = checkoutOrderInfo;
                //    }
                //    break;
                case "getShippingOptionEstimatesJson":

                    string address1   = request.Params["address1"];
                    string address2   = request.Params["address2"];
                    string city       = request.Params["city"];
                    string country    = request.Params["country"];
                    string region     = request.Params["region"];
                    string postalCode = request.Params["postalCode"];
                    bool   isBusiness = Convert.ToBoolean(request.Params["isBusiness"]);

                    var store = storeContext.CurrentStore;

                    var cartController    = new CartController(storeContext);
                    var checkoutOrderInfo = HttpContext.Current.Session[storeContext.SessionKeys.CheckoutOrderInfo] as CheckoutOrderInfo;
                    if (checkoutOrderInfo == null)
                    {
                        var cart = cartController.GetCart(false);
                        checkoutOrderInfo = new CheckoutOrderInfo()
                        {
                            Cart = cart
                        };
                    }
                    //List<string> errors;
                    //var shippingOptionEstimates = store.GetShippingOptionEstimates(origin, destination, checkoutOrderInfo.Cart.GetCartItemsWithProductInfo(), out errors);
                    //var shippingOptions = shippingOptionEstimates.ConvertAll(x => new
                    //                        {
                    //                            Value = x.Cost.GetValueOrDefault(0).ToString("F2"),
                    //                            Name = x.DisplayName,
                    //                            Text = string.Format(@"{0}  :  {1}", x.DisplayName, store.FormatCurrency(x.Cost))
                    //                        });

                    IPostalAddress origin      = store.Address.ToPostalAddress();
                    IPostalAddress destination = new PostalAddress()
                    {
                        Address1 = address1, Address2 = address2, City = city, CountryCode = country, Region = region.ToUpper(), PostalCode = postalCode.ToUpper(), IsResidential = !isBusiness
                    };

                    ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(store.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

                    var shipmentPackages = checkoutOrderInfo.Cart.GetCartItemsAsShipmentPackages(shipmentPackagingStrategy);
                    var shippingRates    = new List <IShippingRate>();
                    var shippingServices = store.GetEnabledShippingProviders(null, checkoutOrderInfo.Cart.Id);
                    foreach (var shipper in shippingServices)
                    {
                        shippingRates.AddRange(shipper.GetRates(origin, destination, shipmentPackages));
                    }
                    var shippingOptions = shippingRates.Select(x => new
                    {
                        Value = x.Rate.ToString("F2"),
                        Name  = x.ServiceType,
                        Text  = string.Format(@"{0}  :  {1}", x.ServiceType, store.FormatCurrency(x.Rate))
                    });

                    string shippingOptionsJson = Newtonsoft.Json.JsonConvert.SerializeObject(shippingOptions);
                    response.Write(shippingOptionsJson);
                    break;

                case "getProductPhotosJson":
                    if (productId.HasValue)
                    {
                        List <ProductPhoto> productPhotos     = Product.GetAllPhotosInSortOrder(productId.Value);
                        List <JsonPhoto>    jsonProductPhotos =
                            productPhotos.ConvertAll(
                                p =>
                                new JsonPhoto()
                        {
                            Id           = p.Id.Value,
                            OriginalUrl  = storeUrls.ProductPhoto(p, null, null),
                            ThumbnailUrl = storeUrls.ProductPhoto(p, 120, 90)
                        });
                        string jsonPhotos = Newtonsoft.Json.JsonConvert.SerializeObject(jsonProductPhotos);

                        response.Write(jsonPhotos);
                    }
                    break;

                case "deleteProductPhoto":
                    int?photoId = WA.Parser.ToInt(request.Params["photoId"]);
                    if (ProductPhoto.DeletePhoto(photoId.GetValueOrDefault(-1)))
                    {
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("unable to delete photo: " + photoId);
                    }
                    break;

                case "updateProductPhotoSortOrder":
                    if (productId.HasValue && request.Params["photoList[]"] != null)
                    {
                        List <string> sortedPhotoList = new List <string>(request.Params.GetValues("photoList[]"));
                        List <int>    sortedPhotoIds  = sortedPhotoList.ConvertAll(p => Convert.ToInt32(p.Split('-')[1]));

                        ProductPhotoQuery q = new ProductPhotoQuery();
                        q.Where(q.ProductId == productId.Value);
                        ProductPhotoCollection photos = new ProductPhotoCollection();
                        if (photos.Load(q))
                        {
                            foreach (ProductPhoto photo in photos)
                            {
                                photo.SortOrder = (short)sortedPhotoIds.IndexOf(photo.Id.Value);
                            }
                            photos.Save();
                        }
                        RespondWithSuccess();
                    }
                    break;

                case "getProductCustomFieldsJson":
                    if (product != null)
                    {
                        List <ProductField>     productFields     = product.GetProductFieldsInSortOrder();
                        List <JsonProductField> jsonProductFields = productFields.ConvertAll(
                            f => new JsonProductField()
                        {
                            Id               = f.Id.Value,
                            WidgetType       = f.WidgetType,
                            Name             = f.Name,
                            Slug             = f.Slug,
                            IsRequired       = f.IsRequired.GetValueOrDefault(),
                            PriceAdjustment  = f.PriceAdjustment.GetValueOrDefault(0),
                            WeightAdjustment = f.WeightAdjustment.GetValueOrDefault(0),
                            SortOrder        = f.SortOrder.GetValueOrDefault(),
                            Choices          = f.GetChoicesInSortOrder().ToList().ConvertAll(
                                c => new JsonProductFieldChoice()
                            {
                                Id               = c.Id.Value,
                                ProductFieldId   = f.Id.Value,
                                Name             = c.Name,
                                PriceAdjustment  = c.PriceAdjustment.GetValueOrDefault(0),
                                WeightAdjustment = c.WeightAdjustment.GetValueOrDefault(0),
                                SortOrder        = c.SortOrder.GetValueOrDefault()
                            })
                        });
                        string jsonCustomFields = Newtonsoft.Json.JsonConvert.SerializeObject(jsonProductFields);

                        response.Write(jsonCustomFields);
                    }
                    break;

                case "updateCategorySortOrder":
                    string[] sortedCatIdStrings = request.Params.GetValues("sortedCategoryIds");
                    if (sortedCatIdStrings != null)
                    {
                        List <int> sortedCatIds = new List <string>(sortedCatIdStrings).ConvertAll(s => WA.Parser.ToInt(s).GetValueOrDefault(-1));
                        CategoryCollection.SetSortOrderByListPosition(sortedCatIds);
                        CacheHelper.ClearCache();
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("no category ids found to update sort order");
                    }
                    break;

                case "updateProductFieldSortOrder":
                    var sortedProductFieldIdStrings = request.Params.GetValues("sortedProductFieldIds[]");
                    if (sortedProductFieldIdStrings != null)
                    {
                        List <int> sortedProductFieldIds = new List <string>(sortedProductFieldIdStrings).ConvertAll(s => WA.Parser.ToInt(s).GetValueOrDefault(-1));
                        ProductFieldCollection.SetSortOrderByListPosition(sortedProductFieldIds);
                        RespondWithSuccess();
                    }
                    else
                    {
                        RespondWithError("no product field ids found to update sort order");
                    }
                    break;

                default:
                    RespondWithError("unknown action");
                    break;
                }

                //response.Write("{ success: true }");
            }
            catch (Exception ex)
            {
                RespondWithError(ex.Message + " Stack Trace:" + ex.StackTrace);
            }

            response.Flush();
        }
        public void ReCalculateOrderTotals()
        {
            var store = DataModel.Store.GetStore(StoreId);

            // SubTotal - add up cart items and quantities
            decimal cartItemSubTotal = 0.0m;
            decimal taxableSubTotal  = 0.0m;
            List <vCartItemProductInfo> cartItems = cart.GetCartItemsWithProductInfo();

            foreach (vCartItemProductInfo item in cartItems)
            {
                decimal itemPriceForQuantity = item.GetPriceForQuantity();
                cartItemSubTotal += itemPriceForQuantity;
                if (item.ProductIsTaxable.GetValueOrDefault(true))
                {
                    taxableSubTotal += itemPriceForQuantity;
                }
            }
            SubTotal = cartItemSubTotal;

            // Shipping Cost - Provided by ShippingProvider
            bool calculateShipping = (ShippingAddress != null) && (!string.IsNullOrEmpty(ShippingAddress.PostalCode));

            if (calculateShipping)
            {
                var shippingService = ShippingServiceFactory.Get(StoreId, ShippingProvider, null, cart.Id);
                if (shippingService != null)
                {
                    ShipmentPackagingStrategy shipmentPackagingStrategy = WA.Enum <ShipmentPackagingStrategy> .TryParseOrDefault(store.GetSetting(StoreSettingNames.ShipmentPackagingStrategy), ShipmentPackagingStrategy.SingleBox);

                    var rate = shippingService.GetRate(store.Address.ToPostalAddress(), ShippingAddress.ToPostalAddress(), cart.GetCartItemsAsShipmentPackages(shipmentPackagingStrategy), this.ShippingRate.ServiceType);
                    if (rate != null)
                    {
                        this.ShippingRate = rate;
                    }
                }
            }
            else
            {
                this.ShippingRate.Rate = 0;
            }

            // Coupons
            ReApplyAllCoupons();

            // Tax Amount
            string taxCountry  = BillingAddress.Country;
            string taxRegion   = BillingAddress.Region;
            bool   taxShipping = true;

            if (store != null)
            {
                if (store.GetSetting(StoreSettingNames.SalesTaxAddressType) == "Shipping")
                {
                    taxCountry = ShippingAddress.Country;
                    taxRegion  = ShippingAddress.Region;
                }

                taxShipping = WA.Parser.ToBool(store.GetSetting(StoreSettingNames.TaxShipping)).GetValueOrDefault(true);
            }
            decimal taxRate = TaxRegion.GetTaxRate(cart.StoreId.GetValueOrDefault(-1), taxCountry, taxRegion);

            if (taxShipping)
            {
                TaxAmount = ((Math.Max(0, taxableSubTotal - DiscountAmount) + ShippingRate.Rate) * taxRate).RoundForMoney();
            }
            else
            {
                TaxAmount = ((Math.Max(0, taxableSubTotal - DiscountAmount)) * taxRate).RoundForMoney();
            }

            // Total
            Total = (SubTotal + ShippingRate.Rate - DiscountAmount + TaxAmount).RoundForMoney();
        }