Exemplo n.º 1
0
        public void Clear_CartWithProduct_ClearsCart()
        {
            _cart.AddItem(_testProduct, 10);

            _cart.Clear();
            Assert.AreEqual(_cart.Items.Count, 0);
        }
        public void OnSuccess(int paymentId, int contentItemId)
        {
            var payment = _paymentService.GetPayment(paymentId);

            if (payment != null)
            {
                var order = _contentManager.Get <OrderPart>(payment.ContentItemId, VersionOptions.Latest); // _orderService.Get(payment.ContentItemId);
                // aggiorna l'odine in base al pagamento effettuato
                //order.Status = OrderPart.Pending;
                order.Status       = Constants.PaymentSucceeded;
                order.AmountPaid   = payment.Amount;
                order.CurrencyCode = payment.Currency;
                // update charge
                order.UpdateCharge(
                    new PaymentGatewayCharge("Payment Gateway", payment.Guid));
                order.LogActivity(OrderPart.Event, string.Format("Payed on POS {0}.", payment.PosName));
                // svuota il carrello
                foreach (var handler in _cartLifeCycleEventHandlers)
                {
                    handler.Finalized();
                }
                _shoppingCart.Clear();
                // raise order and payment events
                _contentManager.Publish(order.ContentItem);
                TriggerEvents(order);
            }
        }
        public ActionResult Create()
        {
            var user = _authenticationService.GetAuthenticatedUser();

            if (user == null)
            {
                throw new OrchardSecurityException(_t("Login required"));
            }

            var customer = user.ContentItem.As <CustomerPart>();

            if (customer == null)
            {
                throw new InvalidOperationException("The current user is not a customer");
            }

            var order = _orderService.CreateOrder(customer.Id, _shoppingCart.Items);


            // If we got here, no PSP handled the PaymentRequest event, so we'll just display the order.
            var shape = _shapeFactory.Order_Created(
                Order: order,
                Books: _orderService.GetBooks(order.Details).ToArray(),
                Customer: customer,
                BillingAddress: (dynamic)_customerService.GetAddress(user.Id)
                );

            _shoppingCart.Clear();
            return(new ShapeResult(this, shape));
        }
        private void UpdateShoppingCart(IEnumerable <UpdateShoppingCartItemViewModel> items)
        {
            _shoppingCart.Clear();

            if (items == null)
            {
                return;
            }

            var minimumOrderQuantities = GetMinimumOrderQuantities(items);

            _shoppingCart.AddRange(
                items
                .Where(item => !item.IsRemoved)
                .Select(item => new ShoppingCartItem(
                            item.ProductId,
                            item.Quantity <= 0 ? 0 : item.Quantity < minimumOrderQuantities[item.ProductId] ? minimumOrderQuantities[item.ProductId] : item.Quantity,
                            item.AttributeIdsToValues))
                );

            _shoppingCart.UpdateItems();

            _workflowManager.TriggerEvent("CartUpdated",
                                          _wca.GetContext().CurrentSite,
                                          () => new Dictionary <string, object> {
                { "Cart", _shoppingCart }
            });
        }
        private void UpdateShoppingCart(FormCollection form)
        {
            var formKeys = form.AllKeys;
            var items    = (from key in formKeys
                            where key.Length > 3
                            where key.Substring(0, 3) == "prd"
                            select new UpdateShoppingCartItemVM
            {
                ProductId = Convert.ToInt32(key.Substring(3)),
                Quantity = Convert.ToInt32(form[key]),
                Size = form["size" + key.Substring(3)]
            }).ToList();

            if (items.Count == 0)
            {
                return;
            }

            _shoppingCart.Clear();

            _shoppingCart.AddRange(items
                                   .Where(item => !item.IsRemoved)
                                   .Select(item => new ShoppingCartItem(item.ProductId, item.Size, item.Quantity < 0 ? 0 : item.Quantity))
                                   );

            _shoppingCart.UpdateItems();
        }
 private void UpdateShoppingCart(IEnumerable <UpdateShoppingCartItemViewModel> items)
 {
     _shoppingCart.Clear();
     if (items == null)
     {
         return;
     }
     _shoppingCart.AddRange(items
                            .Where(item => !item.IsRemoved)
                            .Select(item => new ShoppingCartItem(item.ProductId, item.Quantity < 0 ? 0 : item.Quantity)));
 }
        public void Clear()
        {
            //try
            //{

            //}
            //catch (Exception ex)
            //{
            //    _logger.Error(ex, "Something happened");
            //    //throw;
            //}

            _shoppingCart.Clear();
        }
        public ActionResult Confirmation()
        {
            if (!TempData.ContainsKey("OrderId"))
            {
                return(HttpNotFound());
            }
            var orderId         = TempData["OrderId"];
            var order           = _contentManager.Get <OrderPart>((int)orderId);
            var billingAddress  = _addressFormatter.Format(order.BillingAddress);
            var shippingAddress = _addressFormatter.Format(order.ShippingAddress);
            var items           = order.Items.ToList();
            var products        = _contentManager
                                  .GetMany <IContent>(
                items.Select(p => p.ProductId).Distinct(),
                VersionOptions.Latest,
                QueryHints.Empty)
                                  .ToDictionary(p => p.Id, p => p);
            var shape = _shapeFactory.Order_Confirmation(
                OrderId: order.Id,
                Status: _orderService.StatusLabels[order.Status],
                CheckoutItems: items,
                Products: products,
                SubTotal: order.SubTotal,
                Taxes: order.Taxes,
                Total: order.Total,
                ShippingOption: order.ShippingOption,
                BillingAddress: billingAddress,
                ShippingAddress: shippingAddress,
                TrackingUrl: order.TrackingUrl,
                CustomerEmail: order.CustomerEmail,
                CustomerPhone: order.CustomerPhone,
                ChargeText: order.Charge.ChargeText,
                SpecialInstructions: order.SpecialInstructions,
                PurchaseOrder: order.PurchaseOrder,
                Password: order.Password,
                CurrencyCode: string.IsNullOrWhiteSpace(order.CurrencyCode) ? _currencyProvider.CurrencyCode : order.CurrencyCode);

            foreach (var handler in _cartLifeCycleEventHandlers)
            {
                handler.Finalized();
            }
            _shoppingCart.Clear();
            return(new ShapeResult(this, shape));
        }
        public void OnSuccess(int paymentId, int contentItemId)
        {
            var payment = _paymentService.GetPayment(paymentId);

            if (payment != null)
            {
                var order = _orderService.Get(payment.ContentItemId);
                // agggiorna l'odine in base al pagamento effettuato
                order.Status        = OrderPart.Pending;
                order.AmountPaid    = payment.Amount;
                order.PurchaseOrder = _posServiceIntegration.GetOrderNumber(order.Id);
                order.CurrencyCode  = payment.Currency;
                order.LogActivity(OrderPart.Event, string.Format("Payed on POS {0}.", payment.PosName));
                // svuota il carrello
                foreach (var handler in _cartLifeCycleEventHandlers)
                {
                    handler.Finalized();
                }
                _shoppingCart.Clear();
                _nwazetCommunicationService.OrderToContact(order);
            }
        }
Exemplo n.º 10
0
        public ActionResult PaymentResponse()
        {
            var args = new PaymentResponse(HttpContext);

            foreach (var handler in _paymentServiceProviders)
            {
                handler.ProcessResponse(args);

                if (args.WillHandleResponse)
                {
                    break;
                }
            }

            if (!args.WillHandleResponse)
            {
                throw new OrchardException(_t("Such things mean trouble"));
            }

            var order = _orderService.GetOrderByNumber(args.OrderReference);

            _orderService.UpdateOrderStatus(order, args);

            var user = _authenticationService.GetAuthenticatedUser();

            if (user == null)
            {
                throw new OrchardSecurityException(_t("Login required"));
            }

            var customer = user.ContentItem.As <CustomerPart>();

            if (customer == null)
            {
                throw new InvalidOperationException("The current user is not a customer");
            }

            if (order.Status == OrderStatus.Paid)
            {
                // send an email confirmation to the customer
                string subject = string.Format("Your Order Number {0} has been received", order.Id);
                string body    = string.Format("Dear {0}<br/><br/>Thank you for your order.<br/><br/>You will receive a Tax Invoice when your order is shipped.", customer.FirstName);
                _messageManager.Process(new Dictionary <string, object>
                {
                    { "Recipients", user.Email },
                    { "Subject", subject },
                    { "Body", body }
                });

                //_messageManager.Send(user.ContentItem.Record, "ORDER_RECEIVED", "email", new Dictionary<string, string>
                //{
                //    { "Subject", subject },
                //    { "Body", body}
                //});

                // send a copy of the order to the administator
                _messageManager.Process(new Dictionary <string, object>
                {
                    { "Recipients", _webshopSettings.GetAdministratorEmail() },
                    { "Subject", string.Format("Order Number {0} received from {1} {2}", order.Id, customer.FirstName, customer.LastName) },
                    { "Body", body }
                });


                //string adminEmail = _webshopSettings.GetAdministratorEmail();
                //if (!string.IsNullOrWhiteSpace(adminEmail))
                //    _messageManager.Send(new List<string> { adminEmail}, "ORDER_RECEIVED", "email", new Dictionary<string, string>
                //    {
                //        { "Subject", string.Format("Order Number {0} received from {1} {2}", order.Id, customer.FirstName, customer.LastName) },
                //        { "Body", body}
                //    });

                // decrement stock levels
                _shoppingCart.RemoveFromStock();

                // finally, clear the order
                _shoppingCart.Clear();
            }

            return(new ShapeResult(this, _shapeFactory.Order_PaymentResponse(Order: order, PaymentResponse: args, ContinueShoppingUrl: _webshopSettings.GetContinueShoppingUrl())));
        }
        private void UpdateShoppingCart(IEnumerable <UpdateShoppingCartItemViewModel> items)
        {
            var oldItems = new List <ShoppingCartItem>();

            oldItems.AddRange(_shoppingCart.Items); //create a copy for analysis
            _shoppingCart.Clear();

            if (items == null)
            {
                //removed all items
                foreach (var handler in _cartLifeCycleEventHandlers)
                {
                    //we raise the ItemRemoved event for all the removed items.
                    //The ShoppingCartItem objects also contain the quantity of the variation
                    handler.Updated(new List <ShoppingCartItem>(0), oldItems);
                }
                return;
            }



            var minimumOrderQuantities = GetMinimumOrderQuantities(items);

            _shoppingCart.AddRange(
                items
                .Where(item => !item.IsRemoved)
                .Select(item => new ShoppingCartItem(
                            item.ProductId,
                            item.Quantity <= 0 ? 0 : item.Quantity < minimumOrderQuantities[item.ProductId] ? minimumOrderQuantities[item.ProductId] : item.Quantity,
                            item.AttributeIdsToValues))
                );

            _shoppingCart.UpdateItems();
            //analyze update to raise events
            var addedItems   = new List <ShoppingCartItem>();
            var removedItems = new List <ShoppingCartItem>();
            var newItems     = new List <ShoppingCartItem>();

            newItems.AddRange(_shoppingCart.Items);
            //we use a KeyValuePair because item.QUantity is not alowed to be negative
            var itemsInBoth = new List <KeyValuePair <int, ShoppingCartItem> >(); //quantity variation, item

            itemsInBoth.AddRange(
                newItems
                .Select(newSci => {
                var oldSci = oldItems
                             .FirstOrDefault(sci => ShoppingCartItem.ItemsAreEqual(sci, newSci)); //item was in cart already
                int quantityVariation = 0;
                if (oldSci != null)
                {
                    quantityVariation = newSci.Quantity - oldSci.Quantity;
                    oldSci.Quantity   = Math.Abs(quantityVariation);
                }
                return(new KeyValuePair <int, ShoppingCartItem>(quantityVariation, oldSci));
            })
                .Where(kvp => kvp.Value != null));
            foreach (var item in itemsInBoth.Where(kvp => kvp.Key != 0))
            {
                if (item.Key > 0)   //increase in quantity
                {
                    addedItems.Add(item.Value);
                }
                else if (item.Key < 0)     //decrease in quantity
                {
                    removedItems.Add(item.Value);
                }
                //if quantity has not changed, we do not raise an event for that item
            }
            addedItems.AddRange(
                newItems.Where(sci => !itemsInBoth.Any(isci => ShoppingCartItem.ItemsAreEqual(isci.Value, sci)))
                );
            removedItems.AddRange(
                oldItems.Where(sci => !itemsInBoth.Any(isci => ShoppingCartItem.ItemsAreEqual(isci.Value, sci)))
                );

            foreach (var handler in _cartLifeCycleEventHandlers)
            {
                handler.Updated(addedItems, removedItems);
            }
        }