Example #1
0
        /// <summary>
        /// Change shipping method
        /// </summary>
        protected void ChangeShippingMethod()
        {
            string shippingMethodId = string.Empty;

            foreach (ListViewDataItem item in shippingOptions.Items)
            {
                var rdo = item.FindControl("rdoChooseShipping") as GlobalRadioButton;
                if (rdo != null)
                {
                    if (rdo.Checked)
                    {
                        var hidden = item.FindControl("hiddenShippingId") as HtmlInputControl;
                        if (hidden != null)
                        {
                            shippingMethodId = hidden.Value;
                            break;
                        }
                    }
                }
            }

            Shipment.ShippingMethodId = new Guid(shippingMethodId);

            // restore coupon code to context
            string couponCode = Session[Constants.LastCouponCode] as string;

            if (!String.IsNullOrEmpty(couponCode))
            {
                MarketingContext.Current.AddCouponToMarketingContext(couponCode);
            }

            //Calculate shipping, disocunts, totals, etc
            OrderGroupWorkflowManager.RunWorkflow(Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);
            Cart.AcceptChanges();
        }
Example #2
0
        private void ValidateCart(out string warningMessage, CartHelper cart)
        {
            var workflowResult = OrderGroupWorkflowManager.RunWorkflow(cart.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
            var warnings       = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(workflowResult).ToArray();

            warningMessage = warnings.Any() ? String.Join(" ", warnings) : null;
        }
        protected override void DoCommand(IOrderGroup order, CommandParameters cp)
        {
            Mediachase.Ibn.Web.UI.CHelper.RequireDataBind();
            PurchaseOrder   purchaseOrder   = order as PurchaseOrder;
            WorkflowResults workflowResults = OrderGroupWorkflowManager.RunWorkflow(purchaseOrder, "SaveChangesWorkflow",
                                                                                    false,
                                                                                    false,
                                                                                    new Dictionary <string, object>
            {
                {
                    "PreventProcessPayment",
                    !string.IsNullOrEmpty(order.Properties["QuoteStatus"] as string) &&
                    (order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotation ||
                     order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotationFinished)
                }
            });

            if (workflowResults.Status != WorkflowStatus.Completed)
            {
                string msg = "Unknow error";
                if (workflowResults.Exception != null)
                {
                    msg = workflowResults.Exception.Message;
                }
                ErrorManager.GenerateError(msg);
            }
            else
            {
                WritePurchaseOrderChangeNotes(purchaseOrder);
                SavePurchaseOrderChanges(purchaseOrder);
                PurchaseOrderManager.UpdatePromotionUsage(purchaseOrder, purchaseOrder);
                OrderHelper.ExitPurchaseOrderFromEditMode(purchaseOrder.OrderGroupId);
            }
        }
Example #4
0
        public ActionResult Index()
        {
            var receiptPage = _contentRepository.Get <ReceiptPage>(_siteConfiguration.GetSettings().ReceiptPage);

            var cartHelper = new CartHelper(Cart.DefaultName);

            if (cartHelper.IsEmpty && !PageEditing.PageIsInEditMode)
            {
                return(View("Error/_EmptyCartError"));
            }

            string         message        = "";
            OrderViewModel orderViewModel = null;

            if (cartHelper.Cart.OrderForms.Count > 0)
            {
                var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

                _log.Debug("Order placed - order number: " + orderNumber);

                cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

                System.Diagnostics.Trace.WriteLine("Running Workflow: " + OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

                if (message.Length == 0)
                {
                    cartHelper.Cart.SaveAsPurchaseOrder();
                    cartHelper.Cart.Delete();
                    cartHelper.Cart.AcceptChanges();
                }

                System.Diagnostics.Trace.WriteLine("Loading Order: " + orderNumber);
                var order = _orderService.GetOrderByTrackingNumber(orderNumber);

                // Must be run after order is complete,
                // This might release the order for shipment and
                // send the order receipt by email
                System.Diagnostics.Trace.WriteLine(string.Format("Process Completed Payment: {0} (User: {1})", orderNumber, User.Identity.Name));
                _paymentCompleteHandler.ProcessCompletedPayment(order, User.Identity);

                orderViewModel = new OrderViewModel(_currentMarket.GetCurrentMarket().DefaultCurrency.Format, order);
            }

            ReceiptViewModel model = new ReceiptViewModel(receiptPage);

            model.CheckoutMessage = message;
            model.Order           = orderViewModel;

            // Track successfull order in Google Analytics
            TrackAfterPayment(model);

            _metricsLoggingService.Count("Purchase", "Purchase Success");
            _metricsLoggingService.Count("Payment", "Generic");

            return(View("ReceiptPage", model));
        }
        /// <summary>
        /// Validates and completes a cart.
        /// </summary>
        /// <param name="cart">The cart.</param>
        /// <param name="errorMessages">The error messages.</param>
        public virtual bool DoCompletingCart(ICart cart, IList <string> errorMessages)
        {
            // Change status of payments to processed.
            // It must be done before execute workflow to ensure payments which should mark as processed.
            // To avoid get errors when executed workflow.
            foreach (IPayment p in cart.Forms.SelectMany(f => f.Payments).Where(p => p != null))
            {
                PaymentStatusManager.ProcessPayment(p);
            }

            var isSuccess = true;

            if (_databaseMode.Value != DatabaseMode.ReadOnly)
            {
                if (_featureSwitch.IsSerializedCartsEnabled())
                {
                    var validationIssues = new Dictionary <ILineItem, IList <ValidationIssue> >();
                    cart.AdjustInventoryOrRemoveLineItems(
                        (item, issue) => AddValidationIssues(validationIssues, item, issue), _inventoryProcessor);

                    isSuccess = !validationIssues.Any();

                    foreach (var issue in validationIssues.Values.SelectMany(x => x).Distinct())
                    {
                        if (issue == ValidationIssue.RejectedInventoryRequestDueToInsufficientQuantity)
                        {
                            errorMessages.Add("NotEnoughStockWarning");
                        }
                        else
                        {
                            errorMessages.Add("CartValidationWarning");
                        }
                    }

                    return(isSuccess);
                }

                // Execute CheckOutWorkflow with parameter to ignore running process payment activity again.
                var isIgnoreProcessPayment = new Dictionary <string, object> {
                    { "PreventProcessPayment", true }
                };
                var workflowResults = OrderGroupWorkflowManager.RunWorkflow((OrderGroup)cart,
                                                                            OrderGroupWorkflowManager.CartCheckOutWorkflowName, true, isIgnoreProcessPayment);

                var warnings = workflowResults.OutputParameters["Warnings"] as StringDictionary;
                isSuccess = warnings.Count == 0;

                foreach (string message in warnings.Values)
                {
                    errorMessages.Add(message);
                }
            }

            return(isSuccess);
        }
Example #6
0
        /// <summary>
        /// Places the order.
        /// </summary>
        protected void PlaceOrder()
        {
            MergeShipment();

            // Make sure to execute within transaction
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                try
                {
                    OrderGroupWorkflowManager.RunWorkflow(Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                }
                catch (Exception ex)
                {
                    if (ex is PaymentException)
                    {
                        throw ex;
                    }
                    else if (ex.InnerException != null && ex.InnerException is PaymentException)
                    {
                        throw ex.InnerException;
                    }
                }

                Cart.CustomerId = SecurityContext.Current.CurrentUserId;
                var po = Cart.SaveAsPurchaseOrder();

                if (_currentContact != null)
                {
                    _currentContact.LastOrder = po.Created;
                    _currentContact.SaveChanges();
                    Cart.CustomerName = _currentContact.FullName;
                }

                // Add note to purchaseOrder
                AddNoteToPurchaseOrder("New order placed by {0} in {1}", po, SecurityContext.Current.CurrentUserName, "Public site");
                po.AcceptChanges();

                PurchaseOrderManager.UpdatePromotionUsage(Cart, po);

                // Save latest order id
                Session[SessionLatestOrderIdKey]     = po.OrderGroupId;
                Session[SessionLatestOrderNumberKey] = po.TrackingNumber;
                Session[SessionLatestOrderTotalKey]  = new Money(po.Total, po.BillingCurrency).ToString();

                // Increase the coressponding KPI in CMO.
                IncreaseKpi();

                // Remove old cart
                Cart.Delete();
                Cart.AcceptChanges();

                // Commit changes
                scope.Complete();
            }
        }
Example #7
0
        private void ValidateCart(out string warningMessage)
        {
            if (_cartName == Mediachase.Commerce.Website.Helpers.CartHelper.WishListName)
            {
                warningMessage = null;
                return;
            }

            var workflowResult = OrderGroupWorkflowManager.RunWorkflow(CartHelper.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
            var warnings       = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(workflowResult).ToArray();

            warningMessage = warnings.Any() ? String.Join(" ", warnings) : null;
        }
Example #8
0
        public void ApplyPayment()
        {
            var paymentMethod = PaymentManager.GetPaymentMethod(Constants.PaymentMethodId).PaymentMethod.Single();
            var orderForm     = _helper.Cart.OrderForms.Single();
            var payment       = orderForm.Payments.AddNew(typeof(OtherPayment));

            payment.PaymentMethodId   = paymentMethod.PaymentMethodId;
            payment.PaymentMethodName = paymentMethod.Name;
            payment.Amount            = _helper.Cart.Total;
            payment.TransactionType   = TransactionType.Other.ToString();
            OrderGroupWorkflowManager.RunWorkflow(_helper.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);
            OrderGroupWorkflowManager.RunWorkflow(_helper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            _helper.Cart.AcceptChanges();
        }
Example #9
0
        public DibsPaymentProcessingResult ProcessPaymentResult(DibsPaymentResult result, IIdentity identity)
        {
            var cartHelper = new CartHelper(Cart.DefaultName);

            if (cartHelper.Cart.OrderForms.Count == 0)
            {
                return(null);
            }
            var cart    = cartHelper.Cart;
            var payment = cart.OrderForms[0].Payments[0] as DibsPayment;

            if (payment != null)
            {
                payment.CardNumberMasked = result.CardNumberMasked;
                payment.CartTypeName     = result.CardTypeName;
                payment.TransactionID    = result.Transaction;
                payment.TransactionType  = TransactionType.Authorization.ToString();
                payment.Status           = result.Status;
                cartHelper.Cart.Status   = DIBSPaymentGateway.PaymentCompleted;
            }
            else
            {
                throw new Exception("Not a DIBS Payment");
            }

            var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

            Log.Debug("Order placed - order number: " + orderNumber);

            cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

            var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            var message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

            if (message.Length == 0)
            {
                cartHelper.Cart.SaveAsPurchaseOrder();
                cartHelper.Cart.Delete();
                cartHelper.Cart.AcceptChanges();
            }

            var order = _orderService.GetOrderByTrackingNumber(orderNumber);

            // Must be run after order is complete,
            // This will release the order for shipment and
            // send the order receipt by email
            _paymentCompleteHandler.ProcessCompletedPayment(order, identity);

            return(new DibsPaymentProcessingResult(order, message));
        }
Example #10
0
        public ActionResult SaveAsPaymentPlan(int orderid, int cycleMode, int cycleLength)
        {
            var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderid);

            if (purchaseOrder == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }

            var cart = _orderRepository.Create <ICart>(Guid.NewGuid().ToString());

            cart.CopyFrom(purchaseOrder, _orderGroupFactory);
            var orderReference = _orderRepository.SaveAsPaymentPlan(cart);

            _orderRepository.Delete(cart.OrderLink);
            var paymentPlan = _orderRepository.Load <IPaymentPlan>(orderReference.OrderGroupId);

            paymentPlan.CycleMode   = (PaymentPlanCycle)cycleMode;
            paymentPlan.CycleLength = cycleLength;
            paymentPlan.StartDate   = DateTime.UtcNow;
            paymentPlan.IsActive    = true;

            var principal = PrincipalInfo.CurrentPrincipal;

            AddNoteToOrder(paymentPlan, $"Note: New payment plan placed by {principal.Identity.Name}.", OrderNoteTypes.System, principal.GetContactId());
            paymentPlan.AdjustInventoryOrRemoveLineItems((__, _) => { });
            _orderRepository.Save(paymentPlan);

            //create first order
            orderReference = _orderRepository.SaveAsPurchaseOrder(paymentPlan);
            var newPurchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            OrderGroupWorkflowManager.RunWorkflow((OrderGroup)newPurchaseOrder, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            var noteDetailPattern = "New purchase order placed by {0} in {1} from payment plan {2}";
            var noteDetail        = string.Format(noteDetailPattern, principal.Identity.Name, "VNext site", (paymentPlan as PaymentPlan).Id);

            AddNoteToOrder(newPurchaseOrder, noteDetail, OrderNoteTypes.System, principal.GetContactId());
            _orderRepository.Save(newPurchaseOrder);

            paymentPlan.LastTransactionDate = DateTime.UtcNow;
            paymentPlan.CompletedCyclesCount++;
            _orderRepository.Save(paymentPlan);

            var paymentPlanPageUrl = Url.ContentUrl(_settingsService.GetSiteSettings <ReferencePageSettings>()?.PaymentPlanDetailsPage ?? ContentReference.StartPage)
                                     + $"?paymentPlanId={paymentPlan.OrderLink.OrderGroupId}";

            return(Redirect(paymentPlanPageUrl));
        }
Example #11
0
        /// <summary>
        /// Change shipping method
        /// </summary>
        protected void ChangeShippingMethod()
        {
            var shippingMethodId = string.Empty;

            foreach (var item in shippingOptions.Items)
            {
                var rdo = item.FindControl("rdoChooseShipping") as GlobalRadioButton;
                if (rdo == null)
                {
                    continue;
                }
                if (!rdo.Checked)
                {
                    continue;
                }

                var hidden = item.FindControl("hiddenShippingId") as HtmlInputControl;
                if (hidden == null)
                {
                    continue;
                }

                shippingMethodId = hidden.Value;
                break;
            }

            var ship = _cartHelper.Cart.OrderForms[0].Shipments.ToArray().FirstOrDefault(s => s.Id == SplitShipment.Id);

            var dto = ShippingManager.GetShippingMethod(new Guid(shippingMethodId));

            if (dto != null || dto.ShippingMethod != null || dto.ShippingMethod.Count > 0)
            {
                ship.ShippingMethodId   = dto.ShippingMethod[0].ShippingMethodId;
                ship.ShippingMethodName = dto.ShippingMethod[0].Name;
            }

            // restore coupon code to context
            string couponCode = Session[Constants.LastCouponCode] as string;

            if (!String.IsNullOrEmpty(couponCode))
            {
                MarketingContext.Current.AddCouponToMarketingContext(couponCode);
            }

            //Calculate shipping, discounts, totals, etc
            OrderGroupWorkflowManager.RunWorkflow(_cartHelper.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);
            _cartHelper.Cart.AcceptChanges();
        }
Example #12
0
        /// <summary>
        /// Validates and completes a cart.
        /// </summary>
        /// <param name="cart">The cart.</param>
        /// <param name="errorMessages">The error messages.</param>
        private bool DoCompletingCart(ICart cart, IList <string> errorMessages)
        {
            var isSuccess = true;

            if (_databaseMode.Value != DatabaseMode.ReadOnly)
            {
                if (_featureSwitch.IsSerializedCartsEnabled())
                {
                    var validationIssues = new Dictionary <ILineItem, IList <ValidationIssue> >();
                    cart.AdjustInventoryOrRemoveLineItems(
                        (item, issue) => AddValidationIssues(validationIssues, item, issue), _inventoryProcessor);

                    isSuccess = !validationIssues.Any();

                    foreach (var issue in validationIssues.Values.SelectMany(x => x).Distinct())
                    {
                        if (issue == ValidationIssue.RejectedInventoryRequestDueToInsufficientQuantity)
                        {
                            errorMessages.Add(Utilities.Translate("NotEnoughStockWarning"));
                        }
                        else
                        {
                            errorMessages.Add(Utilities.Translate("CartValidationWarning"));
                        }
                    }

                    return(isSuccess);
                }

                // Execute CheckOutWorkflow with parameter to ignore running process payment activity again.
                var isIgnoreProcessPayment = new Dictionary <string, object> {
                    { "PreventProcessPayment", true }
                };
                var workflowResults = OrderGroupWorkflowManager.RunWorkflow((OrderGroup)cart,
                                                                            OrderGroupWorkflowManager.CartCheckOutWorkflowName, true, isIgnoreProcessPayment);

                var warnings = workflowResults.OutputParameters["Warnings"] as StringDictionary;
                isSuccess = warnings.Count == 0;

                foreach (string message in warnings.Values)
                {
                    errorMessages.Add(message);
                }
            }

            return(isSuccess);
        }
Example #13
0
        public static string RunWorkflowAndReturnFormattedMessage(Cart cart, string workflowName)
        {
            WorkflowResults      results         = cart.RunWorkflow(workflowName);
            IEnumerable <string> resultsMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results);
            string returnString = string.Empty;

            if (resultsMessages.Count() > 0)
            {
                returnString = "Workflow Messages: ";
                foreach (string result in resultsMessages)
                {
                    returnString += result + "<BR />";
                }
            }

            return(returnString);
        }
Example #14
0
        public ActionResult Index()
        {
            var receiptPage = _contentRepository.Get <ReceiptPage>(_siteConfiguration.GetSettings().ReceiptPage);

            var            cartHelper     = new CartHelper(Cart.DefaultName);
            string         message        = "";
            OrderViewModel orderViewModel = null;

            if (cartHelper.Cart.OrderForms.Count > 0)
            {
                var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

                _log.Debug("Order placed - order number: " + orderNumber);

                cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

                var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

                if (message.Length == 0)
                {
                    cartHelper.Cart.SaveAsPurchaseOrder();
                    cartHelper.Cart.Delete();
                    cartHelper.Cart.AcceptChanges();
                }

                var order = _orderService.GetOrderByTrackingNumber(orderNumber);

                // Must be run after order is complete,
                // This will release the order for shipment and
                // send the order receipt by email
                _paymentCompleteHandler.ProcessCompletedPayment(order, User.Identity);

                orderViewModel = new OrderViewModel(_currentMarket.GetCurrentMarket().DefaultCurrency.Format, order);
            }

            ReceiptViewModel model = new ReceiptViewModel(receiptPage);

            model.CheckoutMessage = message;
            model.Order           = orderViewModel;

            // Track successfull order in Google Analytics
            TrackAfterPayment(model);

            return(View("ReceiptPage", model));
        }
Example #15
0
        protected virtual bool DoCompletingCart(ICart cart, IList <string> errorMessages)
        {
            var isSuccess = true;

            if (_featureSwitch.IsSerializedCartsEnabled())
            {
                var validationIssues = new Dictionary <ILineItem, IList <ValidationIssue> >();
                cart.AdjustInventoryOrRemoveLineItems(
                    (item, issue) => AddValidationIssues(validationIssues, item, issue), _inventoryProcessor);

                isSuccess = !validationIssues.Any();

                foreach (var issue in validationIssues.Values.SelectMany(x => x).Distinct())
                {
                    if (issue == ValidationIssue.RemovedDueToInsufficientQuantityInInventory)
                    {
                        errorMessages.Add("Not enough in stock.");
                    }
                    else
                    {
                        errorMessages.Add("Cart validation failure.");
                    }
                }

                return(isSuccess);
            }

            var isIgnoreProcessPayment = new Dictionary <string, object> {
                { "PreventProcessPayment", true }
            };
            var workflowResults = OrderGroupWorkflowManager.RunWorkflow((OrderGroup)cart,
                                                                        OrderGroupWorkflowManager.CartCheckOutWorkflowName, true, isIgnoreProcessPayment);

            if (workflowResults.OutputParameters["Warnings"] is StringDictionary warnings)
            {
                isSuccess = warnings.Count == 0;

                foreach (string message in warnings.Values)
                {
                    errorMessages.Add(message);
                }
            }

            return(isSuccess);
        }
Example #16
0
        public static string RunWorkflowAndReturnFormattedMessage(Cart cart, string workflowName)
        {
            string returnString = string.Empty;

            // TODO: Be aware of this magic string that the workflow requires
            cart.ProviderId = "FrontEnd";
            WorkflowResults results         = cart.RunWorkflow(workflowName);
            var             resultsMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results);

            if (resultsMessages.Count() > 0)
            {
                returnString = "";
                foreach (string result in resultsMessages)
                {
                    returnString += result + "<br />";
                }
            }
            return(returnString);
        }
Example #17
0
        protected override void DoCommand(IOrderGroup order, CommandParameters cp)
        {
            Mediachase.Ibn.Web.UI.CHelper.RequireDataBind();
            var purchaseOrder   = order as PurchaseOrder;
            var workflowResults = OrderGroupWorkflowManager.RunWorkflow(purchaseOrder, "SaveChangesWorkflow",
                                                                        false,
                                                                        //false,
                                                                        new Dictionary <string, object>
            {
                {
                    "PreventProcessPayment",
                    !string.IsNullOrEmpty(order.Properties["QuoteStatus"] as string) &&
                    (order.Properties["QuoteStatus"].ToString() == RequestQuotation ||
                     order.Properties["QuoteStatus"].ToString() == RequestQuotationFinished)
                }
            });

            if (workflowResults.Status != WorkflowStatus.Completed)
            {
                var msg = "Unknow error";
                if (workflowResults.Exception != null)
                {
                    msg = workflowResults.Exception.Message;
                }

                ErrorManager.GenerateError(msg);
            }
            else
            {
                WriteOrderChangeNotes(purchaseOrder);
                SavePurchaseOrderChanges(purchaseOrder);
                OrderHelper.ExitPurchaseOrderFromEditMode(purchaseOrder.OrderGroupId);
            }

            var warnings = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(workflowResults);

            if (warnings.Any())
            {
                CommandHandlerHelper.ShowStatusMessage(string.Join(", ", warnings), CommandManager);
            }
        }
Example #18
0
        /// <summary>
        /// Save cart as payment plan
        /// </summary>
        /// <param name="cart"></param>
        private OrderReference SaveAsPaymentPlan(ICart cart)
        {
            var orderReference     = _orderRepository.SaveAsPaymentPlan(cart);
            var paymentPlanSetting = cart.Properties["PaymentPlanSetting"] as PaymentPlanSetting;

            IPaymentPlan paymentPlan;

            paymentPlan             = _orderRepository.Load <IPaymentPlan>(orderReference.OrderGroupId);
            paymentPlan.CycleMode   = PaymentPlanCycle.Days;
            paymentPlan.CycleLength = paymentPlanSetting.CycleLength;
            paymentPlan.StartDate   = DateTime.Now.AddDays(paymentPlanSetting.CycleLength);
            paymentPlan.EndDate     = paymentPlanSetting.EndDate;
            paymentPlan.IsActive    = paymentPlanSetting.IsActive;

            var principal = PrincipalInfo.CurrentPrincipal;

            AddNoteToCart(paymentPlan, $"Note: New payment plan placed by {principal.Identity.Name} in 'vnext site'.", OrderNoteTypes.System.ToString(), principal.GetContactId());

            _orderRepository.Save(paymentPlan);

            paymentPlan.AdjustInventoryOrRemoveLineItems((item, validationIssue) => { });
            _orderRepository.Save(paymentPlan);

            //create first order
            orderReference = _orderRepository.SaveAsPurchaseOrder(paymentPlan);
            var purchaseOrder = _orderRepository.Load(orderReference);

            OrderGroupWorkflowManager.RunWorkflow((OrderGroup)purchaseOrder, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            var noteDetailPattern = "New purchase order placed by {0} in {1} from payment plan {2}";
            var noteDetail        = string.Format(noteDetailPattern, ManagementHelper.GetUserName(PrincipalInfo.CurrentPrincipal.GetContactId()), "VNext site", (paymentPlan as PaymentPlan).Id);

            AddNoteToPurchaseOrder(purchaseOrder as IPurchaseOrder, noteDetail, OrderNoteTypes.System, PrincipalInfo.CurrentPrincipal.GetContactId());
            _orderRepository.Save(purchaseOrder);

            paymentPlan.LastTransactionDate = DateTime.UtcNow;
            paymentPlan.CompletedCyclesCount++;
            _orderRepository.Save(paymentPlan);

            return(orderReference);
        }
        public ActionResult Index(CartPage currentPage)
        {
            // (added for D2)
            if (ch.LineItems.Count() == 0) // cart could exist but not containing LineItems? ... gets the "Index Out Of Range" then
            {
                wfMessages.Add("No LineItems");

                var model = new CartViewModel // using a bit of it
                {
                    //lineItems = new List<LineItem>(),
                    //cartTotal = "0",
                    messages = wfMessages
                };

                //return View(model);
                return(View("NoCart", model));
            }
            else
            {
                // ToDo: (lab D2)
                //WorkflowResults result = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartValidateWorkflowName);
                WorkflowResults result = OrderGroupWorkflowManager.RunWorkflow
                                             (ch.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);

                //List<string> wfMessages = new List<string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(result));
                wfMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(result).ToList();

                ch.Cart.AcceptChanges();

                var model = new CartViewModel
                {
                    lineItems = ch.LineItems,
                    cartTotal = ch.Cart.Total.ToString("C"),
                    messages  = wfMessages
                };

                return(View(model));
            }
        }
Example #20
0
        public ActionResult ProcessPayment(DibsPaymentPage currentPage, DibsPaymentResult result)
        {
            ReceiptPage receiptPage = _contentRepository.Get <ReceiptPage>(_siteConfiguration.GetSettings().ReceiptPage);

            if (_log.IsDebugEnabled())
            {
                _log.Debug("Payment processed: {0}", result);
            }

            CartHelper     cartHelper     = new CartHelper(Cart.DefaultName);
            string         message        = "";
            OrderViewModel orderViewModel = null;

            if (cartHelper.Cart.OrderForms.Count > 0)
            {
                var payment = cartHelper.Cart.OrderForms[0].Payments[0] as DibsPayment;

                if (payment != null)
                {
                    payment.CardNumberMasked = result.CardNumberMasked;
                    payment.CartTypeName     = result.CardTypeName;
                    payment.TransactionID    = result.Transaction;
                    payment.TransactionType  = TransactionType.Authorization.ToString();
                    payment.Status           = result.Status;
                    cartHelper.Cart.Status   = DIBSPaymentGateway.PaymentCompleted;
                }
                else
                {
                    throw new Exception("Not a DIBS Payment");
                }

                var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

                _log.Debug("Order placed - order number: " + orderNumber);

                cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

                var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

                if (message.Length == 0)
                {
                    cartHelper.Cart.SaveAsPurchaseOrder();
                    cartHelper.Cart.Delete();
                    cartHelper.Cart.AcceptChanges();
                }

                var order = _orderService.GetOrderByTrackingNumber(orderNumber);

                // Must be run after order is complete,
                // This will release the order for shipment and
                // send the order receipt by email
                _paymentCompleteHandler.ProcessCompletedPayment(order, User.Identity);

                orderViewModel = new OrderViewModel(_currentMarket.GetCurrentMarket().DefaultCurrency.Format, order);
            }

            ReceiptViewModel model = new ReceiptViewModel(receiptPage);

            model.CheckoutMessage = message;
            model.Order           = orderViewModel;

            // Track successfull order in Google Analytics
            TrackAfterPayment(model);

            return(View("ReceiptPage", model));
        }
        public void CheckOnCalc() // (Cart theCart, Guid id)
        {
            Cart theCart = LoadOrCreateCart();

            //CartHelper ch = new CartHelper(theCart); // lazy now
            if (theCart.OrderForms[0].LineItems.Count() > 0) // before WF-exec
            {
                // Do calc
            }
            else // just looking
            {
                // add a LineItem
                //ILineItem lineItem = new // nope
                //_oRep.Service. // nope nothing about LineItems
                // seems to need "OldSchool" ... doing it lazy for now
                //ch.AddEntry(CatalogContext.Current.GetCatalogEntry("Some-Sox_1")); // have a look at "LoadOrCreateCart"

                ContentReference theRef     = _refConv.GetContentLink("Long-Sleeve-Shirt-White-Small_1");
                VariationContent theContent = _contentLoader.Get <VariationContent>(theRef);
                LineItem         li         = CreateLineItem(theContent, 2, 22);

                var orderForm = theCart.OrderForms.First();
                orderForm.LineItems.Add(li);
                var index = orderForm.LineItems.IndexOf(li);
                theCart.OrderForms.First().Shipments.First().AddLineItemIndex(index, li.Quantity);
            }

            // just checking
            WorkflowResults wfResult = OrderGroupWorkflowManager.RunWorkflow
                                           (theCart, OrderGroupWorkflowManager.CartValidateWorkflowName);

            IMarket  market = _currentMarket.GetCurrentMarket();
            Currency curr   = theCart.BillingCurrency; // og.Currency;

            Guid        id   = new Guid("097361ec-a4ac-4671-9f2a-a56e3b6f7e97");
            IOrderGroup og   = _oRep.Service.Load(id, theCart.Name).FirstOrDefault();
            IOrderForm  form = og.Forms.FirstOrDefault();
            IShipment   ship = form.Shipments.FirstOrDefault(); // there is a shipment there (...is a "bigger change")

            //CartHelper ch = new CartHelper((Cart)og);
            int liId = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault().LineItemId; // okay

            Shipment otherShip = theCart.OrderForms[0].Shipments.FirstOrDefault();            // no ship here...?
            // it's not added yet the old-school way
            int shipments = theCart.OrderForms[0].Shipments.Count;                            // zero...?

            //otherShip = (Shipment)ship;
            //int ShipId = theCart.OrderForms[0].Shipments.Add(otherShip); // Gets ordinal index it seems ... not ShipmentId
            // okay, but...



            ILineItem Ili = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault();

            var dtoShip = ShippingManager.GetShippingMethodsByMarket
                              (_currMarket.Service.GetCurrentMarket().MarketId.Value, false).ShippingMethod.FirstOrDefault();
            Shipment s = new Shipment();

            s.ShippingMethodId   = dtoShip.ShippingMethodId;
            s.ShippingMethodName = dtoShip.Name;
            int ShipId = theCart.OrderForms[0].Shipments.Add(s);

            // ..seems to work,
            //PurchaseOrderManager.AddLineItemToShipment(
            //  theCart, Ili.LineItemId, s, 2);
            // probably need to persist (old way) & reload "the new way"
            //ILineItem li2 = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault(); // new way (null)

            // OrderForm
            Money formTot = _ofCalc.Service.GetTotal(form, market, curr);

            // OrderGroup
            Money handlingFee = _ogCalc.Service.GetHandlingTotal(theCart);
            Money subTotal    = _ogCalc.Service.GetSubTotal(theCart);
            Money total       = _ogCalc.Service.GetTotal(theCart);

            // Shipping
            //var shipCost = _shipCalc.Service.GetShipmentCost(form, market, curr);
            var shipTot = _shipCalc.Service.GetShippingItemsTotal(ship, curr);

            //LineItems
            var x = _lItemCalc.Service.GetExtendedPrice(theCart.OrderForms.FirstOrDefault().LineItems.FirstOrDefault(), curr); // Ext.Price verkar vara på väg ut

            //Taxes
            var t = _taxCalc.Service.GetTaxTotal(form, market, curr);
        }
        private int PlaceOneClickOrder(CartHelper cartHelper, PlaceOrderInfo orderInfo)
        {
            Cart cart = cartHelper.Cart;

            CustomerContact currentContact = CustomerContext.Current.GetContactById(orderInfo.CustomerId);

            if (currentContact == null)
            {
                throw new NullReferenceException("Cannot load customer with id: " + orderInfo.CustomerId.ToString());
            }

            OrderGroupWorkflowManager.RunWorkflow(cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            cart.CustomerId   = orderInfo.CustomerId;
            cart.CustomerName = currentContact.FullName;

            if (currentContact.PreferredBillingAddress != null)
            {
                OrderAddress orderBillingAddress = StoreHelper.ConvertToOrderAddress(currentContact.PreferredBillingAddress);
                int          billingAddressId    = cart.OrderAddresses.Add(orderBillingAddress);
                cart.OrderForms[0].BillingAddressId = orderBillingAddress.Name;
            }
            if (currentContact.PreferredShippingAddress != null)
            {
                int shippingAddressId = cart.OrderAddresses.Add(StoreHelper.ConvertToOrderAddress(currentContact.PreferredShippingAddress));
            }

            if (cart.OrderAddresses.Count == 0)
            {
                CustomerAddress address = currentContact.ContactAddresses.FirstOrDefault();
                if (address != null)
                {
                    int defaultAddressId = cart.OrderAddresses.Add(StoreHelper.ConvertToOrderAddress(address));
                    cart.OrderForms[0].BillingAddressId = address.Name;
                }
            }

            var po = cart.SaveAsPurchaseOrder();

            // These does not persist
            po.OrderForms[0].Created  = orderInfo.OrderDate;
            po.OrderForms[0].Modified = orderInfo.OrderDate;
            po.Created  = orderInfo.OrderDate;
            po.Modified = orderInfo.OrderDate;

            currentContact.LastOrder = po.Created;
            currentContact.SaveChanges();

            // Add note to purchaseOrder
            OrderNotesManager.AddNoteToPurchaseOrder(po, "", OrderNoteTypes.System, orderInfo.CustomerId);
            // OrderNotesManager.AddNoteToPurchaseOrder(po, "Created: " + po.Created, OrderNoteTypes.System, orderInfo.CustomerId);

            po.AcceptChanges();

            SetOrderDates(po.Id, orderInfo.OrderDate);

            //Add do Find index
            // OrderHelper.CreateOrderToFind(po);

            // Remove old cart
            cart.Delete();
            cart.AcceptChanges();
            return(po.Id);
        }
Example #23
0
 // TODO: For some reason, this does not apply any discounts.
 public void ValidateAndApplyCampaigns()
 {
     OrderGroupWorkflowManager.RunWorkflow(_helper.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
     _helper.Cart.AcceptChanges();
 }
        //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 }));
        }
        public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentInfo paymentInfo, int[] SelectedCategories)
        {
            model.PaymentInfo         = paymentInfo;
            model.AvailableCategories = GetAvailableCategories();
            model.SelectedCategories  = SelectedCategories;

            bool requireSSN = paymentInfo.SelectedPayment == new Guid("8dca4a96-a5bb-4e85-82a4-2754f04c2117") ||
                              paymentInfo.SelectedPayment == new Guid("c2ea88f8-c702-4331-819e-0e77e7ac5450");

            // validate input!
            ValidateFields(model, requireSSN);

            CartHelper ch = new CartHelper(Cart.DefaultName);

            // Verify that we actually have the items we're about to sell
            ConfirmStocks(ch.LineItems);

            if (ModelState.IsValid)
            {
                var    billingAddress  = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName);
                var    shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName);
                string username        = model.Email.Trim();
                billingAddress.Email = username;
                billingAddress.DaytimePhoneNumber = model.Phone;

                HandleUserCreation(model, billingAddress, shippingAddress, username);

                if (ModelState.IsValid)
                {
                    // Checkout:

                    ch.Cart.OrderAddresses.Add(billingAddress);
                    ch.Cart.OrderAddresses.Add(shippingAddress);

                    AddShipping(ch.Cart, shippingAddress);

                    ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub;
                    if (model.SelectedCategories != null)
                    {
                        ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories);
                    }
                    OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);

                    AddPayment(ch.Cart, paymentInfo.SelectedPayment.ToString(), billingAddress);

                    ch.Cart.AcceptChanges();

                    // TODO: This assume the different payment pages are direct children of the start page
                    // and could break the payment if we move the pages.
                    BasePaymentPage page      = null;
                    var             startPage = _contentRepository.Get <HomePage>(ContentReference.StartPage);
                    foreach (var p in _contentRepository.GetChildren <BasePaymentPage>(startPage.Settings.PaymentContainerPage))
                    {
                        if (p.PaymentMethod.Equals(model.PaymentInfo.SelectedPayment.ToString()))
                        {
                            page = p;
                            break;
                        }
                    }

                    var resolver = ServiceLocator.Current.GetInstance <UrlResolver>();

                    if (page != null)
                    {
                        var url = resolver.GetUrl(page.ContentLink);
                        return(Redirect(url));
                    }
                }
            }

            Guid?selectedPayment = model.PaymentInfo.SelectedPayment;

            model.PaymentInfo = GetPaymentInfo();
            if (selectedPayment.HasValue)
            {
                model.PaymentInfo.SelectedPayment = selectedPayment.Value;
            }
            model.TermsArticle = currentPage.TermsArticle;

            return(View(model));
        }
Example #26
0
        public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentSelection paymentSelection, int[] SelectedCategories)
        {
            model.PaymentSelection    = paymentSelection;
            model.AvailableCategories = GetAvailableCategories();
            model.SelectedCategories  = SelectedCategories;

            bool requireSSN = _paymentRegistry.PaymentMethodRequiresSocialSecurityNumber(paymentSelection);

            // validate input!
            ValidateFields(model, requireSSN);

            CartHelper ch = new CartHelper(Cart.DefaultName);

            // Verify that we actually have the items we're about to sell
            ConfirmStocks(ch.LineItems);

            if (ModelState.IsValid)
            {
                var    billingAddress  = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName);
                var    shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName);
                string username        = model.Email.Trim();
                billingAddress.Email = username;
                billingAddress.DaytimePhoneNumber = model.Phone;

                HandleUserCreation(model, billingAddress, shippingAddress, username);

                if (ModelState.IsValid)
                {
                    // Checkout:

                    ch.Cart.OrderAddresses.Add(billingAddress);
                    ch.Cart.OrderAddresses.Add(shippingAddress);

                    AddShipping(ch.Cart, shippingAddress);

                    ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub;
                    if (model.SelectedCategories != null)
                    {
                        ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories);
                    }
                    OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);

                    AddPayment(ch.Cart, paymentSelection.SelectedPayment.ToString(), billingAddress);

                    ch.Cart.AcceptChanges();

                    var url = _paymentRegistry.GetPaymentMethodPageUrl(model.PaymentSelection.SelectedPayment.ToString());

                    if (url != null)
                    {
                        return(Redirect(url));
                    }
                }
            }

            Guid?selectedPayment = model.PaymentSelection.SelectedPayment;

            model.PaymentSelection = GetPaymentInfo();
            if (selectedPayment.HasValue)
            {
                model.PaymentSelection.SelectedPayment = selectedPayment.Value;
            }
            model.TermsArticle = currentPage.TermsArticle;

            return(View(model));
        }
Example #27
0
        /// <summary>
        /// Handles the ItemCommand event of the addressBook control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.ListViewCommandEventArgs"/> instance containing the event data.</param>
        void addressBook_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (string.IsNullOrEmpty(e.CommandArgument.ToString()) || _currentContact == null)
            {
                return;
            }

            var addressId = e.CommandArgument.ToString();
            var ca        = _currentContact.ContactAddresses.FirstOrDefault(x => x.AddressId.ToString().ToLower().Equals(addressId.ToLower()));

            if (ca == null)
            {
                return;
            }

            var address = _cartHelper.FindAddressByName(ca.Name);

            if (address == null)
            {
                address = ConvertCustomerToOrderAddress(ca);
                Cart.OrderAddresses.Add(address);
            }
            else
            {
                CustomerAddress.CopyCustomerAddressToOrderAddress(ca, address);
            }

            // Add address to BillingAddressId/ShippingAddressId
            if (addressType.Value.Equals("billing"))
            {
                Cart.OrderForms[0].BillingAddressId = address.Name;
            }
            else
            {
                int shipId;
                if (int.TryParse(shipmentId.Value, out shipId))
                {
                    var shipment = Cart.OrderForms[0].Shipments.ToArray().FirstOrDefault(s => s.Id == shipId);
                    if (shipment != null)
                    {
                        shipment.ShippingAddressId = ca.Name;
                        OrderGroupWorkflowManager.RunWorkflow(Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);
                    }
                }
                else
                {
                    var shipment = Cart.OrderForms[0].Shipments.ToArray().FirstOrDefault()
                                   ?? new Shipment()
                    {
                        CreatorId = SecurityContext.Current.CurrentUserId.ToString(),
                        Created   = DateTime.UtcNow
                    };

                    shipment.ShippingAddressId = address.Name;

                    if (Cart.OrderForms[0].Shipments.Count < 1)
                    {
                        Cart.OrderForms[0].Shipments.Add(shipment);
                    }

                    if (!shipment.ShippingMethodId.Equals(Guid.Empty))
                    {
                        //Calculate shipping in case choosing shipping method first.
                        OrderGroupWorkflowManager.RunWorkflow(Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);
                    }
                }
            }

            Cart.AcceptChanges();
            //redirect after post
            Context.RedirectFast(Request.RawUrl + "#ShippingRegion" + shipmentId.Value);
        }