private ShippingMethodAndRate GetShippingRateInfo(ShippingMethodDto.ShippingMethodRow row, Shipment shipment)
        {
            ShippingMethodAndRate returnRate = null;
            string nameAndRate = string.Empty;

            // Check if package contains shippable items, if it does not use the default shipping method instead of the one specified
            Type type = Type.GetType(row.ShippingOptionRow.ClassName);

            if (type == null)
            {
                throw new TypeInitializationException(row.ShippingOptionRow.ClassName, null);
            }

            string           outputMessage = string.Empty;
            IShippingGateway provider      = (IShippingGateway)Activator.CreateInstance(type);

            if (shipment != null)
            {
                ShippingRate rate = provider.GetRate(row.ShippingMethodId, shipment, ref outputMessage);
                nameAndRate = string.Format("{0} : {1}", row.Name, rate.Money.Amount.ToString("C"));
                returnRate  = new ShippingMethodAndRate(row.Name, nameAndRate, rate.Money.Amount, row.ShippingMethodId);
            }

            return(returnRate);
        }
        /// <summary>
        /// Binds the form.
        /// </summary>
        private void BindForm()
        {
            if (_ShippingMethodDto != null && _ShippingMethodDto.ShippingMethod.Count > 0)
            {
                try
                {
                    ShippingMethodDto.ShippingMethodRow shippingRow = _ShippingMethodDto.ShippingMethod[0];

                    // set initial state of dual lists
                    BindCountriesList(shippingRow);
                    BindRegionsList(shippingRow);
                    BindPaymentsList(shippingRow);
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage("Error during binding gateway settings: " + ex.Message);
                    return;
                }
            }
            else
            {
                BindCountriesList(null);
                BindRegionsList(null);
                BindPaymentsList(null);
            }
        }
Esempio n. 3
0
        private ShippingRate GetRate(Shipment shipment, ShippingMethodDto.ShippingMethodRow shippingMethodRow)
        {
            var    type            = Type.GetType(shippingMethodRow.ShippingOptionRow.ClassName);
            var    shippingGateway = (IShippingGateway)Activator.CreateInstance(type, _currentMarket.GetCurrentMarket());
            string message         = null;

            return(shippingGateway.GetRate(shippingMethodRow.ShippingMethodId, shipment, ref message));
        }
Esempio n. 4
0
 private static ShippingRate CreateBaseShippingRate(Guid shippingMethodId, ShippingMethodDto.ShippingMethodRow shippingMethodRow)
 {
     return(new ShippingRate(
                shippingMethodId,
                shippingMethodRow.DisplayName,
                new Money(shippingMethodRow.BasePrice,
                          new Currency(shippingMethodRow.Currency))));
 }
        /// <summary>
        /// Binds the regions list.
        /// </summary>
        /// <param name="shippingRow">The shipping row.</param>
        private void BindRegionsList(ShippingMethodDto.ShippingMethodRow shippingRow)
        {
            List <CountryDto.StateProvinceRow> leftRegions  = new List <CountryDto.StateProvinceRow>();
            List <CountryDto.StateProvinceRow> rightRegions = new List <CountryDto.StateProvinceRow>();

            CountryDto dto = CountryManager.GetCountries(true);

            bool allToLeft = false;             // if true, then add all regions to the left list

            if (shippingRow != null)
            {
                ShippingMethodDto.ShippingRegionRow[] restrictedRegionRows = shippingRow.GetShippingRegionRows();
                if (restrictedRegionRows != null && restrictedRegionRows.Length > 0)
                {
                    foreach (CountryDto.StateProvinceRow stateProvinceRow in dto.StateProvince)
                    {
                        bool found = false;
                        foreach (ShippingMethodDto.ShippingRegionRow restrictedRegionRow in restrictedRegionRows)
                        {
                            if (stateProvinceRow.StateProvinceId == restrictedRegionRow.StateProvinceId)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            rightRegions.Add(stateProvinceRow);
                        }
                        else
                        {
                            leftRegions.Add(stateProvinceRow);
                        }
                    }

                    RegionList.LeftDataSource  = leftRegions;
                    RegionList.RightDataSource = rightRegions;
                }
                else
                {
                    // add all regions to the left list
                    allToLeft = true;
                }
            }
            else
            {
                allToLeft = true;
            }

            if (allToLeft)
            {
                // add all regions to the left list
                RegionList.LeftDataSource = dto.StateProvince;
            }

            RegionList.DataBind();
        }
        /// <summary>
        /// Binds the countries list.
        /// </summary>
        /// <param name="shippingRow">The shipping row.</param>
        private void BindCountriesList(ShippingMethodDto.ShippingMethodRow shippingRow)
        {
            List <CountryDto.CountryRow> leftCountries  = new List <CountryDto.CountryRow>();
            List <CountryDto.CountryRow> rightCountries = new List <CountryDto.CountryRow>();

            CountryDto dto = CountryManager.GetCountries(true);

            bool allToLeft = false;             // if true, then add all countries to the left list

            if (shippingRow != null)
            {
                ShippingMethodDto.ShippingCountryRow[] restrictedCountryRows = shippingRow.GetShippingCountryRows();
                if (restrictedCountryRows != null && restrictedCountryRows.Length > 0)
                {
                    foreach (CountryDto.CountryRow countryRow in dto.Country)
                    {
                        bool found = false;
                        foreach (ShippingMethodDto.ShippingCountryRow restrictedCountryRow in restrictedCountryRows)
                        {
                            if (countryRow.CountryId == restrictedCountryRow.CountryId)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            rightCountries.Add(countryRow);
                        }
                        else
                        {
                            leftCountries.Add(countryRow);
                        }
                    }

                    CountryList.LeftDataSource  = leftCountries;
                    CountryList.RightDataSource = rightCountries;
                }
                else
                {
                    // add all countries to the left list
                    allToLeft = true;
                }
            }
            else
            {
                allToLeft = true;
            }

            if (allToLeft)
            {
                // add all countries to the left list
                CountryList.LeftDataSource = dto.Country;
            }

            CountryList.DataBind();
        }
        /// <summary>
        /// Binds the payments list.
        /// </summary>
        /// <param name="shippingRow">The shipping row.</param>
        private void BindPaymentsList(ShippingMethodDto.ShippingMethodRow shippingRow)
        {
            List <PaymentMethodDto.PaymentMethodRow> leftPayments  = new List <PaymentMethodDto.PaymentMethodRow>();
            List <PaymentMethodDto.PaymentMethodRow> rightPayments = new List <PaymentMethodDto.PaymentMethodRow>();

            PaymentMethodDto dto = PaymentManager.GetPaymentMethods(shippingRow != null ? shippingRow.LanguageId : LanguageCode, true);

            bool allToLeft = false;             // if true, then add all payments to the left list

            if (shippingRow != null)
            {
                ShippingMethodDto.ShippingPaymentRestrictionRow[] restrictedPaymentRows = shippingRow.GetShippingPaymentRestrictionRows();
                if (restrictedPaymentRows != null && restrictedPaymentRows.Length > 0)
                {
                    foreach (PaymentMethodDto.PaymentMethodRow paymentMethodRow in dto.PaymentMethod)
                    {
                        bool found = false;
                        foreach (ShippingMethodDto.ShippingPaymentRestrictionRow restrictedPaymentRow in restrictedPaymentRows)
                        {
                            if (paymentMethodRow.PaymentMethodId == restrictedPaymentRow.PaymentMethodId)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            rightPayments.Add(paymentMethodRow);
                        }
                        else
                        {
                            leftPayments.Add(paymentMethodRow);
                        }
                    }

                    PaymentsList.LeftDataSource  = leftPayments;
                    PaymentsList.RightDataSource = rightPayments;
                }
                else
                {
                    // add all payments to the left list
                    allToLeft = true;
                }
            }
            else
            {
                allToLeft = true;
            }

            if (allToLeft)
            {
                // add all payments to the left list
                PaymentsList.LeftDataSource = dto.PaymentMethod;
            }

            PaymentsList.DataBind();
        }
 private static string GetShippingMethodName(Shipment shipment)
 {
     ShippingMethodDto.ShippingMethodRow shippingMethodRow = ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                                             .ShippingMethod.Single(s => s.ShippingMethodId == shipment.ShippingMethodId);
     if (shippingMethodRow != null)
     {
         return(shippingMethodRow.DisplayName);
     }
     return(string.Empty);
 }
Esempio n. 9
0
 public static ShippingOption ToShippingOption(this ShippingMethodDto.ShippingMethodRow method)
 {
     return(new ShippingOption
     {
         Id = method.ShippingMethodId.ToString(),
         Name = method.DisplayName,
         Price = AmountHelper.GetAmount(method.BasePrice),
         PreSelected = method.IsDefault,
         TaxAmount = 0,
         TaxRate = 0,
         Description = method.Description
     });
 }
Esempio n. 10
0
        /// <summary>
        /// Processes the shipments.
        /// </summary>
        private void ProcessShipments()
        {
            ShippingMethodDto methods = ShippingManager.GetShippingMethods(Thread.CurrentThread.CurrentUICulture.Name);

            OrderGroup order = OrderGroup;

            // request rates, make sure we request rates not bound to selected delivery method
            foreach (OrderForm form in order.OrderForms)
            {
                foreach (Shipment shipment in form.Shipments)
                {
                    ShippingMethodDto.ShippingMethodRow row = methods.ShippingMethod.FindByShippingMethodId(shipment.ShippingMethodId);

                    // If shipping method is not found, set it to 0 and continue
                    if (row == null)
                    {
                        Logger.Info(String.Format("Total shipment is 0 so skip shipment calculations."));
                        shipment.ShipmentTotal = 0;
                        continue;
                    }

                    // Check if package contains shippable items, if it does not use the default shipping method instead of the one specified
                    Logger.Debug(String.Format("Getting the type \"{0}\".", row.ShippingOptionRow.ClassName));
                    Type type = Type.GetType(row.ShippingOptionRow.ClassName);
                    if (type == null)
                    {
                        throw new TypeInitializationException(row.ShippingOptionRow.ClassName, null);
                    }
                    string message = String.Empty;
                    Logger.Debug(String.Format("Creating instance of \"{0}\".", type.Name));
                    IShippingGateway provider = (IShippingGateway)Activator.CreateInstance(type);

                    List <LineItem> items = Shipment.GetShipmentLineItems(shipment);

                    Logger.Debug(String.Format("Calculating the rates."));
                    ShippingRate rate = provider.GetRate(row.ShippingMethodId, items.ToArray(), ref message);
                    if (rate != null)
                    {
                        Logger.Debug(String.Format("Rates calculated."));
                        shipment.ShipmentTotal = rate.Price;
                    }
                    else
                    {
                        Logger.Debug(String.Format("No rates has been found."));
                    }
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Updates the delivery method.
        /// </summary>
        private void UpdateDeliveryMethod()
        {
            ShippingMethodDto methods = ShippingManager.GetShippingMethods(Thread.CurrentThread.CurrentUICulture.Name);

            foreach (LineItem lineItem in CartHelper.LineItems)
            {
                if (String.Compare(lineItem.ShippingAddressId, OrderAddress.Name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (ShippingRatesList.Items.Count > 0)
                    {
                        ShippingMethodDto.ShippingMethodRow row = methods.ShippingMethod.FindByShippingMethodId(new Guid(ShippingRatesList.SelectedValue));
                        lineItem.ShippingMethodName = row.DisplayName;
                        lineItem.ShippingMethodId   = row.ShippingMethodId;
                    }
                }
            }
        }
        /// <summary>
        /// Binds the shipping config.
        /// </summary>
        private void BindShippingConfig()
        {
            if (this.phAdditionalParameters.Controls.Count > 0)
            {
                return;
            }

            if (_ShippingMethodDto != null && _ShippingMethodDto.ShippingMethod.Count > 0)
            {
                try
                {
                    ShippingMethodDto.ShippingMethodRow shippingRow = _ShippingMethodDto.ShippingMethod[0];
                    // Load dynamic configuration form
                    System.Web.UI.Control ctrl = null;
                    String mainPath            = string.Concat(_ShippingGatewayConfigurationBasePath, shippingRow.ShippingOptionRow.SystemKeyword, _ShippingGatewayConfigurationFileName);
                    if (System.IO.File.Exists(Server.MapPath(mainPath)))
                    {
                        ctrl = base.LoadControl(mainPath);
                    }
                    else
                    {
                        ctrl = base.LoadControl(string.Concat(_ShippingGatewayConfigurationBasePath, "Generic", _ShippingGatewayConfigurationFileName));
                    }

                    if (ctrl != null)
                    {
                        ctrl.ID = shippingRow.ShippingOptionRow.SystemKeyword;
                        IGatewayControl tmpCtrl = (IGatewayControl)ctrl;
                        tmpCtrl.LoadObject(_ShippingMethodDto);
                        tmpCtrl.ValidationGroup = "vg" + shippingRow.Name;

                        this.phAdditionalParameters.Controls.Add(ctrl);

                        ctrl.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage("Error during binding additional shipping method parameters: " + ex.Message);
                    return;
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Returns the package option array when method id and package that needs to be send is passed.
        /// Use passed message string to pass errors back to the application if any occured.
        /// </summary>
        /// <param name="methodId"></param>
        /// <param name="items">The items.</param>
        /// <param name="message">The message.</param>
        /// <returns>empty array if no results found</returns>
        public ShippingRate GetRate(Guid methodId, LineItem[] items, ref string message)
        {
            if (items == null || items.Length == 0)
            {
                return(null);
            }

            ShippingMethodDto methods = ShippingManager.GetShippingMethods(Thread.CurrentThread.CurrentCulture.Name);

            ShippingMethodDto.ShippingMethodRow row = methods.ShippingMethod.FindByShippingMethodId(methodId);
            if (row != null)
            {
                return(new ShippingRate(methodId, row.DisplayName, row.BasePrice, row.Currency));
            }
            else
            {
                message = "The shipping method could not be loaded.";
                return(null);
            }
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="context">The context.</param>
        public void SaveChanges(IDictionary context)
        {
            ShippingMethodDto dto = (ShippingMethodDto)context[_ShippingMethodDtoString];

            if (dto == null)
            {
                // dto must be created in base shipping control that holds tabs
                return;
            }

            ShippingMethodDto.ShippingMethodRow shippingRow = null;

            // create the row if it doesn't exist; or update its modified date if it exists
            if (dto.ShippingMethod.Count > 0)
            {
                shippingRow = dto.ShippingMethod[0];
            }
            else
            {
                return;
            }

            // 1. populate countries

            // a). delete rows from dto that are not selected
            foreach (ShippingMethodDto.ShippingCountryRow row in shippingRow.GetShippingCountryRows())
            {
                bool found = false;
                foreach (ListItem item in CountryList.RightItems)
                {
                    if (String.Compare(item.Value, row.CountryId.ToString(), true) == 0)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    row.Delete();
                }
            }

            // b). add selected rows to dto
            foreach (ListItem item in CountryList.RightItems)
            {
                bool exists = false;
                foreach (ShippingMethodDto.ShippingCountryRow row in shippingRow.GetShippingCountryRows())
                {
                    if (String.Compare(item.Value, row.CountryId.ToString(), true) == 0)
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    ShippingMethodDto.ShippingCountryRow restrictedRow = dto.ShippingCountry.NewShippingCountryRow();
                    restrictedRow.CountryId        = Int32.Parse(item.Value);
                    restrictedRow.ShippingMethodId = shippingRow.ShippingMethodId;

                    // add the row to the dto
                    dto.ShippingCountry.Rows.Add(restrictedRow);
                }
            }


            // 2. populate regions

            // a). delete rows from dto that are not selected
            foreach (ShippingMethodDto.ShippingRegionRow row in shippingRow.GetShippingRegionRows())
            {
                bool found = false;
                foreach (ListItem item in RegionList.RightItems)
                {
                    if (String.Compare(item.Value, row.StateProvinceId.ToString(), true) == 0)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    row.Delete();
                }
            }

            // b). add selected rows to dto
            foreach (ListItem item in RegionList.RightItems)
            {
                bool exists = false;
                foreach (ShippingMethodDto.ShippingRegionRow row in shippingRow.GetShippingRegionRows())
                {
                    if (String.Compare(item.Value, row.StateProvinceId.ToString(), true) == 0)
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    ShippingMethodDto.ShippingRegionRow restrictedRow = dto.ShippingRegion.NewShippingRegionRow();
                    restrictedRow.StateProvinceId  = Int32.Parse(item.Value);
                    restrictedRow.ShippingMethodId = shippingRow.ShippingMethodId;

                    // add the row to the dto
                    dto.ShippingRegion.Rows.Add(restrictedRow);
                }
            }

            // 3. populate payments restrictions

            // a). delete rows from dto that are not selected
            foreach (ShippingMethodDto.ShippingPaymentRestrictionRow row in shippingRow.GetShippingPaymentRestrictionRows())
            {
                bool found = false;
                foreach (ListItem item in PaymentsList.RightItems)
                {
                    if (String.Compare(item.Value, row.PaymentMethodId.ToString(), true) == 0 && !row.RestrictShippingMethods)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    row.Delete();
                }
            }

            // b). add selected rows to dto
            foreach (ListItem item in PaymentsList.RightItems)
            {
                bool exists = false;
                foreach (ShippingMethodDto.ShippingPaymentRestrictionRow row in shippingRow.GetShippingPaymentRestrictionRows())
                {
                    if (String.Compare(item.Value, row.PaymentMethodId.ToString(), true) == 0 && !row.RestrictShippingMethods)
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    ShippingMethodDto.ShippingPaymentRestrictionRow restrictedRow = dto.ShippingPaymentRestriction.NewShippingPaymentRestrictionRow();
                    restrictedRow.PaymentMethodId         = new Guid(item.Value);
                    restrictedRow.ShippingMethodId        = shippingRow.ShippingMethodId;
                    restrictedRow.RestrictShippingMethods = false;

                    // add the row to the dto
                    dto.ShippingPaymentRestriction.Rows.Add(restrictedRow);
                }
            }
        }
Esempio n. 15
0
        // This method is about what we ended up with in "Fund." - with a few changes done for Adv.
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // SplitPay is in a Session-variable (bool)
            string paymentProcessResult = String.Empty;

            // Load the cart, it should be one there
            var cart = _orderRepository.Load <ICart>(GetContactId(), "Default").FirstOrDefault();

            if (cart == null)
            {
                throw new InvalidOperationException("No cart found"); // make nicer
            }

            #region What actually happens when loading a cart - Adv.

            //Cart cart = OrderContext.Current.GetCart(
            //    "SomeCart"
            //    , CustomerContext.Current.CurrentContactId
            //    , MarketId.Default); // ...is still what happens in behind

            #endregion

            // should clean-up among payments here if the  first time failed - Qty 10 test
            // quick fixdon in the base class

            // From Fund
            IOrderAddress theAddress = AddAddressToOrder(cart);

            // ToDo: Added this field for Adv. & Find ... doing it simple now using one Address
            // The address is for Find, but we need to add it to MDP to be able to use it properly
            // This is a Serialized cart, so doesn't crash if the field is not added to MDP
            theAddress.Properties["AddressType"] = "Shipping";

            #region Ship & Pay from Fund

            // ToDo: Define Shipping - From Fund
            AdjustFirstShipmentInOrder(cart, theAddress, model.SelectedShipId); // ...as a Shipment is added by epi

            // ToDo: Define Payment - From Fund
            AddPaymentToOrder(cart, model.SelectedPayId); // ...as this is not added by default

            #endregion

            #region Split Pay

            // RoCe: Fix this - addSecondPayment comes in as a param (bool)
            // ... force for now if BF-Card is found ... using Session
            if ((bool)Session["SecondPayment"] == true)
            {
                ccService.AddSecondPaymentToOrder(cart);
            }

            // gathered info
            this.frontEndMessage = ccService.FrontEndMessage;

            #endregion

            // Possible change of the cart... adding this
            // would have this done if a flag were set
            var cartReference = _orderRepository.Save(cart);

            // Original Fund... (with additions)
            IPurchaseOrder purchaseOrder;
            OrderReference orderReference;

            #region Transaction Scope

            using (var scope = new Mediachase.Data.Provider.TransactionScope()) // one in BF, also
            {
                var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

                // Added - sets a lock on inventory...
                // ...could come earlier (outside tran) depending on TypeOf-"store"
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.InProgress, (item, issue) => validationIssues.Add(item, issue));

                if (validationIssues.Count >= 1)
                {
                    throw new Exception("Not possible right now"); // ...change approach
                }

                // just checking the cart in watch window
                var theShipping  = cart.GetFirstShipment();
                var theLineItems = cart.GetAllLineItems();
                var firstPayment = cart.GetFirstForm().Payments.First(); // no "GetFirstPayment()"
                var theforms     = cart.Forms;

                //_lineItemCalculator.GetDiscountedPrice()
                // second payment is added in the Trousers-Controller
                // ...fiddling with the GiftCarde as well

                // before 11
                //cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);

                // Gets the older one
                //IEnumerable<PaymentProcessingResult> theResult
                //    = cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);
                //paymentProcessResult = theResult.First().Message;

                PaymentProcessingResult otherResult =
                    _paymentProcessor.ProcessPayment(cart, cart.GetFirstForm().Payments.First(), cart.GetFirstShipment());

                frontEndMessage += otherResult.Message;

                if (otherResult.IsSuccessful)
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Processed.ToString();
                }
                else
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Failed.ToString();
                    throw new System.Exception("Bad payment"); // could have more grace
                }
                // A custom "shipping-processor" created (needs to do OldSchool-things right now)
                // Have a custom (very simple) Shipping-Provider added to the solution.
                // the processor can be cleaned up a lot, no need to show it

                // Custom thing... Error in 11... on currency... check later
                //ShippingProcessor p = new ShippingProcessor();
                //p.ProcessShipments(cart as OrderGroup); // have to go Old-school

                // ...only one form, still
                var totalProcessedAmount = cart.GetFirstForm().Payments.Where
                                               (x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

                // nice extension method
                var cartTotal = cart.GetTotal();

                // Do inventory - decrement or put back in stock
                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    // put back the reserved request
                    _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                        , OrderStatus.Cancelled, (item, issue) => validationIssues.Add(item, issue));

                    #region OldSchool Inventory - no demo,just checking ... were undocumented and wrong in SDK
                    //List<InventoryRequestItem> requestItems = new List<InventoryRequestItem>(); // holds the "items"
                    //InventoryRequestItem requestItem = new InventoryRequestItem();

                    //// calls for some logic
                    //requestItem.RequestType = InventoryRequestType.Cancel; // as a demo
                    //requestItem.OperationKey = reqKey;

                    //requestItems.Add(requestItem);

                    //InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null);
                    //InventoryResponse inventoryResponse = _invService.Service.Request(inventoryRequest);

                    //InventoryRecord rec4 = _invService.Service.Get(LI.Code, wh.Code);
                    #endregion OldSchool

                    throw new InvalidOperationException("Wrong amount"); // maybe change approach
                }

                // RoCe: have to do Promos here also ... move stuff from cart to "base"

                // simulation... should be an "else"
                cart.GetFirstShipment().OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;
                // decrement inventory and let it go
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.Completed, (item, issue) => validationIssues.Add(item, issue));

                // Should do the ClubCard thing here - ClubMembers are logged in
                // PaymentMethodName = "GiftCard"
                if (CustomerContext.Current.CurrentContact != null)
                {
                    // check if GiftCard was used, don't give bonus for that payment
                    IEnumerable <IPayment> giftCardPayment = cart.GetFirstForm().Payments.Where
                                                                 (x => x.PaymentMethodName.Equals("GiftCard"));

                    if (giftCardPayment.Count() >= 1)
                    {
                        ccService.UpdateClubCard(cart, totalProcessedAmount - giftCardPayment.First().Amount);
                    }
                    else
                    {
                        // no GiftCard, but collecting points
                        ccService.UpdateClubCard(cart, totalProcessedAmount);
                    }
                }

                #region OldSchool Inventory check

                //List<InventoryRequestItem> requestItems1 = new List<InventoryRequestItem>(); // holds the "items"
                //InventoryRequestItem requestItem1 = new InventoryRequestItem();

                //// calls for some logic
                //requestItem1.RequestType = InventoryRequestType.Complete; // as a demo
                //requestItem1.OperationKey = reqKey;

                //requestItems1.Add(requestItem1);

                //InventoryRequest inventoryRequest1 = new InventoryRequest(DateTime.UtcNow, requestItems1, null);
                //InventoryResponse inventoryResponse1 = _invService.Service.Request(inventoryRequest1);

                //InventoryRecord rec3 = _invService.Service.Get(LI.Code, wh.Code); // inventory reserved, but not decremented

                #endregion OldSchool

                orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
                _orderRepository.Delete(cart.OrderLink);

                //InventoryRecord rec5 = _invService.Service.Get(LI.Code, wh.Code); // just checking

                scope.Complete();
            } // End Tran

            #endregion

            #region JustChecking

            //Guid custLock;
            //OrderGroupLockManager.IsOrderGroupLocked(orderReference.OrderGroupId, out (Guid)CustomerContext.Current.CurrentContact.PrimaryKeyId));

            /*
             * OrderGroupLockManager.LockOrderGroup(orderReference.OrderGroupId
             *  , (Guid)CustomerContext.Current.CurrentContact.PrimaryKeyId);
             *
             * OrderGroupLockManager.UnlockOrderGroup(orderReference.OrderGroupId);
             */
            #endregion

            // just demoing (Find using this further down)
            purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            // check the below
            var theType  = purchaseOrder.OrderLink.OrderType;
            var toString = purchaseOrder.OrderLink.ToString(); // Gets ID and Type ... combined

            #region ThisAndThat - from Fund

            // should do some with OrderStatusManager

            OrderStatus poStatus;
            poStatus = purchaseOrder.OrderStatus;
            //purchaseOrder.OrderStatus = OrderStatus.InProgress;

            //var info = OrderStatusManager.GetPurchaseOrderStatus(PO);

            var shipment = purchaseOrder.GetFirstShipment();
            var status   = shipment.OrderShipmentStatus;

            //shipment. ... no that much to do
            shipment.OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

            #region Old-School, but some useful stuff

            //OrderStatusManager.ReleaseOrderShipment(purchaseOrder.GetFirstShipment() as Shipment);
            //OrderStatusManager.ReleaseOrderShipment(PO.OrderForms[0].Shipments[0]); // it gets released
            //OrderStatusManager.HoldOrder(PO); // it gets hold
            //OrderStatusManager.

            // seems to be a DTO involved... don't neeed to set the time like this... could use the new ordernote
            //OrderNotesManager.AddNoteToPurchaseOrder(PO, DateTime.UtcNow.ToShortDateString() + " done some for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            //            _orderRepository.Save(purchaseOrder); // check if it's like before ... yes it is needed to save again

            #endregion

            var notes = purchaseOrder.Notes; // IOrderNote is 0
            // RoCe - possible BUG
            // PO.OrderNotes works and contain the note above
            //IOrderNote theNewNote =
            Mediachase.Commerce.Orders.OrderNote otherNote = new OrderNote //IOrderNote
            {
                // Created = DateTime.Now, // do we need to set this ?? Nope .ctor does
                CustomerId = new Guid(), // can set this - regarded
                Detail     = "Order ToString(): " + toString + " - Shipment tracking number: " + shipment.ShipmentTrackingNumber,
                LineItemId = purchaseOrder.GetAllLineItems().First().LineItemId,
                // OrderGroupId = 12, R/O - error
                // OrderNoteId = 12, // can define it, but it's disregarded - no error
                Title = "Some title",
                Type  = OrderNoteTypes.Custom.ToString()
            };                                  // bug issued

            purchaseOrder.Notes.Add(otherNote); // void back
            purchaseOrder.ExpirationDate = DateTime.Now.AddMonths(1);


            PurchaseOrder oldPO = (PurchaseOrder)purchaseOrder;
            //oldPO.OrderAddresses.

            // yes, still need to come after adding notes
            _orderRepository.Save(purchaseOrder); // checking down here ... yes it needs to be saved again

            #endregion

            string conLang0 = ContentLanguage.PreferredCulture.Name;
            //string conLang1 = ContentLanguage.PreferredCulture.NativeName;
            //string conLang2 = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName;

            // original shipment, could rewrite and get the dto so it can be used for the second shipment also
            // or grab the dto when loading into the dropdowns
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            #region Find & Queue plumbing

            // would be done async...
            if (IsOnLine) // just checking if the below is possible, if we have network access
            {
                // index PO and addresses for BoughtThisBoughtThat & demographic analysis
                IClient     client = Client.CreateFromConfig(); // native
                FindQueries Qs     = new FindQueries(client, true);
                Qs.OrderForFind(purchaseOrder);
            }

            if (poToQueue) // could have better tran-integrity, Extraction later in PO_Extract.sln/Sheduled job
            {
                // ToDo: Put a small portion of data from the PO to msmq, will eventually (out-of-process) go to the ERP
                string       QueueName = ".\\Private$\\MyQueue";
                MessageQueue Q1        = new MessageQueue(QueueName);
                MyMessage    m         = new MyMessage()
                {
                    poNr         = purchaseOrder.OrderNumber,
                    status       = purchaseOrder.OrderStatus.ToString(),
                    orderGroupId = orderReference.OrderGroupId
                };

                Q1.Send(m);
            }

            #endregion

            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = frontEndMessage + paymentProcessResult + " - " + purchaseOrder.OrderNumber;
            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="context">The context.</param>
        public void SaveChanges(IDictionary context)
        {
            ShippingMethodDto dto = (ShippingMethodDto)context[_ShippingMethodDtoString];

            ShippingMethodDto.ShippingMethodRow row = null;

            if (dto == null)
            {
                // dto must be created in base Shipping control that holds tabs
                return;
            }

            // create the row if it doesn't exist; or update its modified date if it exists
            if (dto.ShippingMethod.Count > 0)
            {
                row = dto.ShippingMethod[0];
            }
            else
            {
                row = dto.ShippingMethod.NewShippingMethodRow();
                row.ApplicationId    = OrderConfiguration.Instance.ApplicationId;
                row.ShippingMethodId = Guid.NewGuid();
                row.Created          = DateTime.UtcNow;
                row.Name             = this.tbName.Text;
            }

            // fill the row with values
            row.Modified    = DateTime.UtcNow;
            row.DisplayName = tbFriendlyName.Text;
            row.Description = tbDescription.Text;
            Guid shippingOption = Guid.Empty;

            try
            {
                shippingOption = new Guid(ddlShippingOption.SelectedValue);
            }
            catch { }

            //add ShippingOption row in dataset for ForeignKeyConstraint requirement.
            if (row["ShippingOptionId"] != DBNull.Value && !shippingOption.Equals(row.ShippingOptionId))
            {
                string shippingOptionFilter = String.Format("ShippingOptionId = '{0}'", shippingOption);
                if (dto.ShippingOption.Select(shippingOptionFilter).Length == 0)
                {
                    string            language = ddlLanguage.SelectedValue;
                    ShippingMethodDto sm       = ShippingManager.GetShippingMethods(language, true);
                    ShippingMethodDto.ShippingOptionRow[] shippingOptionRows = (ShippingMethodDto.ShippingOptionRow[])sm.ShippingOption.Select(shippingOptionFilter);
                    if (shippingOptionRows != null && shippingOptionRows.Length > 0)
                    {
                        ShippingMethodDto.ShippingOptionRow newShippingOptionRow = dto.ShippingOption.NewShippingOptionRow();
                        newShippingOptionRow.ItemArray = shippingOptionRows[0].ItemArray;
                        dto.ShippingOption.AddShippingOptionRow(newShippingOptionRow);
                        dto.ShippingOption[dto.ShippingOption.Count - 1].AcceptChanges();
                    }
                }
            }

            row.ShippingOptionId = shippingOption;
            row.BasePrice        = decimal.Parse(tbBasePrice.Text);
            row.Currency         = ddlCurrency.SelectedValue;
            row.LanguageId       = ddlLanguage.SelectedValue;
            row.IsActive         = IsActive.IsSelected;
            row.IsDefault        = IsDefault.IsSelected;
            row.Ordering         = Int32.Parse(tbSortOrder.Text);

            // add the row to the dto
            if (row.RowState == DataRowState.Detached)
            {
                dto.ShippingMethod.Rows.Add(row);
            }
        }
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: declare a variable for CartHelper
            CartHelper ch = new CartHelper(Cart.DefaultName);

            int orderAddressId = 0;

            // ToDo: Addresses (an If-Else)
            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                orderAddressId = ch.Cart.OrderAddresses.Add(
                    new OrderAddress
                {
                    CountryCode        = "SWE",
                    CountryName        = "Sweden",
                    Name               = "SomeCustomerAddress",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                });
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress));
                }
                else
                {
                    // there is a preferred address set (and, a fourth alternative exists... do later )
                    OrderAddress orderAddress =
                        new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress);

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress);
                }
            }

            // Depending how it was created...
            OrderAddress address = ch.FindAddressById(orderAddressId.ToString());

            // ToDo: Define Shipping
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            int shippingId = ch.Cart.OrderForms[0].Shipments.Add(
                new Shipment
            {                                          // ...removing anything?
                ShippingAddressId      = address.Name, // note: use no custom prefixes
                ShippingMethodId       = theShip.ShippingMethodId,
                ShippingMethodName     = theShip.Name,
                ShipmentTotal          = theShip.BasePrice,
                ShipmentTrackingNumber = "My tracking number",
            });

            // get the Shipping ... check to see if the Shipping knows about the LineItem
            Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault();

            // First (and only) OrderForm
            LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems;

            // ...basic now... one OrderForm - one Shipping
            foreach (LineItem lineItem in lineItems)
            {
                int index = lineItems.IndexOf(lineItem);
                if ((firstOrderShipment != null) && (index != -1))
                {
                    firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity);
                }
            }


            // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object
            WorkflowResults resultPrepare     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName);
            List <string>   wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare));


            // ToDo: Define Shipping
            PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First();
            Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment));

            // ... need both below
            firstOrderPayment.Amount            = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change...
            firstOrderPayment.BillingAddressId  = address.Name;
            firstOrderPayment.PaymentMethodId   = thePay.PaymentMethodId;
            firstOrderPayment.PaymentMethodName = thePay.Name;
            // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in


            // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object
            // ...activates the gateway (same for shipping)
            WorkflowResults resultCheckout     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false);
            List <string>   wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout));
            //ch.RunWorkflow("CartValidate") ... can see this (or variations)

            string        trackingNumber = String.Empty;
            PurchaseOrder purchaseOrder  = null;

            // Add a transaction scope and convert the cart to PO
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                purchaseOrder = ch.Cart.SaveAsPurchaseOrder();
                ch.Cart.Delete();
                ch.Cart.AcceptChanges();
                trackingNumber = purchaseOrder.TrackingNumber;
                scope.Complete();
            }

            // Housekeeping below (Shipping release, OrderNotes and save the order)
            OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]);

            OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30);
            purchaseOrder.Status         = OrderStatus.InProgress.ToString();

            purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted


            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = trackingNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
Esempio n. 18
0
        /// <summary>
        /// Processes the shipments.
        /// </summary>
        private void ProcessShipments()
        {
            ShippingMethodDto methods = ShippingManager.GetShippingMethods(/*Thread.CurrentThread.CurrentUICulture.Name*/ String.Empty);

            OrderGroup order = OrderGroup;

            // request rates, make sure we request rates not bound to selected delivery method
            foreach (OrderForm form in order.OrderForms)
            {
                foreach (Shipment shipment in form.Shipments)
                {
                    bool processThisShipment = true;

                    string discountName = "@ShipmentSkipRateCalc";
                    // If you find the shipment discount which represents
                    if (shipment.Discounts.Cast <ShipmentDiscount>().Any(x => x.ShipmentId == shipment.ShipmentId && x.DiscountName.Equals(discountName)))
                    {
                        processThisShipment = false;
                    }

                    if (!processThisShipment)
                    {
                        continue;
                    }

                    ShippingMethodDto.ShippingMethodRow row = methods.ShippingMethod.FindByShippingMethodId(shipment.ShippingMethodId);

                    // If shipping method is not found, set it to 0 and continue
                    if (row == null)
                    {
                        Logger.Info(String.Format("Total shipment is 0 so skip shipment calculations."));
                        shipment.ShipmentTotal = 0;
                        continue;
                    }

                    // Check if package contains shippable items, if it does not use the default shipping method instead of the one specified
                    Logger.Debug(String.Format("Getting the type \"{0}\".", row.ShippingOptionRow.ClassName));
                    Type type = Type.GetType(row.ShippingOptionRow.ClassName);
                    if (type == null)
                    {
                        throw new TypeInitializationException(row.ShippingOptionRow.ClassName, null);
                    }
                    Logger.Debug(String.Format("Creating instance of \"{0}\".", type.Name));
                    IShippingGateway provider = null;
                    var orderMarket           = ServiceLocator.Current.GetInstance <IMarketService>().GetMarket(order.MarketId);
                    if (orderMarket != null)
                    {
                        provider = (IShippingGateway)Activator.CreateInstance(type, orderMarket);
                    }
                    else
                    {
                        provider = (IShippingGateway)Activator.CreateInstance(type);
                    }

                    Logger.Debug(String.Format("Calculating the rates."));
                    string       message = String.Empty;
                    ShippingRate rate    = provider.GetRate(row.ShippingMethodId, shipment, ref message);
                    if (rate != null)
                    {
                        Logger.Debug(String.Format("Rates calculated."));
                        // check if shipment currency is convertable to Billing currency, and then convert it
                        if (!CurrencyFormatter.CanBeConverted(rate.Money, order.BillingCurrency))
                        {
                            Logger.Debug(String.Format("Cannot convert selected shipping's currency({0}) to current currency({1}).", rate.Money.Currency.CurrencyCode, order.BillingCurrency));
                            throw new Exception(String.Format("Cannot convert selected shipping's currency({0}) to current currency({1}).", rate.Money.Currency.CurrencyCode, order.BillingCurrency));
                        }
                        else
                        {
                            Money convertedRate = CurrencyFormatter.ConvertCurrency(rate.Money, order.BillingCurrency);
                            shipment.ShipmentTotal = convertedRate.Amount;
                        }
                    }
                    else
                    {
                        Warnings[String.Concat("NoShipmentRateFound-", shipment.ShippingMethodName)] =
                            String.Concat("No rates have been found for ", shipment.ShippingMethodName);
                        Logger.Debug(String.Format("No rates have been found."));
                    }
                }
            }
        }
Esempio n. 19
0
        // older...
        //public bool IsSecondShipmentReqired(ICart cart)
        //{
        //    // this is checked both in VariationController & the CartController
        //    bool theBool = false;
        //    var lineItems = cart.GetAllLineItems();

        //    foreach (ILineItem item in lineItems)
        //    {
        //        if ((bool)item.Properties["RequireSpecialShipping"] == true)
        //        {
        //            cart.Properties["SpecialShip"] = true; // in ECF 11
        //            theBool = true;
        //            break;
        //        }
        //        else
        //        {
        //            cart.Properties["SpecialShip"] = false;
        //            theBool = false;
        //        }
        //    }

        //    return theBool;
        //}

        #endregion

        // ...for now we do it in the TrousersController (RoCe: re-write when time permits)
        // not in use yet

        /* This method is not done yet, and not in use
         * ...will consolidate all this about a forced split shipment...it's spread out now. */
        public ICart AddAnotherShipment(ICart cart, ILineItem lineItem, bool reuseAddress)
        {
            // need to check and add what shipment to use
            string forcedShipmentName = String.Empty; // ...if needed
            Guid   shippingOptionGuid = new Guid();   // for the Shipping Gateway

            // RoCe: move from the Trouser-Controller
            // Create Address & Sipment
            if (!reuseAddress)
            {
                IOrderAddress secondAddress = _orderGroupFactory.Service.CreateOrderAddress(cart);
            }
            else
            {
                IOrderAddress secondAddress = cart.GetFirstForm().Shipments.First().ShippingAddress;
            }

            //IShipment newShipment = _orderFactory.Service.CreateShipment();
            //newShipment.LineItems.Add(lineItem);


            // get the whole dto so we can try to find the ShippingOptionParameters set
            ShippingMethodDto dto = ShippingManager.GetShippingMethodsByMarket(
                _currentMarket.Service.GetCurrentMarket().MarketId.Value, false);

            var shippingOptionParam = dto.ShippingOptionParameter; // separate table - points to the Gateway

            // look for params (separate table) ... gets the gateway guid
            foreach (var item in shippingOptionParam)
            {
                if (item.Parameter == "Suspenders")             // ...a string, as illustration... to find out what Gateway/Method to use
                {
                    shippingOptionGuid = item.ShippingOptionId; // ShippingGateway ... need the id of RoyalMail set when created
                    forcedShipmentName = item.Value;
                }
            }

            // now we know what ShippingMethod to use (shippingOptionGuid)
            ShippingMethodDto.ShippingMethodRow foundShipping = null;
            foreach (var item in dto.ShippingMethod) // ECF should maybe have a method for this (if a 1:1 match is common)
            {
                if (item.ShippingOptionId == shippingOptionGuid)
                {
                    foundShipping = ShippingManager.GetShippingMethod(item.ShippingMethodId).ShippingMethod.FirstOrDefault();
                }
            }

            // could be furter granular eg. what type of method for the Gateway ... like "Standard" or "Express"
            ShippingMethodDto.ShippingMethodParameterRow[] paramRows = foundShipping.GetShippingMethodParameterRows();

            // here it just gets to the front-end as string
            if (paramRows.Count() != 0)
            {
                foreach (var item2 in paramRows) // could be here we can match lineItem with ...
                {
                    var p = item2.Parameter;
                    var v = item2.Value;
                }
            }

            return(cart); // dummy for now
        }
        /// <summary>
        /// Binds the form.
        /// </summary>
        private void BindForm()
        {
            // Bind Languages
            BindLanguages();

            string language = ddlLanguage.SelectedValue;

            // bind available Shipping gateway classes
            BindShippingOptions(language);

            // Bind Currencies
            BindCurrency();

            if (_ShippingMethodDto != null && _ShippingMethodDto.ShippingMethod.Count > 0)
            {
                try
                {
                    ShippingMethodDto.ShippingMethodRow shippingRow = _ShippingMethodDto.ShippingMethod[0];

                    this.lblShippingMethodId.Text = shippingRow.ShippingMethodId.ToString();
                    this.tbName.Text         = shippingRow.Name;
                    this.tbFriendlyName.Text = shippingRow.DisplayName;
                    try
                    {
                        this.tbDescription.Text = shippingRow.Description;
                    }
                    catch
                    {
                        this.tbDescription.Text = "";
                    }
                    this.tbBasePrice.Text = shippingRow.BasePrice.ToString("#.00", System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat);

                    try
                    {
                        this.tbSortOrder.Text = shippingRow.Ordering.ToString();
                    }
                    catch
                    {
                        this.tbSortOrder.Text = "0";
                    }

                    this.IsActive.IsSelected  = shippingRow.IsActive;
                    this.IsDefault.IsSelected = shippingRow.IsDefault;

                    ManagementHelper.SelectListItem(ddlShippingOption, shippingRow.ShippingOptionId);
                    ManagementHelper.SelectListItemIgnoreCase(ddlLanguage, shippingRow.LanguageId);
                    ManagementHelper.SelectListItemIgnoreCase(ddlCurrency, shippingRow.Currency);

                    // do not allow to change system name
                    this.tbName.Enabled = false;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage("Error during binding form: " + ex.Message);
                }
            }
            else
            {
                // set default form values
                this.tbName.Enabled   = true;
                this.tbSortOrder.Text = "0";
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Returns the package option array when method id and package that needs to be send is passed.
        /// Use passed message string to pass errors back to the application if any occured.
        /// </summary>
        /// <param name="methodId"></param>
        /// <param name="items">The items.</param>
        /// <param name="message">The message.</param>
        /// <returns>empty array if no results found</returns>
        public ShippingRate GetRate(Guid methodId, LineItem[] items, ref string message)
        {
            if (items == null || items.Length == 0)
            {
                return(null);
            }

            ShippingRate rate = null;

            ShippingMethodDto methodDto = ShippingManager.GetShippingMethod(methodId);

            if (methodDto != null && methodDto.ShippingMethod.Count > 0)
            {
                ShippingMethodDto.ShippingMethodRow method = methodDto.ShippingMethod[0];

                if (items[0].Parent != null && items[0].Parent.Parent != null)
                {
                    // find shipping address
                    OrderAddress           shippingAddress = null;
                    OrderAddressCollection addresses       = items[0].Parent.Parent.OrderAddresses;
                    foreach (OrderAddress address in addresses)
                    {
                        if (String.Compare(address.Name, items[0].ShippingAddressId, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            shippingAddress = address;
                            break;
                        }
                    }

                    if (shippingAddress != null)
                    {
                        // calculate total item weight
                        decimal weight = 0;

                        foreach (LineItem item in items)
                        {
                            if (!String.IsNullOrEmpty(item.CatalogEntryId))
                            {
                                CatalogEntryDto dto = CatalogContext.Current.GetCatalogEntryDto(item.CatalogEntryId, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));

                                if (dto.CatalogEntry.Count > 0)
                                {
                                    CatalogEntryDto.VariationRow[] variationRows = dto.CatalogEntry[0].GetVariationRows();
                                    if (variationRows != null && variationRows.Length > 0)
                                    {
                                        weight += (decimal)variationRows[0].Weight * item.Quantity;
                                    }
                                }
                            }
                        }

                        // get shipping method cases
                        DataTable casesTable = ShippingManager.GetShippingMethodCases(methodId, shippingAddress.CountryCode, shippingAddress.State,
                                                                                      shippingAddress.PostalCode, shippingAddress.RegionCode, null, shippingAddress.City, weight);

                        // get the row with the greatest weight ; the rows all contain weights less than the order weight
                        double?shippingPrice = null;
                        double maxWeight     = 0;
                        object objprice;
                        foreach (DataRow caseRow in casesTable.Rows)
                        {
                            object obj = caseRow["Total"];
                            if (obj != null && obj != DBNull.Value)
                            {
                                double rowweight = (double)obj;
                                if (maxWeight < rowweight)
                                {
                                    maxWeight = rowweight;
                                    objprice  = caseRow["Charge"];
                                    if (objprice != null && objprice != DBNull.Value)
                                    {
                                        shippingPrice = (double)objprice;
                                    }
                                }
                                else if (maxWeight == rowweight)
                                {
                                    //if the weight is the same, take the lower price
                                    objprice = caseRow["Charge"];
                                    if (objprice != null && objprice != DBNull.Value)
                                    {
                                        double newprice = (double)objprice;
                                        if ((shippingPrice == null) || (newprice < shippingPrice))
                                        {
                                            shippingPrice = newprice;
                                        }
                                    }
                                }
                            }
                        }

                        if (shippingPrice == null)
                        {
                            shippingPrice = 0;
                        }

                        rate = new ShippingRate(methodId, method.DisplayName, method.BasePrice + (decimal)shippingPrice, method.Currency);
                    }
                }
            }
            else
            {
                message = "The shipping method could not be loaded.";
                return(null);
            }

            return(rate);
        }
        // This method is about what we ended up with in "Fund." - with a few changes done for Adv.
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // SplitPay is in a Session-variable (bool)
            string paymentProcessResult = String.Empty;

            // Load the cart, it should be one there
            var cart = _orderRepository.Load <ICart>(GetContactId(), "Default").FirstOrDefault();

            if (cart == null)
            {
                throw new InvalidOperationException("No cart found"); // make nicer
            }

            // From Fund
            IOrderAddress theAddress = AddAddressToOrder(cart);

            // ToDo: Added this field for Adv. & Find ... doing it simple now using one Address
            // The address is for Find, but we need to add it to MDP to be able to use it properly
            // This is a Serialized cart, so doesn't crash if the field is not added to MDP
            theAddress.Properties["AddressType"] = "Shipping";

            #region Ship & Pay from Fund

            // ToDo: Define Shipping - From Fund
            AdjustFirstShipmentInOrder(cart, theAddress, model.SelectedShipId); // ...as a Shipment is added by epi

            // ToDo: Define Payment - From Fund
            AddPaymentToOrder(cart, model.SelectedPayId); // ...as this is not added by default

            #endregion

            #region Split Pay

            // RoCe: Fix this - addSecondPayment comes in as a param (bool)
            // ... force for now if BF-Card is found ... using Session
            if ((bool)Session["SecondPayment"] == true)
            {
                ccService.AddSecondPaymentToOrder(cart);
            }

            // gathered info
            this.frontEndMessage = ccService.FrontEndMessage;

            #endregion

            // Possible change of the cart... adding this
            // would have this done if a flag were set
            var cartReference = _orderRepository.Save(cart);

            // Original Fund... (with additions)
            IPurchaseOrder purchaseOrder;
            OrderReference orderReference;

            #region Transaction Scope

            using (var scope = new Mediachase.Data.Provider.TransactionScope()) // one in BF, also
            {
                var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

                // Added - sets a lock on inventory...
                // ...could come earlier (outside tran) depending on TypeOf-"store"
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.InProgress, (item, issue) => validationIssues.Add(item, issue));

                if (validationIssues.Count >= 1)
                {
                    throw new Exception("Not possible right now"); // ...change approach
                }

                // just checking the cart in watch window
                var theShipping  = cart.GetFirstShipment();
                var theLineItems = cart.GetAllLineItems();
                var firstPayment = cart.GetFirstForm().Payments.First(); // no "GetFirstPayment()"
                var theforms     = cart.Forms;

                PaymentProcessingResult otherResult =
                    _paymentProcessor.ProcessPayment(cart, cart.GetFirstForm().Payments.First(), cart.GetFirstShipment());

                frontEndMessage += otherResult.Message;

                if (otherResult.IsSuccessful)
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Processed.ToString();
                }
                else
                {
                    IPayment thePay = cart.GetFirstForm().Payments.First();
                    thePay.Status = PaymentStatus.Failed.ToString();
                    throw new System.Exception("Bad payment"); // could have more grace
                }

                // ...only one form, still
                var totalProcessedAmount = cart.GetFirstForm().Payments.Where
                                               (x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

                // nice extension method
                var cartTotal = cart.GetTotal();

                // Do inventory - decrement or put back in stock
                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    // put back the reserved request
                    _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                        , OrderStatus.Cancelled, (item, issue) => validationIssues.Add(item, issue));

                    throw new InvalidOperationException("Wrong amount"); // maybe change approach
                }

                // RoCe: have to do Promos here also ... move stuff from cart to "base"
                // simulation... should be an "else"
                cart.GetFirstShipment().OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

                // decrement inventory and let it go
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.Completed, (item, issue) => validationIssues.Add(item, issue));

                // Should do the ClubCard thing here - ClubMembers are logged in
                // PaymentMethodName = "GiftCard"
                if (CustomerContext.Current.CurrentContact != null)
                {
                    // check if GiftCard was used, don't give bonus for that payment
                    IEnumerable <IPayment> giftCardPayment = cart.GetFirstForm().Payments.Where
                                                                 (x => x.PaymentMethodName.Equals("GiftCard"));

                    if (giftCardPayment.Count() >= 1)
                    {
                        ccService.UpdateClubCard(cart, totalProcessedAmount - giftCardPayment.First().Amount);
                    }
                    else
                    {
                        // no GiftCard, but collecting points
                        ccService.UpdateClubCard(cart, totalProcessedAmount);
                    }
                }

                orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
                _orderRepository.Delete(cart.OrderLink);

                scope.Complete();
            } // End Tran

            #endregion

            // just demoing (Find using this further down)
            purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            // check the below
            var theType  = purchaseOrder.OrderLink.OrderType;
            var toString = purchaseOrder.OrderLink.ToString(); // Gets ID and Type ... combined

            #region ThisAndThat - from Fund

            OrderStatus poStatus;
            poStatus = purchaseOrder.OrderStatus;
            //purchaseOrder.OrderStatus = OrderStatus.InProgress;

            //var info = OrderStatusManager.GetPurchaseOrderStatus(PO);

            var shipment = purchaseOrder.GetFirstShipment();
            var status   = shipment.OrderShipmentStatus;

            //shipment. ... no that much to do
            shipment.OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

            var notes = purchaseOrder.Notes; // IOrderNote is 0

            // have getters & setters... not good
            Mediachase.Commerce.Orders.OrderNote otherNote = new OrderNote //IOrderNote
            {
                // Created = DateTime.Now, // do we need to set this ?? Nope .ctor does
                CustomerId = new Guid(), // can set this - regarded
                Detail     = "Order ToString(): " + toString + " - Shipment tracking number: " + shipment.ShipmentTrackingNumber,
                LineItemId = purchaseOrder.GetAllLineItems().First().LineItemId,
                // OrderGroupId = 12, R/O - error
                // OrderNoteId = 12, // can define it, but it's disregarded - no error
                Title = "Some title",
                Type  = OrderNoteTypes.Custom.ToString()
            };                                  // bug issued

            purchaseOrder.Notes.Add(otherNote); // void back
            purchaseOrder.ExpirationDate = DateTime.Now.AddMonths(1);

            // yes, still need to come after adding notes
            _orderRepository.Save(purchaseOrder); // checking down here ... yes it needs to be saved again

            #endregion

            string conLang0 = ContentLanguage.PreferredCulture.Name;

            // original shipment, could rewrite and get the dto so it can be used for the second shipment also
            // or grab the dto when loading into the dropdowns
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            #region Find & Queue plumbing

            // would be done async...
            if (IsOnLine) // just checking if the below is possible, if we have network access
            {
                // index PO and addresses for BoughtThisBoughtThat & demographic analysis
                IClient     client = Client.CreateFromConfig(); // native
                FindQueries Qs     = new FindQueries(client, true);
                Qs.OrderForFind(purchaseOrder);
            }

            if (poToQueue) // could have better tran-integrity, Extraction later in PO_Extract.sln/Sheduled job
            {
                // ToDo: Put a small portion of data from the PO to msmq, will eventually (out-of-process) go to the ERP
                string       QueueName = ".\\Private$\\MyQueue";
                MessageQueue Q1        = new MessageQueue(QueueName);
                MyMessage    m         = new MyMessage()
                {
                    poNr         = purchaseOrder.OrderNumber,
                    status       = purchaseOrder.OrderStatus.ToString(),
                    orderGroupId = orderReference.OrderGroupId
                };

                Q1.Send(m);
            }

            #endregion

            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = frontEndMessage + paymentProcessResult + " - " + purchaseOrder.OrderNumber;
            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }