Example #1
0
        public OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            var store    = _services.StoreService.GetStoreById(order.StoreId) ?? _services.StoreContext.CurrentStore;
            var language = _services.WorkContext.WorkingLanguage;

            var orderSettings        = _services.Settings.LoadSetting <OrderSettings>(store.Id);
            var catalogSettings      = _services.Settings.LoadSetting <CatalogSettings>(store.Id);
            var taxSettings          = _services.Settings.LoadSetting <TaxSettings>(store.Id);
            var pdfSettings          = _services.Settings.LoadSetting <PdfSettings>(store.Id);
            var addressSettings      = _services.Settings.LoadSetting <AddressSettings>(store.Id);
            var companyInfoSettings  = _services.Settings.LoadSetting <CompanyInformationSettings>(store.Id);
            var shoppingCartSettings = _services.Settings.LoadSetting <ShoppingCartSettings>(store.Id);
            var mediaSettings        = _services.Settings.LoadSetting <MediaSettings>(store.Id);

            var model = new OrderDetailsModel();

            model.MerchantCompanyInfo = companyInfoSettings;
            model.Id                     = order.Id;
            model.StoreId                = order.StoreId;
            model.CustomerLanguageId     = order.CustomerLanguageId;
            model.CustomerComment        = order.CustomerOrderComment;
            model.OrderNumber            = order.GetOrderNumber();
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            model.IsReOrderAllowed       = orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.DisplayPdfInvoice      = pdfSettings.Enabled;
            model.RenderOrderNotes       = pdfSettings.RenderOrderNotes;

            // Shipping info
            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable = true;
                model.ShippingAddress.PrepareModel(order.ShippingAddress, false, addressSettings);
                model.ShippingMethod = order.ShippingMethod;


                // Shipments (only already shipped)
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };

                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }

                    model.Shipments.Add(shipmentModel);
                }
            }

            // Billing info
            model.BillingAddress.PrepareModel(order.BillingAddress, false, addressSettings);

            // VAT number
            model.VatNumber = order.VatNumber;

            //payment method
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod = paymentMethod != null?_pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : order.PaymentMethodSystemName;

            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);

            // Purchase order number (we have to find a better to inject this information because it's related to a certain plugin)
            if (paymentMethod != null && paymentMethod.Metadata.SystemName.Equals("SmartStore.PurchaseOrderNumber", StringComparison.InvariantCultureIgnoreCase))
            {
                model.DisplayPurchaseOrderNumber = true;
                model.PurchaseOrderNumber        = order.PurchaseOrderNumber;
            }

            // Totals
            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                // Order subtotal
                var orderSubtotalExclTax = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTax, true, order.CustomerCurrencyCode, language, false, false);

                // Discount (applied to order subtotal)
                var orderSubTotalDiscountExclTax = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTax > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTax, true, order.CustomerCurrencyCode, language, false, false);
                }

                // Order shipping
                var orderShippingExclTax = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTax, true, order.CustomerCurrencyCode, language, false, false);

                // Payment method additional fee
                var paymentMethodAdditionalFeeExclTax = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTax != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTax, true, order.CustomerCurrencyCode,
                                                                                                        language, false, false);
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                // Order subtotal
                var orderSubtotalInclTax = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTax, true, order.CustomerCurrencyCode, language, true, false);

                // Discount (applied to order subtotal)
                var orderSubTotalDiscountInclTax = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTax > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTax, true, order.CustomerCurrencyCode, language, true, false);
                }

                // Order shipping
                var orderShippingInclTax = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTax, true, order.CustomerCurrencyCode, language, true, false);

                // Payment method additional fee
                var paymentMethodAdditionalFeeInclTax = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTax != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTax, true, order.CustomerCurrencyCode,
                                                                                                        language, true, false);
                }
            }
            break;
            }

            // Tax
            var displayTax      = true;
            var displayTaxRates = true;

            if (taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);

                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        var rate = _priceFormatter.FormatTaxRate(tr.Key);
                        //var labelKey = "ShoppingCart.Totals.TaxRateLine" + (_services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "Incl" : "Excl");
                        var labelKey = (_services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "ShoppingCart.Totals.TaxRateLineIncl" : "ShoppingCart.Totals.TaxRateLineExcl");

                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate  = rate,
                            Label = T(labelKey).Text.FormatCurrent(rate),
                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, language),
                        });
                    }
                }
            }

            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;


            // Discount (applied to order total)
            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
            }

            // Gift cards
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                var remainingAmountBase = gcuh.GiftCard.GetGiftCardRemainingAmount();
                var remainingAmount     = _currencyService.ConvertCurrency(remainingAmountBase, order.CurrencyRate);

                var gcModel = new OrderDetailsModel.GiftCard
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language),
                    Remaining  = _priceFormatter.FormatPrice(remainingAmount, true, false)
                };

                model.GiftCards.Add(gcModel);
            }

            // Reward points
            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)),
                                                                               true, order.CustomerCurrencyCode, false, language);
            }

            // Credit balance.
            if (order.CreditBalance > decimal.Zero)
            {
                var convertedCreditBalance = _currencyService.ConvertCurrency(order.CreditBalance, order.CurrencyRate);
                model.CreditBalance = _priceFormatter.FormatPrice(-convertedCreditBalance, true, order.CustomerCurrencyCode, false, language);
            }

            // Total
            var roundingAmount = decimal.Zero;
            var orderTotal     = order.GetOrderTotalInCustomerCurrency(_currencyService, _paymentService, out roundingAmount);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotal, true, order.CustomerCurrencyCode, false, language);

            if (roundingAmount != decimal.Zero)
            {
                model.OrderTotalRounding = _priceFormatter.FormatPrice(roundingAmount, true, order.CustomerCurrencyCode, false, language);
            }

            // Checkout attributes
            model.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable(HtmlUtils.ConvertHtmlToPlainText(order.CheckoutAttributeDescription));

            // Order notes
            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                var createdOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc);

                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Note              = orderNote.FormatOrderNoteText(),
                    CreatedOn         = createdOn,
                    FriendlyCreatedOn = createdOn.RelativeFormat(false, "f")
                });
            }


            // purchased products
            model.ShowSku           = catalogSettings.ShowProductSku;
            model.ShowProductImages = shoppingCartSettings.ShowProductImagesOnShoppingCart;
            var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null);

            foreach (var orderItem in orderItems)
            {
                var orderItemModel = PrepareOrderItemModel(
                    order,
                    orderItem,
                    catalogSettings,
                    shoppingCartSettings,
                    mediaSettings);

                model.Items.Add(orderItemModel);
            }

            return(model);
        }
        protected OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }
            var model = new OrderDetailsModel();

            model.Id                     = order.Id;
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext);
            model.IsReOrderAllowed       = _orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.DisplayPdfInvoice      = _pdfSettings.Enabled;

            //shipping info
            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable     = true;
                model.ShippingAddress = order.ShippingAddress.ToModel();
                model.ShippingMethod  = order.ShippingMethod;


                //shipments (only already shipped)
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel()
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };
                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }
                    model.Shipments.Add(shipmentModel);
                }
            }


            //billing info
            model.BillingAddress = order.BillingAddress.ToModel();

            //VAT number
            model.VatNumber = order.VatNumber;

            //payment method
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod = paymentMethod != null?paymentMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) : order.PaymentMethodSystemName;

            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);

            //purchase order number (we have to find a better to inject this information because it's related to a certain plugin)
            if (paymentMethod != null && paymentMethod.PluginDescriptor.SystemName.Equals("Payments.PurchaseOrder", StringComparison.InvariantCultureIgnoreCase))
            {
                model.DisplayPurchaseOrderNumber = true;
                model.PurchaseOrderNumber        = order.PurchaseOrderNumber;
            }


            //totals)
            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                //order subtotal
                var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                //discount (applied to order subtotal)
                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
                //order shipping
                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                //payment method additional fee
                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                //order subtotal
                var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                //discount (applied to order subtotal)
                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
                //order shipping
                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                //payment method additional fee
                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
            }
            break;
            }

            //tax
            bool displayTax      = true;
            bool displayTaxRates = true;

            if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = _taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
                    //TODO pass languageId to _priceFormatter.FormatPrice
                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);

                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        model.TaxRates.Add(new OrderDetailsModel.TaxRate()
                        {
                            Rate = _priceFormatter.FormatTaxRate(tr.Key),
                            //TODO pass languageId to _priceFormatter.FormatPrice
                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage),
                        });
                    }
                }
            }
            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;


            //discount (applied to order total)
            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);
            }


            //gift cards
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                model.GiftCards.Add(new OrderDetailsModel.GiftCard()
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage),
                });
            }

            //reward points
            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);
            }

            //total
            var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);

            //checkout attributes
            model.CheckoutAttributeInfo = order.CheckoutAttributeDescription;

            //order notes
            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                model.OrderNotes.Add(new OrderDetailsModel.OrderNote()
                {
                    Note      = orderNote.FormatOrderNoteText(),
                    CreatedOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc)
                });
            }


            //purchased products
            model.ShowSku = _catalogSettings.ShowProductSku;
            var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null);

            foreach (var opv in orderProductVariants)
            {
                var opvModel = new OrderDetailsModel.OrderProductVariantModel()
                {
                    Id            = opv.Id,
                    Sku           = opv.ProductVariant.Sku,
                    ProductId     = opv.ProductVariant.ProductId,
                    ProductSeName = opv.ProductVariant.Product.GetSeName(),
                    Quantity      = opv.Quantity,
                    AttributeInfo = opv.AttributeDescription,
                };

                //product name
                if (!String.IsNullOrEmpty(opv.ProductVariant.GetLocalized(x => x.Name)))
                {
                    opvModel.ProductName = string.Format("{0} ({1})", opv.ProductVariant.Product.GetLocalized(x => x.Name), opv.ProductVariant.GetLocalized(x => x.Name));
                }
                else
                {
                    opvModel.ProductName = opv.ProductVariant.Product.GetLocalized(x => x.Name);
                }
                model.Items.Add(opvModel);

                //unit price, subtotal
                switch (order.CustomerTaxDisplayType)
                {
                case TaxDisplayType.ExcludingTax:
                {
                    var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceExclTax, order.CurrencyRate);
                    opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);

                    var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceExclTax, order.CurrencyRate);
                    opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
                break;

                case TaxDisplayType.IncludingTax:
                {
                    var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate);
                    opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);

                    var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceInclTax, order.CurrencyRate);
                    opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
                break;
                }
            }

            return(model);
        }
Example #3
0
        public virtual OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }
            var model = new OrderDetailsModel();

            model.Id                     = order.Id;
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext);
            model.IsReOrderAllowed       = _orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.PdfInvoiceDisabled     = _pdfSettings.DisablePdfInvoicesForPendingOrders && order.OrderStatus == OrderStatus.Pending;

            //shipping info
            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable   = true;
                model.PickUpInStore = order.PickUpInStore;
                if (!order.PickUpInStore)
                {
                    _addressModelFactory.PrepareAddressModel(model.ShippingAddress,
                                                             address: order.ShippingAddress,
                                                             excludeProperties: false,
                                                             addressSettings: _addressSettings);
                }
                else
                if (order.PickupAddress != null)
                {
                    model.PickupAddress = new AddressModel
                    {
                        Address1      = order.PickupAddress.Address1,
                        City          = order.PickupAddress.City,
                        CountryName   = order.PickupAddress.Country != null ? order.PickupAddress.Country.Name : string.Empty,
                        ZipPostalCode = order.PickupAddress.ZipPostalCode
                    }
                }
                ;
                model.ShippingMethod = order.ShippingMethod;


                //shipments (only already shipped)
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };
                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }
                    model.Shipments.Add(shipmentModel);
                }
            }


            //billing info
            _addressModelFactory.PrepareAddressModel(model.BillingAddress,
                                                     address: order.BillingAddress,
                                                     excludeProperties: false,
                                                     addressSettings: _addressSettings);

            //VAT number
            model.VatNumber = order.VatNumber;

            //payment method
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod = paymentMethod != null?paymentMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) : order.PaymentMethodSystemName;

            model.PaymentMethodStatus     = order.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext);
            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);
            //custom values
            model.CustomValues = order.DeserializeCustomValues();

            //order subtotal
            if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal)
            {
                //including tax

                //order subtotal
                var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                //discount (applied to order subtotal)
                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
            }
            else
            {
                //excluding tax

                //order subtotal
                var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                //discount (applied to order subtotal)
                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
            }

            if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                //including tax

                //order shipping
                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                //payment method additional fee
                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
            }
            else
            {
                //excluding tax

                //order shipping
                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                //payment method additional fee
                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
            }

            //tax
            bool displayTax      = true;
            bool displayTaxRates = true;

            if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = _taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Any();
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
                    //TODO pass languageId to _priceFormatter.FormatPrice
                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);

                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate = _priceFormatter.FormatTaxRate(tr.Key),
                            //TODO pass languageId to _priceFormatter.FormatPrice
                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage),
                        });
                    }
                }
            }
            model.DisplayTaxRates        = displayTaxRates;
            model.DisplayTax             = displayTax;
            model.DisplayTaxShippingInfo = _catalogSettings.DisplayTaxShippingInfoOrderDetailsPage;
            model.PricesIncludeTax       = order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax;

            //discount (applied to order total)
            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);
            }


            //gift cards
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                model.GiftCards.Add(new OrderDetailsModel.GiftCard
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage),
                });
            }

            //reward points
            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);
            }

            //total
            var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage);

            //checkout attributes
            model.CheckoutAttributeInfo = order.CheckoutAttributeDescription;

            //order notes
            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Id          = orderNote.Id,
                    HasDownload = orderNote.DownloadId > 0,
                    Note        = orderNote.FormatOrderNoteText(),
                    CreatedOn   = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc)
                });
            }


            //purchased products
            model.ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage;
            var orderItems = order.OrderItems;

            foreach (var orderItem in orderItems)
            {
                var orderItemModel = new OrderDetailsModel.OrderItemModel
                {
                    Id            = orderItem.Id,
                    OrderItemGuid = orderItem.OrderItemGuid,
                    Sku           = orderItem.Product.FormatSku(orderItem.AttributesXml, _productAttributeParser),
                    ProductId     = orderItem.Product.Id,
                    ProductName   = orderItem.Product.GetLocalized(x => x.Name),
                    ProductSeName = orderItem.Product.GetSeName(),
                    Quantity      = orderItem.Quantity,
                    AttributeInfo = orderItem.AttributeDescription,
                };
                //rental info
                if (orderItem.Product.IsRental)
                {
                    var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : "";
                    var rentalEndDate   = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : "";
                    orderItemModel.RentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"),
                                                              rentalStartDate, rentalEndDate);
                }
                model.Items.Add(orderItemModel);

                //unit price, subtotal
                if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                {
                    //including tax
                    var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                    orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);

                    var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate);
                    orderItemModel.SubTotal = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
                else
                {
                    //excluding tax
                    var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                    orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);

                    var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate);
                    orderItemModel.SubTotal = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }

                //downloadable products
                if (_downloadService.IsDownloadAllowed(orderItem))
                {
                    orderItemModel.DownloadId = orderItem.Product.DownloadId;
                }
                if (_downloadService.IsLicenseDownloadAllowed(orderItem))
                {
                    orderItemModel.LicenseId = orderItem.LicenseDownloadId.HasValue ? orderItem.LicenseDownloadId.Value : 0;
                }
            }

            return(model);
        }
Example #4
0
        public int SaveOrderDetails(string type, string productId, string unitPrice, string orderId, string productCount, string useStatus = null, string MemberCardNo = null, string RstType = null)
        {
            int i = 0;

            try
            {
                int count = 1;
                int.TryParse(productCount, out count);

                OrderDetailsModel    odm    = new OrderDetailsModel();
                OrderDetails         info   = new OrderDetails();
                MyMenuModel          odb    = new MyMenuModel();
                List <OrderDetails>  orderD = odm.getOrderDetailInfoData(productId, orderId);
                List <MyOrderDetail> detail = null;
                if (MemberCardNo != null)
                {
                    detail = odb.getMyOrderDetailListData(MemberCardNo, orderId, RstType);
                }
                if (orderD.Count > 0 && useStatus != "04")
                {
                    type = "Update";
                    info.ProductCount = count;
                    info.CreateDate   = DateTime.Now;
                    info.ProductId    = new Guid(productId);
                    info.OrderId      = new Guid(orderId);
                    info.TotalPrice   = Convert.ToDecimal(unitPrice) * count;
                }
                else
                {
                    if (useStatus == "04")
                    {
                        if (detail != null && detail.Count > 0)
                        {
                            foreach (MyOrderDetail item1 in detail)
                            {
                                if (item1.UseState == "04")
                                {
                                    //已经有赠送的菜。(先删除已有的赠送菜,再添加现选择有赠送菜)
                                    int j = odm.DelGiftOrderDetails(useStatus, orderId);
                                }
                            }
                        }
                    }
                    info.DetailsId    = Guid.NewGuid();
                    info.OrderId      = new Guid(orderId);
                    info.ProductId    = new Guid(productId);
                    info.UnitPrice    = Convert.ToDecimal(unitPrice);
                    info.TotalPrice   = Convert.ToDecimal(unitPrice) * count;
                    info.CreateDate   = DateTime.Now;
                    info.ProductCount = count;
                    if (useStatus != "04")
                    {
                        info.UseState = "00";
                    }
                    else
                    {
                        info.UseState = useStatus;
                    }
                }
                i = odm.SaveOrderDetails(type, info);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                i = 0;
            }

            return(i);
        }
Example #5
0
        public List <TreatmentData> getTreatmentData(OrderDetailsModel orderDetailsModel)
        {
            List <TreatmentData> treatmentDataList = new List <TreatmentData>();

            foreach (var orderItemModel in orderDetailsModel.Items)
            {
                TreatmentData treatmentDataItem = new TreatmentData();
                treatmentDataItem.id = orderItemModel.Id;
                var specAttr            = _specificationAttributeService.GetProductSpecificationAttributes(orderItemModel.ProductId);
                var imageSpecAttrOption = specAttr.Select(x => x.SpecificationAttributeOption);
                if (imageSpecAttrOption.Any())
                {
                    var thumbnailBackground = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == "Treatment");
                    if (thumbnailBackground.Any())
                    {
                        foreach (var thbackground in thumbnailBackground)
                        {
                            var gbsBackGroundName = thbackground.Name;
                            treatmentDataItem.DefaultColor = "";
                            treatmentDataItem.ClassName    = "";
                            if (gbsBackGroundName.Any())
                            {
                                switch (gbsBackGroundName)
                                {
                                case "TreatmentImage":
                                    var backGroundShapeName = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == gbsBackGroundName);
                                    if (backGroundShapeName.Any())
                                    {
                                        treatmentDataItem.ClassName = backGroundShapeName.FirstOrDefault().Name;
                                    }
                                    break;

                                case "TreatmentFill":
                                    var backGroundFillOption = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == gbsBackGroundName);
                                    if (backGroundFillOption.Any())
                                    {
                                        var fillOptionValue = backGroundFillOption.FirstOrDefault().Name;
                                        switch (fillOptionValue)
                                        {
                                        case "TreatmentFillPattern":
                                            var img = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == backGroundFillOption.FirstOrDefault().Name);
                                            if (img.Any())
                                            {
                                                treatmentDataItem.DefaultColor = "background-image:url('" + img.FirstOrDefault().ColorSquaresRgb + "')";
                                            }
                                            break;

                                        case "TreatmentFillColor":
                                            var color = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == backGroundFillOption.FirstOrDefault().Name);
                                            if (color.Any())
                                            {
                                                treatmentDataItem.DefaultColor = "background-color:" + color.FirstOrDefault().ColorSquaresRgb;
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        var defaultColorOption = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == "DefaultEnvelopeColor");
                        var defaultEnvelopType = imageSpecAttrOption.Where(x => x.SpecificationAttribute.Name == "Orientation");
                        if (defaultEnvelopType.Any())
                        {
                            string className = defaultEnvelopType.FirstOrDefault().Name;
                            treatmentDataItem.ClassName = className;

                            if (defaultColorOption.Any())
                            {
                                var optionValue = defaultColorOption.FirstOrDefault().ColorSquaresRgb;
                                treatmentDataItem.DefaultColor = optionValue;
                                if (optionValue.Contains("#") && optionValue.Length == 7)
                                {
                                    treatmentDataItem.DefaultColor = "background-color:" + optionValue;
                                }
                                else
                                {
                                    treatmentDataItem.DefaultColor = "background-image:url('" + optionValue + "')";
                                }
                            }
                            else
                            {
                                treatmentDataItem.DefaultColor = "";
                            }
                        }
                    }
                }
                treatmentDataList.Add(treatmentDataItem);
            }
            return(treatmentDataList);
        }
Example #6
0
        public ViewResult Purchase(OrderDetailsModel orderDetailsModel)
        {
            using (IfxConnection Con = new IfxConnection(connString))
            {
                Con.Open();
                int availableQuantity = 0;

                string     selectProductDetails = "select Count from product where productid = ?";
                IfxCommand cmd = new IfxCommand(selectProductDetails, Con);
                cmd.Parameters.Add("productid", IfxType.Serial).Value = orderDetailsModel.ProductID;
                try
                {
                    IfxDataReader rows = cmd.ExecuteReader();
                    while (rows.Read())
                    {
                        availableQuantity = Convert.ToInt32(rows[0]);
                    }
                    rows.Close();
                }
                catch (IfxException ex)
                {
                    Con.Close();
                    orderDetailsModel.ErrorMessage = "Error : " + ex.Message;
                }

                if (orderDetailsModel.Count > availableQuantity)
                {
                    Con.Close();
                    orderDetailsModel.ErrorMessage = "Cannot purchase " + orderDetailsModel.Count + " quantities, available quantities are : " + availableQuantity;
                }
                else
                {
                    int newProductQuantity = availableQuantity - orderDetailsModel.Count;

                    string     updateProductQuantity = "UPDATE Product SET count = ? Where productid = ?";
                    IfxCommand cmd1 = new IfxCommand(updateProductQuantity, Con);
                    cmd1.Parameters.Add("count", IfxType.Int).Value        = newProductQuantity;
                    cmd1.Parameters.Add("productid", IfxType.Serial).Value = orderDetailsModel.ProductID;
                    cmd1.ExecuteNonQuery();

                    try
                    {
                        insertNewOrder(Con, orderDetailsModel);
                    }
                    catch (Exception ex)
                    {
                        string     createOrderTable = "Create table orderdetails (orderid serial PRIMARY KEY, productid int, productname varchar(50), price decimal(18,2), count int, totalamount decimal(18,2))";
                        IfxCommand cmd2             = new IfxCommand(createOrderTable, Con);
                        cmd2.ExecuteNonQuery();
                        insertNewOrder(Con, orderDetailsModel);
                    }
                    finally
                    {
                        Con.Close();
                        orderDetailsModel.ErrorMessage = "Purchase successful";
                    }
                }
                return(View(orderDetailsModel));
                //return RedirectToAction("Index");
            }
        }
Example #7
0
        public ActionResult CheckOuts()
        {
            /*
             * Check if the user has logged on and redirect the user to login if not so
             * Send the user to registration page if not registered
             * Proceed to checkout if all is well
             */
            int uid = Convert.ToInt32(Session["userID"]);

            //Gettting the cuurrent shopping cart
            var     currentShoppingCart = Session["Cart"];
            decimal totalprice          = 0;

            if (Session["userID"] != null)
            {
                OrderModel newOrder = new OrderModel();
                newOrder.customerID = uid;
                newOrder.orderDate  = DateTime.Now;

                DateTime shippingDate = AddWorkdays(DateTime.Now, 5);
                newOrder.shippingDate = shippingDate;


                //get the customer address
                var getAddress = (from a in db.AddressModelSet
                                  where a.customerID == uid
                                  select a).ToList();


                foreach (var address in getAddress)
                {
                    string addr     = address.address;
                    string city     = address.city;
                    string postCode = address.postalCode;

                    newOrder.shippingAddress = addr + ", " + city + ", " + postCode;
                }
                //order.shippingAddress =
                newOrder.status = "In Process";
                //get total price
                foreach (var item in (List <Item>)currentShoppingCart)
                {
                    totalprice          = totalprice + (item.Prdcts.price + item.Quantity);
                    newOrder.totalPrice = totalprice;
                }
                db.OrderModelSet.Add(newOrder);
                db.SaveChanges();



                //get the orderId of the current user
                var getOrderID = (from o in db.OrderModelSet
                                  where o.customerID == uid
                                  select o).ToList();
                int orderID = 0;
                foreach (var o in getOrderID)
                {
                    orderID = o.orderID;
                }


                // var listOrderDetails = new List<OrderDetailsModel>();

                foreach (var item in (List <Item>)currentShoppingCart)
                {
                    var orderDetails = new OrderDetailsModel();
                    orderDetails.orderID         = orderID;
                    orderDetails.productID       = item.Prdcts.productID;
                    orderDetails.quantityOrdered = item.Quantity;
                    orderDetails.priceEach       = item.Prdcts.price;

                    db.OrderDetailsModelSet.Add(orderDetails);
                    db.SaveChanges();
                }
            }


            //return RedirectToAction("Login", "Account" );


            //var getOrder = db.OrderModelSet.Select(x => x).Where(x => x.customerID == uid).ToList();
            return(View("Index"));
        }
        //OrderDetails
        public List <OrderDetailsModel> GetOrdersDetailsById(int id)
        {
            List <OrderDetailsModel> lstOrderDetails = new List <OrderDetailsModel>();

            SqlConnection conn = new SqlConnection(connString);

            try
            {
                SqlCommand cmd = new SqlCommand("GetOrdersDetailsById", conn);
                cmd.Parameters.AddWithValue("@OrderID", id);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;

                if (conn != null && conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                DataSet ds = new DataSet();
                da.Fill(ds);

                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            OrderDetailsModel objOrderDetails = new OrderDetailsModel();


                            objOrderDetails.ID           = Convert.ToInt32(dt.Rows[i]["ID"]);
                            objOrderDetails.OrderID      = Convert.ToInt32(dt.Rows[i]["OrderID"]);
                            objOrderDetails.ProductCode  = Convert.ToString(dt.Rows[i]["ProductCode"]);
                            objOrderDetails.ProductName  = Convert.ToString(dt.Rows[i]["ProductName"]);
                            objOrderDetails.ProductImage = Convert.ToString(dt.Rows[i]["ProductImage"]);
                            objOrderDetails.Unit         = Convert.ToString(dt.Rows[i]["Unit"]);
                            objOrderDetails.Rate         = Convert.ToDecimal(dt.Rows[i]["Rate"]);
                            objOrderDetails.CustomerID   = Convert.ToInt32(dt.Rows[i]["CustomerID"]);
                            objOrderDetails.CustomerName = Convert.ToString(dt.Rows[i]["CustomerName"]);
                            objOrderDetails.Qty          = Convert.ToInt32(dt.Rows[i]["Qty"]);
                            objOrderDetails.Amount       = Convert.ToDecimal(dt.Rows[i]["Amount"]);

                            objOrderDetails.TotalQty    = Convert.ToInt32(dt.Rows[i]["TotalQty"]);
                            objOrderDetails.TotalAmount = Convert.ToDecimal(dt.Rows[i]["TotalAmount"]);

                            lstOrderDetails.Add(objOrderDetails);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            return(lstOrderDetails);
        }
        public string AlipayNotify()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
            HttpRequestBase request = context.Request;
            SortedDictionary <string, string> sPara = GetRequestPost();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify    = new Notify();
                bool   verifyResult = aliNotify.Verify(sPara, request["notify_id"], request["sign"]);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
                    //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表

                    //商户订单号
                    string out_trade_no = request["out_trade_no"];

                    //支付宝交易号
                    string trade_no = request["trade_no"];

                    //交易状态
                    string trade_status = request["trade_status"];


                    if (request["trade_status"] == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的

                        using (Entity entity = new Entity())
                        {
                            Order order = entity.Order.Find(out_trade_no);
                            if ((order.State & 2) == 0)
                            {
                                order.State |= 2;
                                OrderDetailsModel orderDetailsModel = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderDetailsModel>(order.Detail);
                                foreach (var v in orderDetailsModel.OrderDetailModelList)
                                {
                                    entity.Good.Find(v.GoodID).SalesVolume++;
                                    entity.GoodChild.Find(v.GoodChildID).SalesVolume++;
                                }
                                OrderLog orderLog = new OrderLog();
                                orderLog.OrderID    = order.OrderID;
                                orderLog.State      = 2;
                                orderLog.CreateTime = DateTime.Now;
                                orderLog.Mark       = "支付宝返回成功";
                                entity.OrderLog.Add(orderLog);
                                order.OrderExtend.ThirdPartyPaymentNumber = trade_no;

                                entity.SaveChanges();
                            }
                        }
                    }
                    else if (request["trade_status"] == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //付款完成后,支付宝系统发送该交易状态通知
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的

                        using (Entity entity = new Entity())
                        {
                            Order order = entity.Order.Find(out_trade_no);
                            if ((order.State & 2) == 0)
                            {
                                order.State |= 2;
                                OrderDetailsModel orderDetailsModel = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderDetailsModel>(order.Detail);
                                foreach (var v in orderDetailsModel.OrderDetailModelList)
                                {
                                    entity.Good.Find(v.GoodID).SalesVolume++;
                                    entity.GoodChild.Find(v.GoodChildID).SalesVolume++;
                                }
                                OrderLog orderLog = new OrderLog();
                                orderLog.OrderID    = order.OrderID;
                                orderLog.State      = 2;
                                orderLog.CreateTime = DateTime.Now;
                                orderLog.Mark       = "支付宝返回成功";
                                entity.OrderLog.Add(orderLog);
                                order.OrderExtend.ThirdPartyPaymentNumber = trade_no;
                                entity.SaveChanges();
                                ThreadPool.QueueUserWorkItem(delegate(object a)
                                {
                                    string tt       = @"有用户已经支付订单 " + order.OrderID + "金额 " + order.OrderExtend.PaymentPrice + " 请尽快发货";
                                    UserSMS userSMS = new UserSMS()
                                    {
                                        Tel = ConfigurationManager.AppSettings["SMSAdmin"]
                                    };
                                    Random random        = new Random();
                                    userSMS.SerialNumber = DateTime.Now.ToString("yyyyMMddhhmmssfff" + random.Next(100, 999).ToString());
                                    string bb            = SMS.sendSMS(userSMS.Tel, tt, userSMS.SerialNumber);
                                });
                            }
                        }
                    }
                    else
                    {
                        OrderLog orderLog = new OrderLog();
                        orderLog.OrderID = out_trade_no;

                        orderLog.CreateTime = DateTime.Now;
                        orderLog.Mark       = "支付宝返回" + request["trade_status"];

                        using (Entity entity = new Entity())
                        {
                            entity.OrderLog.Add(orderLog);
                            entity.SaveChanges();
                        }
                    }

                    //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

                    return("success");  //请不要修改或删除

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    return("fail");
                }
            }
            else
            {
                return("无通知参数");
            }
        }
        public IHttpActionResult Post(OrderDetailsModel orderDetail)
        {
            if (orderDetail.PaymentTypeId == 33)
            {
                var encryption = Encrypt((orderDetail.CardNumber).ToString(), true);
                var card       = Uow.Repository <Card>().FirstOrDefault(c => (c.CardNumber == encryption) && (c.Cvv == orderDetail.CVV));
                if (card != null)
                {
                    if (card.Amount >= orderDetail.Amount)
                    {
                        var cartList = Uow.Repository <Cart>().All();
                        if (cartList != null)
                        {
                            string             message;
                            int                flag            = 0;
                            List <OrderDetail> orderDetailList = new List <OrderDetail>();
                            foreach (var item in cartList)
                            {
                                if (item.UserId == orderDetail.UserId)
                                {
                                    OrderDetail detailTemp = new OrderDetail();
                                    detailTemp.ProductId = item.ProductId;
                                    detailTemp.Quantity  = item.Quantity;
                                    detailTemp.SubTotal  = item.SubTotal;
                                    var product = Uow.Repository <Product>().FirstOrDefault(p => p.ProductId == item.ProductId);
                                    detailTemp.DiscountId = product.DiscountId;
                                    detailTemp.OrderId    = orderDetail.OrderId;
                                    orderDetailList.Add(detailTemp);
                                }
                            }

                            if (orderDetailList != null)
                            {
                                try
                                {
                                    message = (OrderDetailDomain.Post(orderDetailList));
                                    if (message != "Order Placed!!")
                                    {
                                        flag = 1;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }

                            if (flag != 1)
                            {
                                var Order = Uow.Repository <Order>().FirstOrDefault(o => o.OrderId == orderDetail.OrderId);
                                Order.OrderStatus   = "true";
                                Order.PaymentTypeId = orderDetail.PaymentTypeId;
                                OrderDomain.Put(Order);
                                card.Amount = card.Amount - orderDetail.Amount;
                                CardDomain.Put(card);
                                return(Ok("items ordered"));
                            }
                            else
                            {
                                return(Ok("Order Not Placed!"));
                            }
                        }
                        else
                        {
                            return(Ok("cart is empty"));
                        }
                    }

                    else
                    {
                        return(Ok("Insufficient amount in card"));
                    }
                }
                else
                {
                    return(Ok());
                }
            }
            else if (orderDetail.PaymentTypeId == 34)
            {
                var balanceCheck = BalanceDomain.GetBy(orderDetail.UserId);
                if (balanceCheck.BalanceAmount >= orderDetail.Amount)
                {
                    balanceCheck.BalanceAmount = balanceCheck.BalanceAmount - orderDetail.Amount;
                    var message = BalanceDomain.Put(balanceCheck);
                    if (message == "Item Updated.")
                    {
                        return(Ok("items ordered"));
                    }
                    else
                    {
                        return(Ok());
                    }
                }
                else
                {
                    return(Ok("balance is not enough"));
                }
            }
            else
            {
                return(Ok("error"));
            }
        }
Example #11
0
        private OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }
            var model = new OrderDetailsModel();

            model.Id                     = order.Id;
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext);
            model.IsReOrderAllowed       = _orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.DisplayPdfInvoice      = _pdfSettings.Enabled;


            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable     = true;
                model.ShippingAddress = order.ShippingAddress.ToModel();
                model.ShippingMethod  = order.ShippingMethod;
                model.OrderWeight     = order.OrderWeight;
                var baseWeight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId);
                if (baseWeight != null)
                {
                    model.BaseWeightIn = baseWeight.Name;
                }

                if (order.ShippedDateUtc.HasValue)
                {
                    model.ShippedDate = _dateTimeHelper.ConvertToUserTime(order.ShippedDateUtc.Value, DateTimeKind.Utc).ToString("D");
                }

                if (order.DeliveryDateUtc.HasValue)
                {
                    model.DeliveryDate = _dateTimeHelper.ConvertToUserTime(order.DeliveryDateUtc.Value, DateTimeKind.Utc).ToString("D");
                }

                model.TrackingNumber = order.TrackingNumber;
            }



            model.BillingAddress = order.BillingAddress.ToModel();


            model.VatNumber = order.VatNumber;


            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod           = paymentMethod != null ? paymentMethod.PluginDescriptor.FriendlyName : order.PaymentMethodSystemName;
            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);


            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);

                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }

                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);

                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);

                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }

                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);

                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
            }
            break;
            }


            bool displayTax      = true;
            bool displayTaxRates = true;

            if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = _taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);

                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false);

                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        model.TaxRates.Add(new OrderDetailsModel.TaxRate()
                        {
                            Rate = _priceFormatter.FormatTaxRate(tr.Key),

                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false),
                        });
                    }
                }
            }
            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;



            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false);
            }



            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                model.GiftCards.Add(new OrderDetailsModel.GiftCard()
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false),
                });
            }


            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false);
            }


            var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false);


            model.CheckoutAttributeInfo = order.CheckoutAttributeDescription;


            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                model.OrderNotes.Add(new OrderDetailsModel.OrderNote()
                {
                    Note      = Fara.Core.Html.HtmlHelper.FormatText(orderNote.Note, false, true, false, false, false, false),
                    CreatedOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc)
                });
            }



            model.ShowSku = _catalogSettings.ShowProductSku;
            var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null);

            foreach (var opv in orderProductVariants)
            {
                var opvModel = new OrderDetailsModel.OrderProductVariantModel()
                {
                    Id            = opv.Id,
                    Sku           = opv.ProductVariant.Sku,
                    ProductId     = opv.ProductVariant.ProductId,
                    ProductSeName = opv.ProductVariant.Product.GetSeName(),
                    Quantity      = opv.Quantity,
                    AttributeInfo = opv.AttributeDescription,
                };


                if (!string.IsNullOrEmpty(opv.ProductVariant.GetLocalized(x => x.Name)))
                {
                    opvModel.ProductName = string.Format("{0} ({1})", opv.ProductVariant.Product.GetLocalized(x => x.Name), opv.ProductVariant.GetLocalized(x => x.Name));
                }
                else
                {
                    opvModel.ProductName = opv.ProductVariant.Product.GetLocalized(x => x.Name);
                }
                model.Items.Add(opvModel);


                switch (order.CustomerTaxDisplayType)
                {
                case TaxDisplayType.ExcludingTax:
                {
                    var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceExclTax, order.CurrencyRate);
                    opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);

                    var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceExclTax, order.CurrencyRate);
                    opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false);
                }
                break;

                case TaxDisplayType.IncludingTax:
                {
                    var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate);
                    opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);

                    var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceInclTax, order.CurrencyRate);
                    opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true);
                }
                break;
                }
            }

            return(model);
        }
Example #12
0
        // GET: Admin/Order/Details/5
        public ActionResult Details(long id)
        {
            var r = new OrderDetailsModel().GetDetailsByOrderID(id);

            return(View(r));
        }
        public ActionResult Importexcel()
        {
            NewOrderModel objNewOrder = new NewOrderModel();
            int           custId      = 0;
            int           orderId     = 0;

            try
            {
                custId  = Convert.ToInt32(TempData["CustomerId"]);
                orderId = Convert.ToInt32(TempData["orderId"]);

                objNewOrder.OrderID = orderId;

                if (custId > 0)
                {
                    objNewOrder.CustomerID = custId;

                    DataTable dt = new DataTable();

                    if (Request.Files["FileUpload1"].ContentLength > 0)
                    {
                        string extension  = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
                        string query      = null;
                        string connString = "";

                        string[] validFileTypes = { ".xls", ".xlsx", ".csv" };

                        string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
                        if (!Directory.Exists(path1))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
                        }
                        if (validFileTypes.Contains(extension))
                        {
                            if (System.IO.File.Exists(path1))
                            {
                                System.IO.File.Delete(path1);
                            }
                            Request.Files["FileUpload1"].SaveAs(path1);

                            //Connection String to Excel Workbook
                            if (extension.Trim() == ".xls")
                            {
                                connString   = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                                dt           = ConvertXSLXtoDataTable(path1, connString);
                                ViewBag.Data = dt;
                            }
                            else if (extension.Trim() == ".xlsx")
                            {
                                connString   = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                                dt           = ConvertXSLXtoDataTable(path1, connString);
                                ViewBag.Data = dt;
                            }
                            else if (extension == ".csv")
                            {
                                dt           = ConvertCSVtoDataTable(path1);
                                ViewBag.Data = dt;
                            }

                            if (dt != null && dt.Rows.Count > 1)
                            {
                                List <OrderDetailsModel> lstOrderDetails = new List <OrderDetailsModel>();
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    OrderDetailsModel objOrderDetails = new OrderDetailsModel();

                                    objOrderDetails.ProductCode = Convert.ToString(dt.Rows[i][0]);
                                    objOrderDetails.Qty         = Convert.ToInt32(dt.Rows[i][1]);

                                    ProductModel objProduct = new ProductModel();

                                    objProduct = objBusiness.GetProductByCode(objOrderDetails.ProductCode);

                                    if (objProduct != null)
                                    {
                                        objOrderDetails.Amount = objProduct.Rate * objOrderDetails.Qty;

                                        objNewOrder.TotalAmount = objNewOrder.TotalAmount + objOrderDetails.Amount;

                                        objNewOrder.TotalQty = objNewOrder.TotalQty + objOrderDetails.Qty;

                                        lstOrderDetails.Add(objOrderDetails);
                                    }
                                }

                                objNewOrder.lstOrderDetails = lstOrderDetails;


                                if (objNewOrder.lstOrderDetails != null)
                                {
                                    orderId = objBusiness.AddOrderAndDetails(objNewOrder);

                                    if (orderId > 0)
                                    {
                                        ViewBag.Result = "Success: Excel Uploaded Successfully!";

                                        // Source file to be renamed
                                        string sourceFile = path1;
                                        // Create a FileInfo
                                        System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
                                        // Check if file is there
                                        if (fi.Exists)
                                        {
                                            string fileName = "OrderID_" + orderId + System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();

                                            string newFilePath = Server.MapPath("~/Content/Uploads/") + fileName;

                                            if (System.IO.File.Exists(newFilePath))
                                            {
                                                System.IO.File.Delete(newFilePath);
                                            }

                                            fi.MoveTo(Server.MapPath("~/Content/Uploads/") + fileName);
                                        }
                                    }
                                    else
                                    {
                                        ViewBag.Error = "Failure: Something went wrong while uploading.";
                                    }
                                }
                            }
                        }
                        else
                        {
                            ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format";
                        }
                    }
                }
                else
                {
                    ViewBag.Error = "Something went wrong";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(View());
        }
Example #14
0
        public async Task <OrderDetailsModel> PrepareOrderDetailsModelAsync(Order order)
        {
            Guard.NotNull(order, nameof(order));

            var settingFactory = _services.SettingFactory;
            var store          = await _db.Stores.FindByIdAsync(order.StoreId, false) ?? _services.StoreContext.CurrentStore;

            var language = _services.WorkContext.WorkingLanguage;

            var orderSettings = await settingFactory.LoadSettingsAsync <OrderSettings>(store.Id);

            var catalogSettings = await settingFactory.LoadSettingsAsync <CatalogSettings>(store.Id);

            var taxSettings = await settingFactory.LoadSettingsAsync <TaxSettings>(store.Id);

            var pdfSettings = await settingFactory.LoadSettingsAsync <PdfSettings>(store.Id);

            var addressSettings = await settingFactory.LoadSettingsAsync <AddressSettings>(store.Id);

            var companyInfoSettings = await settingFactory.LoadSettingsAsync <CompanyInformationSettings>(store.Id);

            var shoppingCartSettings = await settingFactory.LoadSettingsAsync <ShoppingCartSettings>(store.Id);

            var mediaSettings = await settingFactory.LoadSettingsAsync <MediaSettings>(store.Id);

            var model = new OrderDetailsModel
            {
                Id                     = order.Id,
                StoreId                = order.StoreId,
                CustomerLanguageId     = order.CustomerLanguageId,
                CustomerComment        = order.CustomerOrderComment,
                OrderNumber            = order.GetOrderNumber(),
                CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc),
                OrderStatus            = await _services.Localization.GetLocalizedEnumAsync(order.OrderStatus),
                IsReOrderAllowed       = orderSettings.IsReOrderAllowed,
                IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order),
                DisplayPdfInvoice      = pdfSettings.Enabled,
                RenderOrderNotes       = pdfSettings.RenderOrderNotes,
                // Shipping info.
                ShippingStatus = await _services.Localization.GetLocalizedEnumAsync(order.ShippingStatus)
            };

            // TODO: refactor modelling for multi-order processing.
            var companyCountry = await _db.Countries.FindByIdAsync(companyInfoSettings.CountryId, false);

            model.MerchantCompanyInfo        = companyInfoSettings;
            model.MerchantCompanyCountryName = companyCountry?.GetLocalized(x => x.Name);

            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable = true;
                await MapperFactory.MapAsync(order.ShippingAddress, model.ShippingAddress);

                model.ShippingMethod = order.ShippingMethod;

                // Shipments (only already shipped).
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };

                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }

                    model.Shipments.Add(shipmentModel);
                }
            }

            await MapperFactory.MapAsync(order.BillingAddress, model.BillingAddress);

            model.VatNumber = order.VatNumber;

            // Payment method.
            var paymentMethod = await _paymentService.LoadPaymentMethodBySystemNameAsync(order.PaymentMethodSystemName);

            model.PaymentMethodSystemName = order.PaymentMethodSystemName;
            // TODO: (mh) (core)
            //model.PaymentMethod = paymentMethod != null ? _pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : order.PaymentMethodSystemName;
            model.PaymentMethod           = order.PaymentMethodSystemName;
            model.CanRePostProcessPayment = await _paymentService.CanRePostProcessPaymentAsync(order);

            // Purchase order number (we have to find a better to inject this information because it's related to a certain plugin).
            if (paymentMethod != null && paymentMethod.Metadata.SystemName.Equals("Smartstore.PurchaseOrderNumber", StringComparison.InvariantCultureIgnoreCase))
            {
                model.DisplayPurchaseOrderNumber = true;
                model.PurchaseOrderNumber        = order.PurchaseOrderNumber;
            }

            if (order.AllowStoringCreditCardNumber)
            {
                model.CardNumber             = _encryptor.DecryptText(order.CardNumber);
                model.MaskedCreditCardNumber = _encryptor.DecryptText(order.MaskedCreditCardNumber);
                model.CardCvv2            = _encryptor.DecryptText(order.CardCvv2);
                model.CardExpirationMonth = _encryptor.DecryptText(order.CardExpirationMonth);
                model.CardExpirationYear  = _encryptor.DecryptText(order.CardExpirationYear);
            }

            if (order.AllowStoringDirectDebit)
            {
                model.DirectDebitAccountHolder = _encryptor.DecryptText(order.DirectDebitAccountHolder);
                model.DirectDebitAccountNumber = _encryptor.DecryptText(order.DirectDebitAccountNumber);
                model.DirectDebitBankCode      = _encryptor.DecryptText(order.DirectDebitBankCode);
                model.DirectDebitBankName      = _encryptor.DecryptText(order.DirectDebitBankName);
                model.DirectDebitBIC           = _encryptor.DecryptText(order.DirectDebitBIC);
                model.DirectDebitCountry       = _encryptor.DecryptText(order.DirectDebitCountry);
                model.DirectDebitIban          = _encryptor.DecryptText(order.DirectDebitIban);
            }

            // TODO: (mh) (core) Reimplement when pricing is ready.
            // Totals.
            var customerCurrency = await _db.Currencies
                                   .AsNoTracking()
                                   .Where(x => x.CurrencyCode == order.CustomerCurrencyCode)
                                   .FirstOrDefaultAsync();

            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                // Order subtotal.
                var orderSubtotalExclTax = _currencyService.ConvertToExchangeRate(order.OrderSubtotalExclTax, order.CurrencyRate, customerCurrency);
                model.OrderSubtotal = orderSubtotalExclTax.ToString();

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountExclTax = _currencyService.ConvertToExchangeRate(order.OrderSubTotalDiscountExclTax, order.CurrencyRate, customerCurrency);
                if (orderSubTotalDiscountExclTax > 0)
                {
                    model.OrderSubTotalDiscount = (orderSubTotalDiscountExclTax * -1).ToString();
                }

                // Order shipping.
                var orderShippingExclTax = _currencyService.ConvertToExchangeRate(order.OrderShippingExclTax, order.CurrencyRate, customerCurrency);
                model.OrderShipping = orderShippingExclTax.ToString();

                // Payment method additional fee.
                var paymentMethodAdditionalFeeExclTax = _currencyService.ConvertToExchangeRate(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate, customerCurrency);
                if (paymentMethodAdditionalFeeExclTax != 0)
                {
                    model.PaymentMethodAdditionalFee = paymentMethodAdditionalFeeExclTax.ToString();
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                // Order subtotal.
                var orderSubtotalInclTax = _currencyService.ConvertToExchangeRate(order.OrderSubtotalInclTax, order.CurrencyRate, customerCurrency);
                model.OrderSubtotal = orderSubtotalInclTax.ToString();

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountInclTax = _currencyService.ConvertToExchangeRate(order.OrderSubTotalDiscountInclTax, order.CurrencyRate, customerCurrency);
                if (orderSubTotalDiscountInclTax > 0)
                {
                    model.OrderSubTotalDiscount = (orderSubTotalDiscountInclTax * -1).ToString();
                }

                // Order shipping.
                var orderShippingInclTax = _currencyService.ConvertToExchangeRate(order.OrderShippingInclTax, order.CurrencyRate, customerCurrency);
                model.OrderShipping = orderShippingInclTax.ToString();

                // Payment method additional fee.
                var paymentMethodAdditionalFeeInclTax = _currencyService.ConvertToExchangeRate(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate, customerCurrency);
                if (paymentMethodAdditionalFeeInclTax != 0)
                {
                    model.PaymentMethodAdditionalFee = paymentMethodAdditionalFeeInclTax.ToString();
                }
            }
            break;
            }

            // Tax.
            var displayTax      = true;
            var displayTaxRates = true;

            if (taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertToExchangeRate(order.OrderTax, order.CurrencyRate, customerCurrency);
                    model.Tax = orderTaxInCustomerCurrency.ToString();

                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        var rate     = _taxService.FormatTaxRate(tr.Key);
                        var labelKey = _services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "ShoppingCart.Totals.TaxRateLineIncl" : "ShoppingCart.Totals.TaxRateLineExcl";

                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate  = rate,
                            Label = T(labelKey, rate),
                            Value = _currencyService.ConvertToExchangeRate(tr.Value, order.CurrencyRate, customerCurrency).ToString()
                        });
                    }
                }
            }

            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;

            // Discount (applied to order total).
            var orderDiscountInCustomerCurrency = _currencyService.ConvertToExchangeRate(order.OrderDiscount, order.CurrencyRate, customerCurrency);

            if (orderDiscountInCustomerCurrency > 0)
            {
                model.OrderTotalDiscount = (orderDiscountInCustomerCurrency * -1).ToString();
            }

            // Gift cards.
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                var remainingAmountBase = _giftCardService.GetRemainingAmount(gcuh.GiftCard);
                var remainingAmount     = _currencyService.ConvertToExchangeRate(remainingAmountBase.Amount, order.CurrencyRate, customerCurrency);
                var usedAmount          = _currencyService.ConvertToExchangeRate(gcuh.UsedValue, order.CurrencyRate, customerCurrency);

                var gcModel = new OrderDetailsModel.GiftCard
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = (usedAmount * -1).ToString(),
                    Remaining  = remainingAmount.ToString()
                };

                model.GiftCards.Add(gcModel);
            }

            // Reward points         .
            if (order.RedeemedRewardPointsEntry != null)
            {
                var usedAmount = _currencyService.ConvertToExchangeRate(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate, customerCurrency);

                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = (usedAmount * -1).ToString();
            }

            // Credit balance.
            if (order.CreditBalance > 0)
            {
                var convertedCreditBalance = _currencyService.ConvertToExchangeRate(order.CreditBalance, order.CurrencyRate, customerCurrency);
                model.CreditBalance = (convertedCreditBalance * -1).ToString();
            }

            // Total.
            (var orderTotal, var roundingAmount) = await _orderService.GetOrderTotalInCustomerCurrencyAsync(order, customerCurrency);

            model.OrderTotal = orderTotal.ToString();

            if (roundingAmount != 0)
            {
                model.OrderTotalRounding = roundingAmount.ToString();
            }

            // Checkout attributes.
            model.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable(HtmlUtils.ConvertHtmlToPlainText(order.CheckoutAttributeDescription));

            // Order notes.
            await _db.LoadCollectionAsync(order, x => x.OrderNotes);

            var orderNotes = order.OrderNotes
                             .Where(x => x.DisplayToCustomer)
                             .OrderByDescending(x => x.CreatedOnUtc)
                             .ToList();

            foreach (var orderNote in orderNotes)
            {
                var createdOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc);

                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Note              = orderNote.FormatOrderNoteText(),
                    CreatedOn         = createdOn,
                    FriendlyCreatedOn = orderNote.CreatedOnUtc.Humanize()
                });
            }

            // Purchased products.
            model.ShowSku                 = catalogSettings.ShowProductSku;
            model.ShowProductImages       = shoppingCartSettings.ShowProductImagesOnShoppingCart;
            model.ShowProductBundleImages = shoppingCartSettings.ShowProductBundleImagesOnShoppingCart;
            model.BundleThumbSize         = mediaSettings.CartThumbBundleItemPictureSize;

            await _db.LoadCollectionAsync(order, x => x.OrderItems, false, q => q.Include(x => x.Product));

            foreach (var orderItem in order.OrderItems)
            {
                var orderItemModel = await PrepareOrderItemModelAsync(order, orderItem, catalogSettings, shoppingCartSettings, mediaSettings, customerCurrency);

                model.Items.Add(orderItemModel);
            }

            return(model);
        }