コード例 #1
0
        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);
            }
        }
コード例 #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;
        }
コード例 #3
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();
        }
コード例 #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));
        }
コード例 #5
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();
            }
        }
コード例 #6
0
        /// <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);
        }
コード例 #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;
        }
コード例 #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();
        }
コード例 #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));
        }
コード例 #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));
        }
コード例 #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();
        }
コード例 #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);
        }
コード例 #13
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));
        }
コード例 #14
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);
        }
コード例 #15
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);
            }
        }
コード例 #16
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);
        }
コード例 #17
0
        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));
            }
        }
コード例 #18
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);
        }
コード例 #20
0
        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);
        }
コード例 #21
0
 // TODO: For some reason, this does not apply any discounts.
 public void ValidateAndApplyCampaigns()
 {
     OrderGroupWorkflowManager.RunWorkflow(_helper.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
     _helper.Cart.AcceptChanges();
 }
コード例 #22
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);
        }
コード例 #23
0
        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));
        }
コード例 #24
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));
        }