Exemple #1
0
        /// <summary>
        /// Deletes a shipment item
        /// </summary>
        /// <param name="shipmentItem">Shipment item</param>
        public virtual void DeleteShipmentItem(ShipmentItem shipmentItem)
        {
            if (shipmentItem == null)
                throw new ArgumentNullException("shipmentItem");

            _siRepository.Delete(shipmentItem);

            //event notification
            _eventPublisher.EntityDeleted(shipmentItem);
        }
        public void Can_save_and_load_shipmentItem()
        {
            var shipmentItem = new ShipmentItem()
            {
                Shipment = GetTestShipment(),
                OrderItemId = 2,
                Quantity = 3, 
            };

            var fromDb = SaveAndLoadEntity(shipmentItem);
            fromDb.ShouldNotBeNull();
            fromDb.Shipment.ShouldNotBeNull();
            fromDb.OrderItemId.ShouldEqual(2);
            fromDb.Quantity.ShouldEqual(3);
        }
        /// <summary>
        /// Reverse booked inventory (if acceptable)
        /// </summary>
        /// <param name="product">product</param>
        /// <param name="shipmentItem">Shipment item</param>
        /// <returns>Quantity reversed</returns>
        public virtual int ReverseBookedInventory(Product product, ShipmentItem shipmentItem)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            if (shipmentItem == null)
                throw new ArgumentNullException("shipmentItem");

            //only products with "use multiple warehouses" are handled this way
            if (product.ManageInventoryMethod != ManageInventoryMethod.ManageStock)
                return 0;
            if (!product.UseMultipleWarehouses)
                return 0;

            var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == shipmentItem.WarehouseId);
            if (pwi == null)
                return 0;

            var shipment = shipmentItem.Shipment;

            //not shipped yet? hence "BookReservedInventory" method was not invoked
            if (!shipment.ShippedDateUtc.HasValue)
                return 0;

            var qty = shipmentItem.Quantity;

            pwi.StockQuantity += qty;
            pwi.ReservedQuantity += qty;
            UpdateProduct(product);

            //TODO add support for bundled products (AttributesXml)

            return qty;
        }
Exemple #4
0
        public ActionResult AddShipment(int orderId, FormCollection form, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
                return AccessDeniedView();

            var order = _orderService.GetOrderById(orderId);
            if (order == null)
                //No order found with the specified id
                return RedirectToAction("List");

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null && !HasAccessToOrder(order))
                return RedirectToAction("List");

            var orderItems = order.OrderItems;
            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null)
            {
                orderItems = orderItems.Where(orderItem => HasAccessToOrderItem(orderItem)).ToList();
            }

            Shipment shipment = null;
            decimal? totalWeight = null;
            foreach (var orderItem in orderItems)
            {
                //is shippable
                if (!orderItem.Product.IsShipEnabled)
                    continue;

                //ensure that this product can be shipped (have at least one item to ship)
                var maxQtyToAdd = orderItem.GetTotalNumberOfItemsCanBeAddedToShipment();
                if (maxQtyToAdd <= 0)
                    continue;

                int qtyToAdd = 0; //parse quantity
                foreach (string formKey in form.AllKeys)
                    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    {
                        int.TryParse(form[formKey], out qtyToAdd);
                        break;
                    }

                //validate quantity
                if (qtyToAdd <= 0)
                    continue;
                if (qtyToAdd > maxQtyToAdd)
                    qtyToAdd = maxQtyToAdd;

                //ok. we have at least one item. let's create a shipment (if it does not exist)

                var orderItemTotalWeight = orderItem.ItemWeight.HasValue ? orderItem.ItemWeight * qtyToAdd : null;
                if (orderItemTotalWeight.HasValue)
                {
                    if (!totalWeight.HasValue)
                        totalWeight = 0;
                    totalWeight += orderItemTotalWeight.Value;
                }
                if (shipment == null)
                {
                    var trackingNumber = form["TrackingNumber"];
                    shipment = new Shipment()
                    {
                        OrderId = order.Id,
                        TrackingNumber = trackingNumber,
                        TotalWeight = null,
                        ShippedDateUtc = null,
                        DeliveryDateUtc = null,
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                }
                //create a shipment item
                var shipmentItem = new ShipmentItem()
                {
                    OrderItemId = orderItem.Id,
                    Quantity = qtyToAdd,
                };
                shipment.ShipmentItems.Add(shipmentItem);
            }

            //if we have at least one item in the shipment, then save it
            if (shipment != null && shipment.ShipmentItems.Count > 0)
            {
                shipment.TotalWeight = totalWeight;
                _shipmentService.InsertShipment(shipment);

                SuccessNotification(_localizationService.GetResource("Admin.Orders.Shipments.Added"));
                return continueEditing
                           ? RedirectToAction("ShipmentDetails", new {id = shipment.Id})
                           : RedirectToAction("Edit", new { id = orderId });
            }
            else
            {
                ErrorNotification(_localizationService.GetResource("Admin.Orders.Shipments.NoProductsSelected"));
                return RedirectToAction("AddShipment", new { orderId = orderId });
            }
        }
        protected virtual void InstallOrders()
        {
            //default store
            var defaultStore = _storeRepository.Table.FirstOrDefault();
            if (defaultStore == null)
                throw new Exception("No default store could be loaded");

            //first order
            var firstCustomer = _customerRepository.Table.First(c => c.Email.Equals("*****@*****.**"));
            var firstOrder = new Order()
            {
                StoreId = defaultStore.Id,
                OrderGuid = Guid.NewGuid(),
                Customer = firstCustomer,
                CustomerLanguageId = _languageRepository.Table.First().Id,
                CustomerIp = "127.0.0.1",
                OrderSubtotalInclTax = 1855M,
                OrderSubtotalExclTax = 1855M,
                OrderSubTotalDiscountInclTax = decimal.Zero,
                OrderSubTotalDiscountExclTax = decimal.Zero,
                OrderShippingInclTax = decimal.Zero,
                OrderShippingExclTax = decimal.Zero,
                PaymentMethodAdditionalFeeInclTax = decimal.Zero,
                PaymentMethodAdditionalFeeExclTax = decimal.Zero,
                TaxRates = "0:0;",
                OrderTax = decimal.Zero,
                OrderTotal = 1855M,
                RefundedAmount = decimal.Zero,
                OrderDiscount = decimal.Zero,
                CheckoutAttributeDescription = string.Empty,
                CheckoutAttributesXml = string.Empty,
                CustomerCurrencyCode = "USD",
                CurrencyRate = 1M,
                AffiliateId = 0,
                OrderStatus = OrderStatus.Processing,
                AllowStoringCreditCardNumber = false,
                CardType = string.Empty,
                CardName = string.Empty,
                CardNumber = string.Empty,
                MaskedCreditCardNumber = string.Empty,
                CardCvv2 = string.Empty,
                CardExpirationMonth = string.Empty,
                CardExpirationYear = string.Empty,
                PaymentMethodSystemName = "Payments.CheckMoneyOrder",
                AuthorizationTransactionId = string.Empty,
                AuthorizationTransactionCode = string.Empty,
                AuthorizationTransactionResult = string.Empty,
                CaptureTransactionId = string.Empty,
                CaptureTransactionResult = string.Empty,
                SubscriptionTransactionId = string.Empty,
                PaymentStatus = PaymentStatus.Paid,
                PaidDateUtc = DateTime.UtcNow,
                BillingAddress = (Address)firstCustomer.BillingAddress.Clone(),
                ShippingAddress = (Address)firstCustomer.ShippingAddress.Clone(),
                ShippingStatus = ShippingStatus.NotYetShipped,
                ShippingMethod = "Ground",
                PickUpInStore = false,
                ShippingRateComputationMethodSystemName = "Shipping.FixedRate",
                CustomValuesXml = string.Empty,
                VatNumber = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _orderRepository.Insert(firstOrder);

            //item Apple iCam
            var firstOrderItem1 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = firstOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Apple iCam")).Id,
                UnitPriceInclTax = 1300M,
                UnitPriceExclTax = 1300M,
                PriceInclTax = 1300M,
                PriceExclTax = 1300M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(firstOrderItem1);

            //item Leica T Mirrorless Digital Camera
            var fierstOrderItem2 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = firstOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Leica T Mirrorless Digital Camera")).Id,
                UnitPriceInclTax = 530M,
                UnitPriceExclTax = 530M,
                PriceInclTax = 530M,
                PriceExclTax = 530M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(fierstOrderItem2);

            //item $25 Virtual Gift Card
            var firstOrderItem3 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = firstOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("$25 Virtual Gift Card")).Id,
                UnitPriceInclTax = 25M,
                UnitPriceExclTax = 25M,
                PriceInclTax = 25M,
                PriceExclTax = 25M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = "From: Steve Gates &lt;[email protected]&gt;<br />For: Brenda Lindgren &lt;[email protected]&gt;",
                AttributesXml = "<Attributes><GiftCardInfo><RecipientName>Brenda Lindgren</RecipientName><RecipientEmail>[email protected]</RecipientEmail><SenderName>Steve Gates</SenderName><SenderEmail>[email protected]</SenderEmail><Message></Message></GiftCardInfo></Attributes>",
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(firstOrderItem3);

            var firstOrderGiftcard = new GiftCard
            {
                GiftCardType = GiftCardType.Virtual,
                PurchasedWithOrderItem = firstOrderItem3,
                Amount = 25M,
                IsGiftCardActivated = false,
                GiftCardCouponCode = string.Empty,
                RecipientName = "Brenda Lindgren",
                RecipientEmail = "*****@*****.**",
                SenderName = "Steve Gates",
                SenderEmail = "*****@*****.**",
                Message = string.Empty,
                IsRecipientNotified = false,
                CreatedOnUtc = DateTime.UtcNow
            };
            _giftCardRepository.Insert(firstOrderGiftcard);

            //order notes
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order placed",
                Order = firstOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order paid",
                Order = firstOrder
            });


            //second order
            var secondCustomer = _customerRepository.Table.First(c => c.Email.Equals("*****@*****.**"));
            var secondOrder = new Order()
            {
                StoreId = defaultStore.Id,
                OrderGuid = Guid.NewGuid(),
                Customer = secondCustomer,
                CustomerLanguageId = _languageRepository.Table.First().Id,
                CustomerIp = "127.0.0.1",
                OrderSubtotalInclTax = 2460M,
                OrderSubtotalExclTax = 2460M,
                OrderSubTotalDiscountInclTax = decimal.Zero,
                OrderSubTotalDiscountExclTax = decimal.Zero,
                OrderShippingInclTax = decimal.Zero,
                OrderShippingExclTax = decimal.Zero,
                PaymentMethodAdditionalFeeInclTax = decimal.Zero,
                PaymentMethodAdditionalFeeExclTax = decimal.Zero,
                TaxRates = "0:0;",
                OrderTax = decimal.Zero,
                OrderTotal = 2460M,
                RefundedAmount = decimal.Zero,
                OrderDiscount = decimal.Zero,
                CheckoutAttributeDescription = string.Empty,
                CheckoutAttributesXml = string.Empty,
                CustomerCurrencyCode = "USD",
                CurrencyRate = 1M,
                AffiliateId = 0,
                OrderStatus = OrderStatus.Pending,
                AllowStoringCreditCardNumber = false,
                CardType = string.Empty,
                CardName = string.Empty,
                CardNumber = string.Empty,
                MaskedCreditCardNumber = string.Empty,
                CardCvv2 = string.Empty,
                CardExpirationMonth = string.Empty,
                CardExpirationYear = string.Empty,
                PaymentMethodSystemName = "Payments.CheckMoneyOrder",
                AuthorizationTransactionId = string.Empty,
                AuthorizationTransactionCode = string.Empty,
                AuthorizationTransactionResult = string.Empty,
                CaptureTransactionId = string.Empty,
                CaptureTransactionResult = string.Empty,
                SubscriptionTransactionId = string.Empty,
                PaymentStatus = PaymentStatus.Pending,
                PaidDateUtc = null,
                BillingAddress = (Address)secondCustomer.BillingAddress.Clone(),
                ShippingAddress = (Address)secondCustomer.ShippingAddress.Clone(),
                ShippingStatus = ShippingStatus.NotYetShipped,
                ShippingMethod = "Next Day Air",
                PickUpInStore = false,
                ShippingRateComputationMethodSystemName = "Shipping.FixedRate",
                CustomValuesXml = string.Empty,
                VatNumber = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _orderRepository.Insert(secondOrder);

            //order notes
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order placed",
                Order = secondOrder
            });

            //item Vintage Style Engagement Ring
            var secondOrderItem1 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = secondOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Vintage Style Engagement Ring")).Id,
                UnitPriceInclTax = 2100M,
                UnitPriceExclTax = 2100M,
                PriceInclTax = 2100M,
                PriceExclTax = 2100M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(secondOrderItem1);

            //item Flower Girl Bracelet
            var secondOrderItem2 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = secondOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Flower Girl Bracelet")).Id,
                UnitPriceInclTax = 360M,
                UnitPriceExclTax = 360M,
                PriceInclTax = 360M,
                PriceExclTax = 360M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(secondOrderItem2);


            //third order
            var thirdCustomer = _customerRepository.Table.First(c => c.Email.Equals("*****@*****.**"));
            var thirdOrder = new Order()
            {
                StoreId = defaultStore.Id,
                OrderGuid = Guid.NewGuid(),
                Customer = thirdCustomer,
                CustomerLanguageId = _languageRepository.Table.First().Id,
                CustomerIp = "127.0.0.1",
                OrderSubtotalInclTax = 8.80M,
                OrderSubtotalExclTax = 8.80M,
                OrderSubTotalDiscountInclTax = decimal.Zero,
                OrderSubTotalDiscountExclTax = decimal.Zero,
                OrderShippingInclTax = decimal.Zero,
                OrderShippingExclTax = decimal.Zero,
                PaymentMethodAdditionalFeeInclTax = decimal.Zero,
                PaymentMethodAdditionalFeeExclTax = decimal.Zero,
                TaxRates = "0:0;",
                OrderTax = decimal.Zero,
                OrderTotal = 8.80M,
                RefundedAmount = decimal.Zero,
                OrderDiscount = decimal.Zero,
                CheckoutAttributeDescription = string.Empty,
                CheckoutAttributesXml = string.Empty,
                CustomerCurrencyCode = "USD",
                CurrencyRate = 1M,
                AffiliateId = 0,
                OrderStatus = OrderStatus.Pending,
                AllowStoringCreditCardNumber = false,
                CardType = string.Empty,
                CardName = string.Empty,
                CardNumber = string.Empty,
                MaskedCreditCardNumber = string.Empty,
                CardCvv2 = string.Empty,
                CardExpirationMonth = string.Empty,
                CardExpirationYear = string.Empty,
                PaymentMethodSystemName = "Payments.CheckMoneyOrder",
                AuthorizationTransactionId = string.Empty,
                AuthorizationTransactionCode = string.Empty,
                AuthorizationTransactionResult = string.Empty,
                CaptureTransactionId = string.Empty,
                CaptureTransactionResult = string.Empty,
                SubscriptionTransactionId = string.Empty,
                PaymentStatus = PaymentStatus.Pending,
                PaidDateUtc = null,
                BillingAddress = (Address)thirdCustomer.BillingAddress.Clone(),
                ShippingAddress = null,
                ShippingStatus = ShippingStatus.ShippingNotRequired,
                ShippingMethod = string.Empty,
                PickUpInStore = false,
                ShippingRateComputationMethodSystemName = string.Empty,
                CustomValuesXml = string.Empty,
                VatNumber = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _orderRepository.Insert(thirdOrder);

            //order notes
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order placed",
                Order = thirdOrder
            });

            //item If You Wait
            var thirdOrderItem1 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = thirdOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("If You Wait (donation)")).Id,
                UnitPriceInclTax = 3M,
                UnitPriceExclTax = 3M,
                PriceInclTax = 3M,
                PriceExclTax = 3M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(thirdOrderItem1);

            //item Night Visions
            var thirdOrderItem2 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = thirdOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Night Visions")).Id,
                UnitPriceInclTax = 2.8M,
                UnitPriceExclTax = 2.8M,
                PriceInclTax = 2.8M,
                PriceExclTax = 2.8M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(thirdOrderItem2);

            //item Science & Faith
            var thirdOrderItem3 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = thirdOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Science & Faith")).Id,
                UnitPriceInclTax = 3M,
                UnitPriceExclTax = 3M,
                PriceInclTax = 3M,
                PriceExclTax = 3M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(thirdOrderItem3);


            //fourth order
            var fourthCustomer = _customerRepository.Table.First(c => c.Email.Equals("*****@*****.**"));
            var fourthOrder = new Order()
            {
                StoreId = defaultStore.Id,
                OrderGuid = Guid.NewGuid(),
                Customer = fourthCustomer,
                CustomerLanguageId = _languageRepository.Table.First().Id,
                CustomerIp = "127.0.0.1",
                OrderSubtotalInclTax = 102M,
                OrderSubtotalExclTax = 102M,
                OrderSubTotalDiscountInclTax = decimal.Zero,
                OrderSubTotalDiscountExclTax = decimal.Zero,
                OrderShippingInclTax = decimal.Zero,
                OrderShippingExclTax = decimal.Zero,
                PaymentMethodAdditionalFeeInclTax = decimal.Zero,
                PaymentMethodAdditionalFeeExclTax = decimal.Zero,
                TaxRates = "0:0;",
                OrderTax = decimal.Zero,
                OrderTotal = 102M,
                RefundedAmount = decimal.Zero,
                OrderDiscount = decimal.Zero,
                CheckoutAttributeDescription = string.Empty,
                CheckoutAttributesXml = string.Empty,
                CustomerCurrencyCode = "USD",
                CurrencyRate = 1M,
                AffiliateId = 0,
                OrderStatus = OrderStatus.Processing,
                AllowStoringCreditCardNumber = false,
                CardType = string.Empty,
                CardName = string.Empty,
                CardNumber = string.Empty,
                MaskedCreditCardNumber = string.Empty,
                CardCvv2 = string.Empty,
                CardExpirationMonth = string.Empty,
                CardExpirationYear = string.Empty,
                PaymentMethodSystemName = "Payments.CheckMoneyOrder",
                AuthorizationTransactionId = string.Empty,
                AuthorizationTransactionCode = string.Empty,
                AuthorizationTransactionResult = string.Empty,
                CaptureTransactionId = string.Empty,
                CaptureTransactionResult = string.Empty,
                SubscriptionTransactionId = string.Empty,
                PaymentStatus = PaymentStatus.Paid,
                PaidDateUtc = DateTime.UtcNow,
                BillingAddress = (Address)fourthCustomer.BillingAddress.Clone(),
                ShippingAddress = (Address)fourthCustomer.ShippingAddress.Clone(),
                ShippingStatus = ShippingStatus.Shipped,
                ShippingMethod = "Pickup in store",
                PickUpInStore = true,
                PickupAddress = (Address)fourthCustomer.ShippingAddress.Clone(),
                ShippingRateComputationMethodSystemName = "Pickup.PickupInStore",
                CustomValuesXml = string.Empty,
                VatNumber = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _orderRepository.Insert(fourthOrder);

            //order notes
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order placed",
                Order = fourthOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order paid",
                Order = fourthOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order shipped",
                Order = fourthOrder
            });

            //item Pride and Prejudice
            var fourthOrderItem1 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = fourthOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Pride and Prejudice")).Id,
                UnitPriceInclTax = 24M,
                UnitPriceExclTax = 24M,
                PriceInclTax = 24M,
                PriceExclTax = 24M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(fourthOrderItem1);

            //item First Prize Pies
            var fourthOrderItem2 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = fourthOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("First Prize Pies")).Id,
                UnitPriceInclTax = 51M,
                UnitPriceExclTax = 51M,
                PriceInclTax = 51M,
                PriceExclTax = 51M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(fourthOrderItem2);

            //item Fahrenheit 451 by Ray Bradbury
            var fourthOrderItem3 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = fourthOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Fahrenheit 451 by Ray Bradbury")).Id,
                UnitPriceInclTax = 27M,
                UnitPriceExclTax = 27M,
                PriceInclTax = 27M,
                PriceExclTax = 27M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(fourthOrderItem3);

            //shipments
            //shipment 1
            var fourthOrderShipment1 = new Shipment
            {
                Order = fourthOrder,
                TrackingNumber = string.Empty,
                TotalWeight = 4M,
                ShippedDateUtc = DateTime.UtcNow,
                DeliveryDateUtc = DateTime.UtcNow,
                AdminComment = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _shipmentRepository.Insert(fourthOrderShipment1);

            var fourthOrderShipment1Item1 = new ShipmentItem()
            {
                OrderItemId = fourthOrderItem1.Id,
                Quantity = 1,
                WarehouseId = 0,
                Shipment = fourthOrderShipment1
            };
            _shipmentItemRepository.Insert(fourthOrderShipment1Item1);

            var fourthOrderShipment1Item2 = new ShipmentItem()
            {
                OrderItemId = fourthOrderItem2.Id,
                Quantity = 1,
                WarehouseId = 0,
                Shipment = fourthOrderShipment1
            };
            _shipmentItemRepository.Insert(fourthOrderShipment1Item2);

            //shipment 2
            var fourthOrderShipment2 = new Shipment
            {
                Order = fourthOrder,
                TrackingNumber = string.Empty,
                TotalWeight = 2M,
                ShippedDateUtc = DateTime.UtcNow,
                DeliveryDateUtc = DateTime.UtcNow,
                AdminComment = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _shipmentRepository.Insert(fourthOrderShipment2);

            var fourthOrderShipment2Item1 = new ShipmentItem()
            {
                OrderItemId = fourthOrderItem3.Id,
                Quantity = 1,
                WarehouseId = 0,
                Shipment = fourthOrderShipment2
            };
            _shipmentItemRepository.Insert(fourthOrderShipment2Item1);




            //fifth order
            var fifthCustomer = _customerRepository.Table.First(c => c.Email.Equals("*****@*****.**"));
            var fifthOrder = new Order()
            {
                StoreId = defaultStore.Id,
                OrderGuid = Guid.NewGuid(),
                Customer = fifthCustomer,
                CustomerLanguageId = _languageRepository.Table.First().Id,
                CustomerIp = "127.0.0.1",
                OrderSubtotalInclTax = 43.50M,
                OrderSubtotalExclTax = 43.50M,
                OrderSubTotalDiscountInclTax = decimal.Zero,
                OrderSubTotalDiscountExclTax = decimal.Zero,
                OrderShippingInclTax = decimal.Zero,
                OrderShippingExclTax = decimal.Zero,
                PaymentMethodAdditionalFeeInclTax = decimal.Zero,
                PaymentMethodAdditionalFeeExclTax = decimal.Zero,
                TaxRates = "0:0;",
                OrderTax = decimal.Zero,
                OrderTotal = 43.50M,
                RefundedAmount = decimal.Zero,
                OrderDiscount = decimal.Zero,
                CheckoutAttributeDescription = string.Empty,
                CheckoutAttributesXml = string.Empty,
                CustomerCurrencyCode = "USD",
                CurrencyRate = 1M,
                AffiliateId = 0,
                OrderStatus = OrderStatus.Complete,
                AllowStoringCreditCardNumber = false,
                CardType = string.Empty,
                CardName = string.Empty,
                CardNumber = string.Empty,
                MaskedCreditCardNumber = string.Empty,
                CardCvv2 = string.Empty,
                CardExpirationMonth = string.Empty,
                CardExpirationYear = string.Empty,
                PaymentMethodSystemName = "Payments.CheckMoneyOrder",
                AuthorizationTransactionId = string.Empty,
                AuthorizationTransactionCode = string.Empty,
                AuthorizationTransactionResult = string.Empty,
                CaptureTransactionId = string.Empty,
                CaptureTransactionResult = string.Empty,
                SubscriptionTransactionId = string.Empty,
                PaymentStatus = PaymentStatus.Paid,
                PaidDateUtc = DateTime.UtcNow,
                BillingAddress = (Address)fifthCustomer.BillingAddress.Clone(),
                ShippingAddress = (Address)fifthCustomer.ShippingAddress.Clone(),
                ShippingStatus = ShippingStatus.Delivered,
                ShippingMethod = "Ground",
                PickUpInStore = false,
                ShippingRateComputationMethodSystemName = "Shipping.FixedRate",
                CustomValuesXml = string.Empty,
                VatNumber = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _orderRepository.Insert(fifthOrder);

            //order notes
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order placed",
                Order = fifthOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order paid",
                Order = fifthOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order shipped",
                Order = fifthOrder
            });
            _orderNoteRepository.Insert(new OrderNote()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Note = "Order delivered",
                Order = fifthOrder
            });

            //item Levi's 511 Jeans
            var fifthOrderItem1 = new OrderItem()
            {
                OrderItemGuid = Guid.NewGuid(),
                Order = fifthOrder,
                ProductId = _productRepository.Table.First(p => p.Name.Equals("Levi's 511 Jeans")).Id,
                UnitPriceInclTax = 43.50M,
                UnitPriceExclTax = 43.50M,
                PriceInclTax = 43.50M,
                PriceExclTax = 43.50M,
                OriginalProductCost = decimal.Zero,
                AttributeDescription = string.Empty,
                AttributesXml = string.Empty,
                Quantity = 1,
                DiscountAmountInclTax = decimal.Zero,
                DiscountAmountExclTax = decimal.Zero,
                DownloadCount = 0,
                IsDownloadActivated = false,
                LicenseDownloadId = 0,
                ItemWeight = null,
                RentalStartDateUtc = null,
                RentalEndDateUtc = null
            };
            _orderItemRepository.Insert(fifthOrderItem1);

            //shipment 1
            var fifthOrderShipment1 = new Shipment
            {
                Order = fifthOrder,
                TrackingNumber = string.Empty,
                TotalWeight = 2M,
                ShippedDateUtc = DateTime.UtcNow,
                DeliveryDateUtc = DateTime.UtcNow,
                AdminComment = string.Empty,
                CreatedOnUtc = DateTime.UtcNow
            };
            _shipmentRepository.Insert(fifthOrderShipment1);

            var fifthOrderShipment1Item1 = new ShipmentItem()
            {
                OrderItemId = fifthOrderItem1.Id,
                Quantity = 1,
                WarehouseId = 0,
                Shipment = fifthOrderShipment1
            };
            _shipmentItemRepository.Insert(fifthOrderShipment1Item1);
        }
        public ActionResult AddShipment(int orderId, FormCollection form, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
                return AccessDeniedView();

            var order = _orderService.GetOrderById(orderId);
            if (order == null)
                //No order found with the specified id
                return RedirectToAction("List");

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null && !HasAccessToOrder(order))
                return RedirectToAction("List");

            var orderItems = order.OrderItems;
            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null)
            {
                orderItems = orderItems.Where(HasAccessToOrderItem).ToList();
            }

            Shipment shipment = null;
            decimal? totalWeight = null;
            foreach (var orderItem in orderItems)
            {
                //is shippable
                if (!orderItem.Product.IsShipEnabled)
                    continue;

                //ensure that this product can be shipped (have at least one item to ship)
                var maxQtyToAdd = orderItem.GetTotalNumberOfItemsCanBeAddedToShipment();
                if (maxQtyToAdd <= 0)
                    continue;

                int qtyToAdd = 0; //parse quantity
                foreach (string formKey in form.AllKeys)
                    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    {
                        int.TryParse(form[formKey], out qtyToAdd);
                        break;
                    }

                int warehouseId = 0;
                if (orderItem.Product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                    orderItem.Product.UseMultipleWarehouses)
                {
                    //multiple warehouses supported
                    //warehouse is chosen by a store owner
                    foreach (string formKey in form.AllKeys)
                        if (formKey.Equals(string.Format("warehouse_{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                        {
                            int.TryParse(form[formKey], out warehouseId);
                            break;
                        }
                }
                else
                {
                    //multiple warehouses are not supported
                    warehouseId = orderItem.Product.WarehouseId;
                }

                foreach (string formKey in form.AllKeys)
                    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    {
                        int.TryParse(form[formKey], out qtyToAdd);
                        break;
                    }

                //validate quantity
                if (qtyToAdd <= 0)
                    continue;
                if (qtyToAdd > maxQtyToAdd)
                    qtyToAdd = maxQtyToAdd;

                //ok. we have at least one item. let's create a shipment (if it does not exist)

                var orderItemTotalWeight = orderItem.ItemWeight.HasValue ? orderItem.ItemWeight * qtyToAdd : null;
                if (orderItemTotalWeight.HasValue)
                {
                    if (!totalWeight.HasValue)
                        totalWeight = 0;
                    totalWeight += orderItemTotalWeight.Value;
                }
                if (shipment == null)
                {
                    var trackingNumber = form["TrackingNumber"];
                    var adminComment = form["AdminComment"];
                    shipment = new Shipment
                    {
                        OrderId = order.Id,
                        TrackingNumber = trackingNumber,
                        TotalWeight = null,
                        ShippedDateUtc = null,
                        DeliveryDateUtc = null,
                        AdminComment = adminComment,
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                }
                //create a shipment item
                var shipmentItem = new ShipmentItem
                {
                    Id = shipment.ShipmentItems.Count > 0 ? shipment.ShipmentItems.Max(x=>x.Id)+1 : 1,
                    _id = ObjectId.GenerateNewId().ToString(),
                    ProductId = orderItem.ProductId,
                    OrderItemId = orderItem.Id,
                    Quantity = qtyToAdd,
                    WarehouseId = warehouseId
                };
                shipment.ShipmentItems.Add(shipmentItem);
            }

            //if we have at least one item in the shipment, then save it
            if (shipment != null && shipment.ShipmentItems.Count > 0)
            {
                shipment.TotalWeight = totalWeight;
                _shipmentService.InsertShipment(shipment);

                //add a note
                order.OrderNotes.Add(new OrderNote
                {
                    Note = "A shipment has been added",
                    DisplayToCustomer = false,
                    CreatedOnUtc = DateTime.UtcNow,
                    Id = order.OrderNotes.Count > 0 ? order.OrderNotes.Max(x => x.Id) + 1 : 1,
                    _id = ObjectId.GenerateNewId().ToString(),
                    OrderId = order.Id,
                });
                _orderService.UpdateOrder(order);
                LogEditOrder(order.Id);
                SuccessNotification(_localizationService.GetResource("Admin.Orders.Shipments.Added"));
                return continueEditing
                           ? RedirectToAction("ShipmentDetails", new {id = shipment.Id})
                           : RedirectToAction("Edit", new { id = orderId });
            }

            ErrorNotification(_localizationService.GetResource("Admin.Orders.Shipments.NoProductsSelected"));
            return RedirectToAction("AddShipment", new { orderId = orderId });
        }
        /// <summary>
        /// Reverse booked inventory (if acceptable)
        /// </summary>
        /// <param name="product">product</param>
        /// <param name="shipmentItem">Shipment item</param>
        /// <returns>Quantity reversed</returns>
        public virtual int ReverseBookedInventory(Product product, ShipmentItem shipmentItem)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            if (shipmentItem == null)
                throw new ArgumentNullException("shipmentItem");
            
            //only products with "use multiple warehouses" are handled this way
            if (product.ManageInventoryMethod != ManageInventoryMethod.ManageStock)
                return 0;
            if (!product.UseMultipleWarehouses)
                return 0;

            var pwi = product.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == shipmentItem.WarehouseId);
            if (pwi == null)
                return 0;

            var shipment = EngineContext.Current.Resolve<IShipmentService>().GetShipmentById(shipmentItem.ShipmentId);

            //not shipped yet? hence "BookReservedInventory" method was not invoked
            if (!shipment.ShippedDateUtc.HasValue)
                return 0;

            var qty = shipmentItem.Quantity;

            pwi.StockQuantity += qty;
            pwi.ReservedQuantity += qty;

            var builder = Builders<Product>.Filter;
            var filter = builder.Eq(x => x.Id, product.Id);
            filter = filter & builder.Where(x => x.ProductWarehouseInventory.Any(y => y.WarehouseId == pwi.WarehouseId));

            var update = Builders<Product>.Update
                    .Set(x => x.ProductWarehouseInventory.ElementAt(-1), pwi)
                    .CurrentDate("UpdateDate");
            _productRepository.Collection.UpdateOneAsync(filter, update);

            //cache
            _cacheManager.RemoveByPattern(string.Format(PRODUCTS_BY_ID_KEY, product.Id));
            //_cacheManager.RemoveByPattern(PRODUCTS_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityUpdated(product);


            //UpdateProduct(product);

            //TODO add support for bundled products (AttributesXml)

            return qty;
        }
        public void AddSelectedShipment(int orderId)
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
            //    return AccessDeniedView();

            var order = _orderService.GetOrderById(orderId);

            //model.CanAddNewShipments = order.HasItemsToAddToShipment();

            //if (order == null)
            //    //No order found with the specified id
            //    return RedirectToAction("List");

            //a vendor should have access only to his products
            //if (_workContext.CurrentVendor != null && !HasAccessToOrder(order))
            //    return RedirectToAction("List");
            bool blnAddToShipment = false;
            blnAddToShipment = order.HasItemsToAddToShipment();

            if (order.HasItemsToAddToShipment())
            {
                var orderItems = order.OrderItems;
                //a vendor should have access only to his products
                if (_workContext.CurrentVendor != null)
                {
                    orderItems = orderItems.Where(HasAccessToOrderItem).ToList();
                }

                Shipment shipment = null;
                decimal? totalWeight = null;
                foreach (var orderItem in orderItems)
                {
                    //is shippable
                    if (!orderItem.Product.IsShipEnabled)
                        continue;

                    //ensure that this product can be shipped (have at least one item to ship)
                    var maxQtyToAdd = orderItem.GetTotalNumberOfItemsCanBeAddedToShipment();
                    if (maxQtyToAdd <= 0)
                        continue;

                    int qtyToAdd = 0; //parse quantity

                    qtyToAdd = orderItem.Quantity;

                    //foreach (string formKey in form.AllKeys)
                    //    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    //    {
                    //        int.TryParse(form[formKey], out qtyToAdd);
                    //        break;
                    //    }

                    int warehouseId = 0;
                    if (orderItem.Product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                        orderItem.Product.UseMultipleWarehouses)
                    {
                        //multiple warehouses supported
                        //warehouse is chosen by a store owner
                        //foreach (string formKey in form.AllKeys)
                        //    if (formKey.Equals(string.Format("warehouse_{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                        //    {
                        //        int.TryParse(form[formKey], out warehouseId);
                        //        break;
                        //    }
                    }
                    else
                    {
                        //multiple warehouses are not supported
                        warehouseId = orderItem.Product.WarehouseId;
                    }

                    //foreach (string formKey in form.AllKeys)
                    //    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    //    {
                    //        int.TryParse(form[formKey], out qtyToAdd);
                    //        break;
                    //    }

                    //validate quantity
                    if (qtyToAdd <= 0)
                        continue;
                    if (qtyToAdd > maxQtyToAdd)
                        qtyToAdd = maxQtyToAdd;

                    //ok. we have at least one item. let's create a shipment (if it does not exist)

                    var orderItemTotalWeight = orderItem.ItemWeight.HasValue ? orderItem.ItemWeight * qtyToAdd : null;
                    if (orderItemTotalWeight.HasValue)
                    {
                        if (!totalWeight.HasValue)
                            totalWeight = 0;
                        totalWeight += orderItemTotalWeight.Value;
                    }
                    if (shipment == null)
                    {
                        var trackingNumber = "";
                        var adminComment = "";
                        shipment = new Shipment
                        {
                            OrderId = order.Id,
                            TrackingNumber = trackingNumber,
                            TotalWeight = null,
                            ShippedDateUtc = null,
                            DeliveryDateUtc = null,
                            AdminComment = adminComment,
                            CreatedOnUtc = DateTime.UtcNow,
                        };
                    }
                    //create a shipment item
                    var shipmentItem = new ShipmentItem
                    {
                        OrderItemId = orderItem.Id,
                        Quantity = qtyToAdd,
                        WarehouseId = warehouseId
                    };
                    shipment.ShipmentItems.Add(shipmentItem);
                }

                //if we have at least one item in the shipment, then save it
                if (shipment != null && shipment.ShipmentItems.Count > 0)
                {
                    shipment.TotalWeight = totalWeight;
                    _shipmentService.InsertShipment(shipment);

                    //add a note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "A shipment has been added",
                        DisplayToCustomer = false,
                        CreatedOnUtc = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);
                }
            }
        }