private decimal GetConvertedRate(decimal rate, Currency source, Currency target) => (source.CurrencyCode == target.CurrencyCode) ? rate : _currencyService.ConvertCurrency(rate, source, target);
protected virtual CustomerOrderListModel PrepareCustomerOrderListModel() { var model = new CustomerOrderListModel(); var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id); foreach (var order in orders) { var orderModel = new CustomerOrderListModel.OrderDetailsModel { Id = order.Id, CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc), OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext), PaymentStatus = order.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext), ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext), IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order) }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); model.Orders.Add(orderModel); } var recurringPayments = _orderService.SearchRecurringPayments(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id, 0, null, 0, int.MaxValue); foreach (var recurringPayment in recurringPayments) { var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel { Id = recurringPayment.Id, StartDate = _dateTimeHelper.ConvertToUserTime(recurringPayment.StartDateUtc, DateTimeKind.Utc).ToString(), CycleInfo = string.Format("{0} {1}", recurringPayment.CycleLength, recurringPayment.CyclePeriod.GetLocalizedEnum(_localizationService, _workContext)), NextPayment = recurringPayment.NextPaymentDate.HasValue ? _dateTimeHelper.ConvertToUserTime(recurringPayment.NextPaymentDate.Value, DateTimeKind.Utc).ToString() : "", TotalCycles = recurringPayment.TotalCycles, CyclesRemaining = recurringPayment.CyclesRemaining, InitialOrderId = recurringPayment.InitialOrder.Id, CanCancel = _orderProcessingService.CanCancelRecurringPayment(_workContext.CurrentCustomer, recurringPayment), }; model.RecurringOrders.Add(recurringPaymentModel); } return(model); }
private async Task <decimal> GetConvertedRateAsync(decimal rate, Currency source, Currency target) { return((source.CurrencyCode == target.CurrencyCode) ? rate : await _currencyService.ConvertCurrency(rate, source, target)); }
public virtual SubmitReturnRequestModel PrepareReturnRequest(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; model.OrderNumber = _orderService.GetOrderById(order.Id).OrderNumber; //return reasons model.AvailableReturnReasons = _cacheManager.Get(string.Format(ModelCacheEventConsumer.RETURNREQUESTREASONS_MODEL_KEY, _workContext.WorkingLanguage.Id), () => { var reasons = new List <SubmitReturnRequestModel.ReturnRequestReasonModel>(); foreach (var rrr in _returnRequestService.GetAllReturnRequestReasons()) { reasons.Add(new SubmitReturnRequestModel.ReturnRequestReasonModel() { Id = rrr.Id, Name = rrr.GetLocalized(x => x.Name) }); } return(reasons); }); //return actions model.AvailableReturnActions = _cacheManager.Get(string.Format(ModelCacheEventConsumer.RETURNREQUESTACTIONS_MODEL_KEY, _workContext.WorkingLanguage.Id), () => { var actions = new List <SubmitReturnRequestModel.ReturnRequestActionModel>(); foreach (var rra in _returnRequestService.GetAllReturnRequestActions()) { actions.Add(new SubmitReturnRequestModel.ReturnRequestActionModel() { Id = rra.Id, Name = rra.GetLocalized(x => x.Name) }); } return(actions); }); var shipments = Grand.Core.Infrastructure.EngineContext.Current.Resolve <Grand.Services.Shipping.IShipmentService>().GetShipmentsByOrder(order.Id); //products var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { var qtyDelivery = shipments.Where(x => x.DeliveryDateUtc.HasValue).SelectMany(x => x.ShipmentItems).Where(x => x.OrderItemId == orderItem.Id).Sum(x => x.Quantity); var qtyReturn = _returnRequestService.SearchReturnRequests(customerId: order.CustomerId, orderItemId: orderItem.Id).Sum(x => x.Quantity); var product = _productService.GetProductByIdIncludeArch(orderItem.ProductId); if (!product.NotReturnable) { var orderItemModel = new SubmitReturnRequestModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.ProductId, ProductName = product.GetLocalized(x => x.Name), ProductSeName = product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, Quantity = qtyDelivery - qtyReturn, }; model.Items.Add(orderItemModel); //unit price 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); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } } } return(model); }
/// <summary> /// Prepare the customer order list model /// </summary> /// <returns>Customer order list model</returns> public virtual CustomerOrderListModel PrepareCustomerOrderListModel(string status, int?page, int?pageSize) { if (page == 0) { page = null; } List <int> statusList = new List <int>(); if (!string.IsNullOrEmpty(status)) { if (status == ((int)OrderStatus.Cancelled).ToString()) { statusList.Add((int)OrderStatus.Cancelled); } if (status == ((int)OrderStatus.Pending).ToString()) { statusList.Add((int)OrderStatus.Pending); statusList.Add((int)OrderStatus.Processing); } } var model = new CustomerOrderListModel(); var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id, osIds: statusList); //pageIndex: --page ?? 0, pageSize: 5, List <CustomerOrderListModel.OrderDetailsModel> allOrders = new List <CustomerOrderListModel.OrderDetailsModel>(); foreach (var order in orders) { var orderModel = new CustomerOrderListModel.OrderDetailsModel { Id = order.Id, CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc), OrderStatusEnum = order.OrderStatus, OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext), PaymentStatus = order.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext), ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext), IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order), CustomOrderNumber = order.CustomOrderNumber }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); allOrders.Add(orderModel); } List <CustomerOrderListModel.OrderDetailsModel> legacyOrders = null; var miscPlugins = _pluginFinder.GetPlugins <MyOrderServicePlugin>(storeId: EngineContext.Current.Resolve <IStoreContext>().CurrentStore.Id).ToList(); if (miscPlugins.Count > 0 && _gbsOrderSettings.LegacyOrdersInOrderHistory) { legacyOrders = new Orders.OrderExtensions().getLegacyOrders(); if (!string.IsNullOrEmpty(status)) { legacyOrders = legacyOrders.Where(x => statusList.Contains((int)x.OrderStatusEnum)).ToList(); } if (legacyOrders != null && legacyOrders.Count() > 0) { allOrders.AddRange(legacyOrders); } allOrders.Sort((x, y) => y.CreatedOn.CompareTo(x.CreatedOn)); } var ordersPaging = new PagedList <CustomerOrderListModel.OrderDetailsModel>(allOrders, pageIndex: --page ?? 0, pageSize: pageSize ?? 5); model.Orders = ordersPaging.ToList(); // do paging on orders var recurringPayments = _orderService.SearchRecurringPayments(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id); foreach (var recurringPayment in recurringPayments) { var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel { Id = recurringPayment.Id, StartDate = _dateTimeHelper.ConvertToUserTime(recurringPayment.StartDateUtc, DateTimeKind.Utc).ToString(), CycleInfo = string.Format("{0} {1}", recurringPayment.CycleLength, recurringPayment.CyclePeriod.GetLocalizedEnum(_localizationService, _workContext)), NextPayment = recurringPayment.NextPaymentDate.HasValue ? _dateTimeHelper.ConvertToUserTime(recurringPayment.NextPaymentDate.Value, DateTimeKind.Utc).ToString() : "", TotalCycles = recurringPayment.TotalCycles, CyclesRemaining = recurringPayment.CyclesRemaining, InitialOrderId = recurringPayment.InitialOrder.Id, InitialOrderNumber = recurringPayment.InitialOrder.CustomOrderNumber, CanCancel = _orderProcessingService.CanCancelRecurringPayment(_workContext.CurrentCustomer, recurringPayment), CanRetryLastPayment = _orderProcessingService.CanRetryLastRecurringPayment(_workContext.CurrentCustomer, recurringPayment) }; model.RecurringOrders.Add(recurringPaymentModel); } model.CustomProperties["PagerModel"] = new PagerModel { PageSize = ordersPaging.PageSize, TotalRecords = ordersPaging.TotalCount, PageIndex = ordersPaging.PageIndex, ShowTotalSummary = true, RouteActionName = "CustomerOrders", UseRouteLinks = true, RouteValues = new OrderRouteValues { page = page ?? 0, status = status, pageSize = pageSize } }; if (model.Orders.Any()) { model.Orders.FirstOrDefault().CustomProperties["PagerModel"] = new PagerModel { PageSize = ordersPaging.PageSize, TotalRecords = ordersPaging.TotalCount, PageIndex = ordersPaging.PageIndex, ShowTotalSummary = true, RouteActionName = "CustomerOrders", UseRouteLinks = true, RouteValues = new OrderRouteValues { page = page ?? 0, status = status, pageSize = pageSize } }; } return(model); }
protected virtual SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; //return reasons model.AvailableReturnReasons = _cacheManager.Get(string.Format(ModelCacheEventConsumer.RETURNREQUESTREASONS_MODEL_KEY, _workContext.WorkingLanguage.Id), () => { var reasons = new List <SubmitReturnRequestModel.ReturnRequestReasonModel>(); foreach (var rrr in _returnRequestService.GetAllReturnRequestReasons()) { reasons.Add(new SubmitReturnRequestModel.ReturnRequestReasonModel() { Id = rrr.Id, Name = rrr.GetLocalized(x => x.Name) }); } return(reasons); }); //return actions model.AvailableReturnActions = _cacheManager.Get(string.Format(ModelCacheEventConsumer.RETURNREQUESTACTIONS_MODEL_KEY, _workContext.WorkingLanguage.Id), () => { var actions = new List <SubmitReturnRequestModel.ReturnRequestActionModel>(); foreach (var rra in _returnRequestService.GetAllReturnRequestActions()) { actions.Add(new SubmitReturnRequestModel.ReturnRequestActionModel() { Id = rra.Id, Name = rra.GetLocalized(x => x.Name) }); } return(actions); }); //returnable products var orderItems = order.OrderItems.Where(oi => !oi.Product.NotReturnable); foreach (var orderItem in orderItems) { var orderItemModel = new SubmitReturnRequestModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, Quantity = orderItem.Quantity }; model.Items.Add(orderItemModel); //unit price 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); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } } return(model); }
/// <summary> /// Prepare the customer order list model /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the customer order list model /// </returns> public virtual async Task <CustomerOrderListModel> PrepareCustomerOrderListModelAsync() { var model = new CustomerOrderListModel(); var orders = await _orderService.SearchOrdersAsync(storeId : (await _storeContext.GetCurrentStoreAsync()).Id, customerId : (await _workContext.GetCurrentCustomerAsync()).Id); foreach (var order in orders) { var orderModel = new CustomerOrderListModel.OrderDetailsModel { Id = order.Id, CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc), OrderStatusEnum = order.OrderStatus, OrderStatus = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus), PaymentStatus = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus), ShippingStatus = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus), IsReturnRequestAllowed = await _orderProcessingService.IsReturnRequestAllowedAsync(order), CustomOrderNumber = order.CustomOrderNumber }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = await _priceFormatter.FormatPriceAsync(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, (await _workContext.GetWorkingLanguageAsync()).Id); model.Orders.Add(orderModel); } var recurringPayments = await _orderService.SearchRecurringPaymentsAsync((await _storeContext.GetCurrentStoreAsync()).Id, (await _workContext.GetCurrentCustomerAsync()).Id); foreach (var recurringPayment in recurringPayments) { var order = await _orderService.GetOrderByIdAsync(recurringPayment.InitialOrderId); var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel { Id = recurringPayment.Id, StartDate = (await _dateTimeHelper.ConvertToUserTimeAsync(recurringPayment.StartDateUtc, DateTimeKind.Utc)).ToString(), CycleInfo = $"{recurringPayment.CycleLength} {await _localizationService.GetLocalizedEnumAsync(recurringPayment.CyclePeriod)}", NextPayment = await _orderProcessingService.GetNextPaymentDateAsync(recurringPayment) is DateTime nextPaymentDate ? (await _dateTimeHelper.ConvertToUserTimeAsync(nextPaymentDate, DateTimeKind.Utc)).ToString() : "", TotalCycles = recurringPayment.TotalCycles, CyclesRemaining = await _orderProcessingService.GetCyclesRemainingAsync(recurringPayment), InitialOrderId = order.Id, InitialOrderNumber = order.CustomOrderNumber, CanCancel = await _orderProcessingService.CanCancelRecurringPaymentAsync(await _workContext.GetCurrentCustomerAsync(), recurringPayment), CanRetryLastPayment = await _orderProcessingService.CanRetryLastRecurringPaymentAsync(await _workContext.GetCurrentCustomerAsync(), recurringPayment) }; model.RecurringOrders.Add(recurringPaymentModel); } return(model); }
public virtual async Task <ReturnRequestModel> PrepareReturnRequestModel(ReturnRequestModel model, ReturnRequest returnRequest, bool excludeProperties) { if (model == null) { throw new ArgumentNullException("model"); } if (returnRequest == null) { throw new ArgumentNullException("returnRequest"); } var order = await _orderService.GetOrderById(returnRequest.OrderId); decimal unitPriceInclTaxInCustomerCurrency = 0; foreach (var item in returnRequest.ReturnRequestItems) { var orderItem = order.OrderItems.Where(x => x.Id == item.OrderItemId).First(); unitPriceInclTaxInCustomerCurrency += _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate) * item.Quantity; } model.Total = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency); model.Quantity = returnRequest.ReturnRequestItems.Sum(x => x.Quantity); model.Id = returnRequest.Id; model.OrderId = order.Id; model.OrderNumber = order.OrderNumber; model.OrderCode = order.Code; model.ReturnNumber = returnRequest.ReturnNumber; model.CustomerId = returnRequest.CustomerId; model.NotifyCustomer = returnRequest.NotifyCustomer; var customer = await _customerService.GetCustomerById(returnRequest.CustomerId); if (customer != null) { model.CustomerInfo = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"); } else { model.CustomerInfo = _localizationService.GetResource("Admin.Customers.Guest"); } model.ReturnRequestStatusStr = returnRequest.ReturnRequestStatus.ToString(); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc); model.PickupDate = returnRequest.PickupDate; model.GenericAttributes = returnRequest.GenericAttributes; if (!excludeProperties) { var addr = new AddressModel(); model.PickupAddress = await PrepareAddressModel(addr, returnRequest.PickupAddress, excludeProperties); model.CustomerComments = returnRequest.CustomerComments; model.ExternalId = returnRequest.ExternalId; model.StaffNotes = returnRequest.StaffNotes; model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId; } return(model); }
public async Task <LiquidReturnRequest> Handle(GetReturnRequestTokensCommand request, CancellationToken cancellationToken) { var liquidReturnRequest = new LiquidReturnRequest(request.ReturnRequest, request.Store, request.Order, request.ReturnRequestNote); liquidReturnRequest.Status = request.ReturnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, request.Language.Id); liquidReturnRequest.Products = await ProductListToHtmlTable(); liquidReturnRequest.PickupAddressStateProvince = !string.IsNullOrEmpty(request.ReturnRequest.PickupAddress.StateProvinceId) ? (await _stateProvinceService.GetStateProvinceById(request.ReturnRequest.PickupAddress.StateProvinceId))?.GetLocalized(x => x.Name, request.Language.Id) : ""; liquidReturnRequest.PickupAddressCountry = !string.IsNullOrEmpty(request.ReturnRequest.PickupAddress.CountryId) ? (await _countryService.GetCountryById(request.ReturnRequest.PickupAddress.CountryId))?.GetLocalized(x => x.Name, request.Language.Id) : ""; async Task <string> ProductListToHtmlTable() { var sb = new StringBuilder(); sb.AppendLine("<table border=\"0\" style=\"width:100%;\">"); sb.AppendLine(string.Format("<tr style=\"text-align:center;\">")); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Name"))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Price"))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Quantity"))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).ReturnReason"))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).ReturnAction"))); sb.AppendLine("</tr>"); var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode); foreach (var rrItem in request.ReturnRequest.ReturnRequestItems) { var orderItem = request.Order.OrderItems.Where(x => x.Id == rrItem.OrderItemId).First(); sb.AppendLine(string.Format("<tr style=\"background-color: {0};text-align: center;\">", _templatesSettings.Color2)); string productName = (await _productService.GetProductById(orderItem.ProductId))?.GetLocalized(x => x.Name, request.Order.CustomerLanguageId); sb.AppendLine("<td style=\"padding: 0.6em 0.4em;text-align: left;\">" + WebUtility.HtmlEncode(productName)); sb.AppendLine("</td>"); string unitPriceStr; if (request.Order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, request.Order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, currency, request.Language, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, request.Order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, currency, request.Language, false); } sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: right;\">{0}</td>", unitPriceStr)); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", orderItem.Quantity)); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", rrItem.ReasonForReturn)); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", rrItem.RequestedAction)); } sb.AppendLine("</table>"); return(sb.ToString()); } return(liquidReturnRequest); }
/// <summary> /// Prepare the customer order list model /// </summary> /// <returns>Customer order list model</returns> public virtual CustomerOrderListModel PrepareCustomerOrderListModel(bool viewAll = true) { var model = new CustomerOrderListModel(); var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id, pageSize: viewAll ? int.MaxValue : 15); foreach (var order in orders) { var orderModel = new CustomerOrderListModel.OrderDetailsModel { Id = order.Id, CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc), OrderStatusEnum = order.OrderStatus, OrderStatus = _localizationService.GetLocalizedEnum(order.OrderStatus), PaymentStatus = _localizationService.GetLocalizedEnum(order.PaymentStatus), ShippingStatus = _localizationService.GetLocalizedEnum(order.ShippingStatus), IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order), CustomOrderNumber = order.CustomOrderNumber, OrderItems = order.OrderItems }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); model.Orders.Add(orderModel); } // PrepareProductDetailsModel var recurringPayments = _orderService.SearchRecurringPayments(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id); foreach (var recurringPayment in recurringPayments) { var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel { Id = recurringPayment.Id, StartDate = _dateTimeHelper.ConvertToUserTime(recurringPayment.StartDateUtc, DateTimeKind.Utc).ToString(), CycleInfo = $"{recurringPayment.CycleLength} {_localizationService.GetLocalizedEnum(recurringPayment.CyclePeriod)}", NextPayment = recurringPayment.NextPaymentDate.HasValue ? _dateTimeHelper.ConvertToUserTime(recurringPayment.NextPaymentDate.Value, DateTimeKind.Utc).ToString() : "", TotalCycles = recurringPayment.TotalCycles, CyclesRemaining = recurringPayment.CyclesRemaining, InitialOrderId = recurringPayment.InitialOrder.Id, InitialOrderNumber = recurringPayment.InitialOrder.CustomOrderNumber, CanCancel = _orderProcessingService.CanCancelRecurringPayment(_workContext.CurrentCustomer, recurringPayment), CanRetryLastPayment = _orderProcessingService.CanRetryLastRecurringPayment(_workContext.CurrentCustomer, recurringPayment) }; model.RecurringOrders.Add(recurringPaymentModel); } return(model); }
/// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var processPaymentResult = new ProcessPaymentResult(); //get customer var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); //get settings var useSandbox = _braintreePaymentSettings.UseSandbox; var merchantId = _braintreePaymentSettings.MerchantId; var publicKey = _braintreePaymentSettings.PublicKey; var privateKey = _braintreePaymentSettings.PrivateKey; //new gateway var gateway = new BraintreeGateway { Environment = useSandbox ? Environment.SANDBOX : Environment.PRODUCTION, MerchantId = merchantId, PublicKey = publicKey, PrivateKey = privateKey }; var billingAddress = _addressService.GetAddressById(customer.BillingAddressId ?? 0); //search to see if customer is already in the vault var searchRequest = new CustomerSearchRequest().Email.Is(billingAddress?.Email); var vaultCustomer = gateway.Customer.Search(searchRequest); var customerId = vaultCustomer.FirstOrDefault()?.Id ?? string.Empty; var currencyMerchantId = string.Empty; var amount = processPaymentRequest.OrderTotal; if (_braintreePaymentSettings.UseMultiCurrency) { //get currency var currency = _workContext.WorkingCurrency; currencyMerchantId = _braintreeMerchantService.GetMerchantId(currency.CurrencyCode); if (!string.IsNullOrEmpty(currencyMerchantId)) { amount = _currencyService.ConvertCurrency(amount, currency.Rate); } } //new transaction request var transactionRequest = new TransactionRequest { Amount = amount, CustomerId = customerId, Channel = BraintreePaymentDefaults.PartnerCode, MerchantAccountId = currencyMerchantId }; if (_braintreePaymentSettings.Use3DS) { transactionRequest.PaymentMethodNonce = processPaymentRequest.CustomValues["CardNonce"].ToString(); } else { //transaction credit card request var transactionCreditCardRequest = new TransactionCreditCardRequest { Number = processPaymentRequest.CreditCardNumber, CVV = processPaymentRequest.CreditCardCvv2, ExpirationDate = processPaymentRequest.CreditCardExpireMonth + "/" + processPaymentRequest.CreditCardExpireYear, }; transactionRequest.CreditCard = transactionCreditCardRequest; } //customer request var customerRequest = new CustomerRequest { CustomerId = customerId, FirstName = billingAddress?.FirstName, LastName = billingAddress?.LastName, Email = billingAddress?.Email, Fax = billingAddress?.FaxNumber, Company = billingAddress?.Company, Phone = billingAddress?.PhoneNumber }; transactionRequest.Customer = customerRequest; var country = _countryService.GetCountryByAddress(billingAddress); //address request var addressRequest = new AddressRequest { FirstName = billingAddress?.FirstName, LastName = billingAddress?.LastName, StreetAddress = billingAddress?.Address1, PostalCode = billingAddress?.ZipPostalCode, CountryCodeAlpha2 = country?.TwoLetterIsoCode, CountryCodeAlpha3 = country?.ThreeLetterIsoCode }; transactionRequest.BillingAddress = addressRequest; //transaction options request var transactionOptionsRequest = new TransactionOptionsRequest { SubmitForSettlement = true, ThreeDSecure = new TransactionOptionsThreeDSecureRequest() }; transactionRequest.Options = transactionOptionsRequest; //sending a request var result = gateway.Transaction.Sale(transactionRequest); //result if (result.IsSuccess()) { processPaymentResult.NewPaymentStatus = PaymentStatus.Paid; } else { processPaymentResult.AddError("Error processing payment." + result.Message); } return(processPaymentResult); }
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); string Authority; System.Net.ServicePointManager.Expect100Continue = false; var zp = new ZarinPalWebService.PaymentGatewayImplementationService(); var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext); var payPalStandardPaymentSettings = _settingService.LoadSetting <ZarinPalPaymentSettings>(storeScope); var email = processPaymentRequest.CustomValues["EMail"]; var merchantCode = payPalStandardPaymentSettings.MerchantCode; var description = payPalStandardPaymentSettings.Description; var phonenumber = processPaymentRequest.CustomValues["Phonenumber"]; var userSsl = payPalStandardPaymentSettings.UseSsl; var currencyId = payPalStandardPaymentSettings.CurrencyId; //processPaymentRequest.CustomValues.Clear(); //check configurations fileds if (string.IsNullOrWhiteSpace(merchantCode) || string.IsNullOrWhiteSpace(description) || currencyId == 0) { result.AddError( _localizationService.GetResource("Plugins.Payments.ZarinPal.ErrorOccurred")); result.NewPaymentStatus = PaymentStatus.Voided; return(result); } //get base url var baseUrl = _webHelper.GetStoreHost(userSsl); //get currency for convert to target currency var sourceCurrency = _currencyService.GetCurrencyById(_workContext.WorkingCurrency.Id); var targetCurrency = _currencyService.GetCurrencyById(currencyId); //get converted price var finalPrice = _currencyService.ConvertCurrency(processPaymentRequest.OrderTotal, sourceCurrency, targetCurrency); if (email == null) { email = ""; } if (phonenumber == null) { phonenumber = ""; } //send information to bank and get status var status = zp.PaymentRequest(merchantCode, (int)finalPrice, description, email.ToString(), phonenumber.ToString(), baseUrl + "Plugins/PaymentZarinPal/Result", out Authority); //retuened status from bank if (status == 100) { result.NewPaymentStatus = PaymentStatus.Pending; } else { result.NewPaymentStatus = PaymentStatus.Voided; result.AddError(_localizationService.GetResource("Plugins.Payments.ZarinPal.ErrorOccurred")); } result.AuthorizationTransactionCode = Authority; return(result); }
public async Task <IActionResult> GetTodaysOrders() { var customer = await _workContext.GetCurrentCustomerAsync(); var orders = await _orderService.SearchOrdersAsync(customerId : customer.Id); var perviousOrders = orders.Where(x => x.ScheduleDate.Date == DateTime.Now.Date).ToList(); if (perviousOrders.Any()) { var languageId = _workContext.GetWorkingLanguageAsync().Id; var model = new CustomerOrderListModel(); foreach (var order in perviousOrders) { var orderModel = new CustomerOrderListModel.OrderDetailsModel { Id = order.Id, ScheduleDate = await _dateTimeHelper.ConvertToUserTimeAsync(order.ScheduleDate, DateTimeKind.Utc), CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc), OrderStatusEnum = order.OrderStatus, OrderStatus = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus), PaymentStatus = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus), ShippingStatus = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus), IsReturnRequestAllowed = await _orderProcessingService.IsReturnRequestAllowedAsync(order), CustomOrderNumber = order.CustomOrderNumber, Rating = order.Rating, RatingText = order.RatingText }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = await _priceFormatter.FormatPriceAsync(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.GetWorkingLanguageAsync().Id); var orderItems = await _orderService.GetOrderItemsAsync(order.Id); foreach (var orderItem in orderItems) { var product = await _productService.GetProductByIdAsync(orderItem.ProductId); var productPicture = await _pictureService.GetPicturesByProductIdAsync(orderItem.ProductId); var vendor = await _vendorService.GetVendorByProductIdAsync(product.Id); var orderItemModel = new OrderDetailsModel.OrderItemModel { Id = orderItem.Id, OrderItemGuid = orderItem.OrderItemGuid, Sku = await _productService.FormatSkuAsync(product, orderItem.AttributesXml), VendorName = vendor != null ? vendor.Name : string.Empty, ProductId = product.Id, ProductPictureUrl = productPicture.Any() ? await _pictureService.GetPictureUrlAsync(productPicture.FirstOrDefault().Id) : await _pictureService.GetDefaultPictureUrlAsync(), ProductName = await _localizationService.GetLocalizedAsync(product, x => x.Name), ProductSeName = await _urlRecordService.GetSeNameAsync(product), Quantity = orderItem.Quantity, AttributeInfo = orderItem.AttributeDescription, VendorLogoPictureUrl = await _pictureService.GetPictureUrlAsync(vendor != null?vendor.PictureId : 0, showDefaultPicture : true) }; //rental info if (product.IsRental) { var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? _productService.FormatRentalDate(product, orderItem.RentalStartDateUtc.Value) : ""; var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? _productService.FormatRentalDate(product, orderItem.RentalEndDateUtc.Value) : ""; orderItemModel.RentalInfo = string.Format(await _localizationService.GetResourceAsync("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate); } orderModel.Items.Add(orderItemModel); //unit price, subtotal if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); orderItemModel.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true); var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate); orderItemModel.SubTotal = await _priceFormatter.FormatPriceAsync(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false); var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate); orderItemModel.SubTotal = await _priceFormatter.FormatPriceAsync(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false); } //downloadable products if (await _orderService.IsDownloadAllowedAsync(orderItem)) { orderItemModel.DownloadId = product.DownloadId; } if (await _orderService.IsLicenseDownloadAllowedAsync(orderItem)) { orderItemModel.LicenseId = orderItem.LicenseDownloadId ?? 0; } } model.Orders.Add(orderModel); } return(Ok(new { success = true, model })); } return(Ok(new { success = false, message = "No previous order found" })); }
/// <summary> /// Prepare the customer subscription list model /// </summary> /// <returns>Customer subscription list model</returns> public virtual CustomerSubscriptionListModel PrepareCustomerSubscriptionListModel() { var model = new CustomerSubscriptionListModel(); var subscriptions = _subscriptionService.SearchSubscriptions(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id); foreach (var subscription in subscriptions) { var subscriptionModel = new CustomerSubscriptionListModel.SubscriptionDetailsModel { Id = subscription.Id, CreatedOn = _dateTimeHelper.ConvertToUserTime(subscription.CreatedOnUtc, DateTimeKind.Utc), SubscriptionStatusEnum = subscription.SubscriptionStatus, SubscriptionStatus = subscription.SubscriptionStatus.GetLocalizedEnum(_localizationService, _workContext), PaymentStatus = subscription.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext), IsReturnRequestAllowed = _subscriptionProcessingService.IsReturnRequestAllowed(subscription), CustomSubscriptionNumber = subscription.CustomSubscriptionNumber }; var subscriptionTotalInCustomerCurrency = _currencyService.ConvertCurrency(subscription.SubscriptionTotal, subscription.CurrencyRate); subscriptionModel.SubscriptionTotal = _priceFormatter.FormatPrice(subscriptionTotalInCustomerCurrency, true, subscription.CustomerCurrencyCode, false, _workContext.WorkingLanguage); model.Subscriptions.Add(subscriptionModel); } var recurringPayments = _subscriptionService.SearchRecurringPayments(_storeContext.CurrentStore.Id, _workContext.CurrentCustomer.Id); foreach (var recurringPayment in recurringPayments) { var recurringPaymentModel = new CustomerSubscriptionListModel.RecurringSubscriptionModel { Id = recurringPayment.Id, StartDate = _dateTimeHelper.ConvertToUserTime(recurringPayment.StartDateUtc, DateTimeKind.Utc).ToString(), CycleInfo = string.Format("{0} {1}", recurringPayment.CycleLength, recurringPayment.CyclePeriod.GetLocalizedEnum(_localizationService, _workContext)), NextPayment = recurringPayment.NextPaymentDate.HasValue ? _dateTimeHelper.ConvertToUserTime(recurringPayment.NextPaymentDate.Value, DateTimeKind.Utc).ToString() : "", TotalCycles = recurringPayment.TotalCycles, CyclesRemaining = recurringPayment.CyclesRemaining, InitialSubscriptionId = recurringPayment.InitialSubscription.Id, InitialSubscriptionNumber = recurringPayment.InitialSubscription.CustomSubscriptionNumber, CanCancel = _subscriptionProcessingService.CanCancelRecurringPayment(_workContext.CurrentCustomer, recurringPayment), CanRetryLastPayment = _subscriptionProcessingService.CanRetryLastRecurringPayment(_workContext.CurrentCustomer, recurringPayment) }; model.RecurringSubscriptions.Add(recurringPaymentModel); } return(model); }
public virtual async Task <SubmitReturnRequestModel> PrepareReturnRequest(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; model.OrderNumber = (await _orderService.GetOrderById(order.Id)).OrderNumber; //return reasons model.AvailableReturnReasons = await _cacheManager.GetAsync(string.Format(ModelCacheEventConsumer.RETURNREQUESTREASONS_MODEL_KEY, _workContext.WorkingLanguage.Id), async() => { var reasons = new List <SubmitReturnRequestModel.ReturnRequestReasonModel>(); foreach (var rrr in await _returnRequestService.GetAllReturnRequestReasons()) { reasons.Add(new SubmitReturnRequestModel.ReturnRequestReasonModel() { Id = rrr.Id, Name = rrr.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id) }); } return(reasons); }); //return actions model.AvailableReturnActions = await _cacheManager.GetAsync(string.Format(ModelCacheEventConsumer.RETURNREQUESTACTIONS_MODEL_KEY, _workContext.WorkingLanguage.Id), async() => { var actions = new List <SubmitReturnRequestModel.ReturnRequestActionModel>(); foreach (var rra in await _returnRequestService.GetAllReturnRequestActions()) { actions.Add(new SubmitReturnRequestModel.ReturnRequestActionModel() { Id = rra.Id, Name = rra.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id) }); } return(actions); }); var shipments = await _serviceProvider.GetRequiredService <Grand.Services.Shipping.IShipmentService>().GetShipmentsByOrder(order.Id); //products var orderItems = await _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { var qtyDelivery = shipments.Where(x => x.DeliveryDateUtc.HasValue).SelectMany(x => x.ShipmentItems).Where(x => x.OrderItemId == orderItem.Id).Sum(x => x.Quantity); var returnRequests = await _returnRequestService.SearchReturnRequests(customerId : order.CustomerId, orderItemId : orderItem.Id); int qtyReturn = 0; foreach (var rr in returnRequests) { foreach (var rrItem in rr.ReturnRequestItems) { qtyReturn += rrItem.Quantity; } } var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId); if (!product.NotReturnable) { var orderItemModel = new SubmitReturnRequestModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.ProductId, ProductName = product.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id), ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id), AttributeInfo = orderItem.AttributeDescription, Quantity = qtyDelivery - qtyReturn, }; if (orderItemModel.Quantity > 0) { model.Items.Add(orderItemModel); } //unit price if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); orderItemModel.UnitPrice = await _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = await _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } } } if (_orderSettings.ReturnRequests_AllowToSpecifyPickupAddress) { //existing addresses var addresses = new List <Address>(); foreach (var item in _workContext.CurrentCustomer.Addresses) { if (string.IsNullOrEmpty(item.CountryId)) { addresses.Add(item); continue; } var country = await _countryService.GetCountryById(item.CountryId); if (country == null || (country.AllowsShipping && _storeMappingService.Authorize(country))) { addresses.Add(item); continue; } } foreach (var address in addresses) { var addressModel = new AddressModel(); await _addressViewModelService.PrepareModel(model : addressModel, address : address, excludeProperties : false); model.ExistingAddresses.Add(addressModel); } //new address var countries = await _countryService.GetAllCountriesForShipping(); await _addressViewModelService.PrepareModel(model : model.NewAddress, address : null, excludeProperties : false, loadCountries : () => countries, prePopulateWithCustomerFields : true, customer : _workContext.CurrentCustomer); } model.ShowPickupAddress = _orderSettings.ReturnRequests_AllowToSpecifyPickupAddress; model.ShowPickupDate = _orderSettings.ReturnRequests_AllowToSpecifyPickupDate; model.PickupDateRequired = _orderSettings.ReturnRequests_PickupDateRequired; return(model); }
protected SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; string returnRequestReasons = _orderSettings.GetLocalized(x => x.ReturnRequestReasons, order.CustomerLanguageId, true, false); string returnRequestActions = _orderSettings.GetLocalized(x => x.ReturnRequestActions, order.CustomerLanguageId, true, false); //return reasons foreach (var rrr in returnRequestReasons.SplitSafe(",")) { model.AvailableReturnReasons.Add(new SelectListItem() { Text = rrr, Value = rrr }); } //return actions foreach (var rra in returnRequestActions.SplitSafe(",")) { model.AvailableReturnActions.Add(new SelectListItem() { Text = rra, Value = rra }); } //products var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { var attributeQueryData = new List <List <int> >(); var orderItemModel = new SubmitReturnRequestModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, Quantity = orderItem.Quantity }; if (orderItem.Product.ProductType != ProductType.BundledProduct) { _productAttributeParser.DeserializeQueryData(attributeQueryData, orderItem.AttributesXml, orderItem.ProductId); } else if (orderItem.Product.BundlePerItemPricing && orderItem.BundleData.HasValue()) { var bundleData = orderItem.GetBundleData(); bundleData.ForEach(x => _productAttributeParser.DeserializeQueryData(attributeQueryData, x.AttributesXml, x.ProductId, x.BundleItemId)); } orderItemModel.ProductUrl = _productAttributeParser.GetProductUrlWithAttributes(attributeQueryData, orderItemModel.ProductSeName); //unit price switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } break; case TaxDisplayType.IncludingTax: { var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } break; } model.Items.Add(orderItemModel); } return(model); }
public async Task AddOrderTokens(LiquidObject liquidObject, Order order, Customer customer, Store store, OrderNote orderNote = null, Vendor vendor = null, decimal refundedAmount = 0) { var language = await _languageService.GetLanguageById(order.CustomerLanguageId); var currency = await _currencyService.GetCurrencyByCode(order.CustomerCurrencyCode); var productService = _serviceProvider.GetRequiredService <IProductService>(); var downloadService = _serviceProvider.GetRequiredService <IDownloadService>(); var vendorService = _serviceProvider.GetRequiredService <IVendorService>(); var liquidOrder = new LiquidOrder(order, customer, language, currency, store, orderNote, vendor); foreach (var item in order.OrderItems.Where(x => x.VendorId == vendor?.Id || vendor == null)) { var product = await productService.GetProductById(item.ProductId); var vendorItem = await vendorService.GetVendorById(item.VendorId); var liqitem = new LiquidOrderItem(item, product, order, language, currency, store, vendorItem); #region Download liqitem.IsDownloadAllowed = downloadService.IsDownloadAllowed(order, item, product); liqitem.IsLicenseDownloadAllowed = downloadService.IsLicenseDownloadAllowed(order, item, product); #endregion #region Unit price string unitPriceStr; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(item.UnitPriceInclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, currency, language, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(item.UnitPriceExclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, currency, language, false); } liqitem.UnitPrice = unitPriceStr; #endregion #region total price string priceStr; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(item.PriceInclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, currency, language, true); } else { //excluding tax var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(item.PriceExclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, currency, language, false); } liqitem.TotalPrice = priceStr; #endregion string sku = ""; if (product != null) { sku = product.FormatSku(item.AttributesXml, _productAttributeParser); } liqitem.ProductSku = WebUtility.HtmlEncode(sku); liqitem.ShowSkuOnProductDetailsPage = _catalogSettings.ShowSkuOnProductDetailsPage; liqitem.ProductOldPrice = _priceFormatter.FormatPrice(product.OldPrice, true, currency, language, true); liquidOrder.OrderItems.Add(liqitem); } liquidOrder.BillingCustomAttributes = await _addressAttributeFormatter.FormatAttributes(order.BillingAddress?.CustomAttributes); liquidOrder.BillingCountry = order.BillingAddress != null && !string.IsNullOrEmpty(order.BillingAddress.CountryId) ? (await _countryService.GetCountryById(order.BillingAddress.CountryId))?.GetLocalized(x => x.Name, order.CustomerLanguageId) : ""; liquidOrder.BillingStateProvince = !string.IsNullOrEmpty(order.BillingAddress.StateProvinceId) ? (await _stateProvinceService.GetStateProvinceById(order.BillingAddress.StateProvinceId))?.GetLocalized(x => x.Name, order.CustomerLanguageId) : ""; liquidOrder.ShippingCountry = order.ShippingAddress != null && !string.IsNullOrEmpty(order.ShippingAddress.CountryId) ? (await _countryService.GetCountryById(order.ShippingAddress.CountryId))?.GetLocalized(x => x.Name, order.CustomerLanguageId) : ""; liquidOrder.ShippingStateProvince = order.ShippingAddress != null && !string.IsNullOrEmpty(order.ShippingAddress.StateProvinceId) ? (await _stateProvinceService.GetStateProvinceById(order.ShippingAddress.StateProvinceId)).GetLocalized(x => x.Name, order.CustomerLanguageId) : ""; liquidOrder.ShippingCustomAttributes = await _addressAttributeFormatter.FormatAttributes(order.ShippingAddress != null?order.ShippingAddress.CustomAttributes : ""); var paymentMethod = _serviceProvider.GetRequiredService <IPaymentService>().LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); liquidOrder.PaymentMethod = paymentMethod != null?paymentMethod.GetLocalizedFriendlyName(_localizationService, language.Id) : order.PaymentMethodSystemName; liquidOrder.AmountRefunded = _priceFormatter.FormatPrice(refundedAmount, true, currency, language, false); Dictionary <string, string> dict = new Dictionary <string, string>(); foreach (var item in order.TaxRatesDictionary) { string taxRate = string.Format(_localizationService.GetResource("Messages.Order.TaxRateLine"), _priceFormatter.FormatTaxRate(item.Key)); string taxValue = _priceFormatter.FormatPrice(item.Value, true, currency, language, false); dict.Add(taxRate, taxValue); } liquidOrder.TaxRates = dict; Dictionary <string, string> cards = new Dictionary <string, string>(); var servicegiftCard = _serviceProvider.GetRequiredService <IGiftCardService>(); var gcuhC = await servicegiftCard.GetAllGiftCardUsageHistory(order.Id); foreach (var gcuh in gcuhC) { var giftCard = await servicegiftCard.GetGiftCardById(gcuh.GiftCardId); string giftCardText = string.Format(_localizationService.GetResource("Messages.Order.GiftCardInfo", language.Id), WebUtility.HtmlEncode(giftCard.GiftCardCouponCode)); string giftCardAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, currency, language, false); cards.Add(giftCardText, giftCardAmount); } liquidOrder.GiftCards = cards; if (order.RedeemedRewardPointsEntry != null) { liquidOrder.RPTitle = string.Format(_localizationService.GetResource("Messages.Order.RewardPoints", language.Id), -order.RedeemedRewardPointsEntry?.Points); liquidOrder.RPAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, currency, language, false); } void CalculateSubTotals() { string _cusSubTotal; bool _displaySubTotalDiscount; string _cusSubTotalDiscount; string _cusShipTotal; string _cusPaymentMethodAdditionalFee; bool _displayTax; string _cusTaxTotal; bool _displayTaxRates; bool _displayDiscount; string _cusDiscount; string _cusTotal; _displaySubTotalDiscount = false; _cusSubTotalDiscount = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal) { //including tax //subtotal var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); _cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, currency, language, true); //discount (applied to order subtotal) var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero) { _cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, currency, language, true); _displaySubTotalDiscount = true; } } else { //exсluding tax //subtotal var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); _cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, currency, language, false); //discount (applied to order subtotal) var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero) { _cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, currency, language, false); _displaySubTotalDiscount = true; } } //shipping, payment method fee _cusTaxTotal = string.Empty; _cusDiscount = string.Empty; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax //shipping var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); _cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, currency, language, true); //payment method additional fee var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); _cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, currency, language, true); } else { //excluding tax //shipping var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); _cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, currency, language, false); //payment method additional fee var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); _cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, currency, language, false); } //shipping bool displayShipping = order.ShippingStatus != ShippingStatus.ShippingNotRequired; //payment method fee bool displayPaymentMethodFee = order.PaymentMethodAdditionalFeeExclTax > decimal.Zero; //tax _displayTax = true; _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 { var _taxRates = new SortedDictionary <decimal, decimal>(); foreach (var tr in order.TaxRatesDictionary) { _taxRates.Add(tr.Key, _currencyService.ConvertCurrency(tr.Value, order.CurrencyRate)); } _displayTaxRates = _taxSettings.DisplayTaxRates && _taxRates.Any(); _displayTax = !_displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); string taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, currency, language, order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax, false); _cusTaxTotal = taxStr; } } //discount _displayDiscount = false; if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); _cusDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, currency, language, order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax, false); _displayDiscount = true; } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); _cusTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, currency, language, order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax, false); liquidOrder.SubTotal = _cusSubTotal; liquidOrder.DisplaySubTotalDiscount = _displaySubTotalDiscount; liquidOrder.SubTotalDiscount = _cusSubTotalDiscount; liquidOrder.Shipping = _cusShipTotal; liquidOrder.Discount = _cusDiscount; liquidOrder.PaymentMethodAdditionalFee = _cusPaymentMethodAdditionalFee; liquidOrder.Tax = _cusTaxTotal; liquidOrder.Total = _cusTotal; liquidOrder.DisplayTax = _displayTax; liquidOrder.DisplayDiscount = _displayDiscount; liquidOrder.DisplayTaxRates = _displayTaxRates; } CalculateSubTotals(); liquidObject.Order = liquidOrder; await _mediator.EntityTokensAdded(order, liquidOrder, liquidObject); }
/// <summary> /// Print an order to PDF /// </summary> /// <param name="order">Order</param> /// <param name="lang">Language</param> /// <param name="filePath">File path</param> public virtual void PrintOrderToPdf(Order order, Language lang, string filePath) { if (order == null) { throw new ArgumentNullException("order"); } if (lang == null) { throw new ArgumentNullException("lang"); } if (String.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } var pageSize = PageSize.A4; if (_pdfSettings.LetterPageSizeEnabled) { pageSize = PageSize.LETTER; } var doc = new Document(pageSize); PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); //fonts var titleFont = GetFont(); titleFont.SetStyle(Font.BOLD); titleFont.Color = BaseColor.BLACK; var font = GetFont(); var attributesFont = GetFont(); attributesFont.SetStyle(Font.ITALIC); #region Header //logo var logoPicture = _pictureService.GetPictureById(_pdfSettings.LogoPictureId); var logoExists = logoPicture != null; //header var headerTable = new PdfPTable(logoExists ? 2 : 1); headerTable.WidthPercentage = 100f; if (logoExists) { headerTable.SetWidths(new[] { 50, 50 }); } //logo if (logoExists) { var logoFilePath = _pictureService.GetPictureLocalPath(logoPicture, 0, false); var cellLogo = new PdfPCell(Image.GetInstance(logoFilePath)); cellLogo.Border = Rectangle.NO_BORDER; headerTable.AddCell(cellLogo); } //store info var cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.Order#", lang.Id), order.Id), titleFont)); var anchor = new Anchor(_storeInformationSettings.StoreUrl.Trim(new char[] { '/' }), font); anchor.Reference = _storeInformationSettings.StoreUrl; cell.AddElement(new Paragraph(anchor)); cell.AddElement(new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.OrderDate", lang.Id), _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc).ToString("D")), font)); headerTable.AddCell(cell); doc.Add(headerTable); #endregion #region Addresses var addressTable = new PdfPTable(2); addressTable.WidthPercentage = 100f; addressTable.SetWidths(new[] { 50, 50 }); //billing info cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(_localizationService.GetResource("PDFInvoice.BillingInformation", lang.Id), titleFont)); if (!String.IsNullOrEmpty(order.BillingAddress.Company)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.BillingAddress.Company), font)); } cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.BillingAddress.FirstName + " " + order.BillingAddress.LastName), font)); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.BillingAddress.PhoneNumber), font)); if (!String.IsNullOrEmpty(order.BillingAddress.FaxNumber)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.BillingAddress.FaxNumber), font)); } cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.BillingAddress.Address1), font)); if (!String.IsNullOrEmpty(order.BillingAddress.Address2)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.BillingAddress.Address2), font)); } cell.AddElement(new Paragraph(" " + String.Format("{0}, {1} {2}", order.BillingAddress.City, order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name) : "", order.BillingAddress.ZipPostalCode), font)); cell.AddElement(new Paragraph(" " + String.Format("{0}", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name) : ""), font)); //VAT number if (!String.IsNullOrEmpty(order.VatNumber)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.VATNumber", lang.Id), order.VatNumber), font)); } addressTable.AddCell(cell); //shipping info if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { if (order.ShippingAddress == null) { throw new NopException(string.Format("Shipping is required, but address is not available. Order ID = {0}", order.Id)); } cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(_localizationService.GetResource("PDFInvoice.ShippingInformation", lang.Id), titleFont)); if (!String.IsNullOrEmpty(order.ShippingAddress.Company)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.ShippingAddress.Company), font)); } cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.ShippingAddress.FirstName + " " + order.ShippingAddress.LastName), font)); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.ShippingAddress.PhoneNumber), font)); if (!String.IsNullOrEmpty(order.ShippingAddress.FaxNumber)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.ShippingAddress.FaxNumber), font)); } cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.ShippingAddress.Address1), font)); if (!String.IsNullOrEmpty(order.ShippingAddress.Address2)) { cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.ShippingAddress.Address2), font)); } cell.AddElement(new Paragraph(" " + String.Format("{0}, {1} {2}", order.ShippingAddress.City, order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name) : "", order.ShippingAddress.ZipPostalCode), font)); cell.AddElement(new Paragraph(" " + String.Format("{0}", order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name) : ""), font)); cell.AddElement(new Paragraph(" ")); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.ShippingMethod", lang.Id), order.ShippingMethod), font)); cell.AddElement(new Paragraph()); addressTable.AddCell(cell); } else { cell = new PdfPCell(new Phrase(" ")); cell.Border = Rectangle.NO_BORDER; addressTable.AddCell(cell); } doc.Add(addressTable); doc.Add(new Paragraph(" ")); #endregion #region Products //products doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.Product(s)", lang.Id), titleFont)); doc.Add(new Paragraph(" ")); var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null); var productsTable = new PdfPTable(4); productsTable.WidthPercentage = 100f; productsTable.SetWidths(new[] { 40, 20, 20, 20 }); //product name cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductName", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //price cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductPrice", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //qty cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductQuantity", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //total cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductTotal", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); for (int i = 0; i < orderProductVariants.Count; i++) { var orderProductVariant = orderProductVariants[i]; var pv = orderProductVariant.ProductVariant; //product name string name = ""; if (!String.IsNullOrEmpty(pv.GetLocalized(x => x.Name))) { name = string.Format("{0} ({1})", pv.Product.GetLocalized(x => x.Name), pv.GetLocalized(x => x.Name)); } else { name = pv.Product.GetLocalized(x => x.Name); } cell = new PdfPCell(); cell.AddElement(new Paragraph(name, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; var attributesParagraph = new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderProductVariant.AttributeDescription, true), attributesFont); cell.AddElement(attributesParagraph); productsTable.AddCell(cell); //price string unitPrice = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.UnitPriceExclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.UnitPriceInclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } break; } cell = new PdfPCell(new Phrase(unitPrice, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); //qty cell = new PdfPCell(new Phrase(orderProductVariant.Quantity.ToString(), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); //total string subTotal = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.PriceExclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } break; case TaxDisplayType.IncludingTax: { var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.PriceInclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } break; } cell = new PdfPCell(new Phrase(subTotal, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); } doc.Add(productsTable); #endregion #region Checkout attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { doc.Add(new Paragraph(" ")); string attributes = HtmlHelper.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true); var pCheckoutAttributes = new Paragraph(attributes, font); pCheckoutAttributes.Alignment = Element.ALIGN_RIGHT; doc.Add(pCheckoutAttributes); doc.Add(new Paragraph(" ")); } #endregion #region Totals //subtotal doc.Add(new Paragraph(" ")); switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); string orderSubtotalExclTaxStr = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); string orderSubtotalInclTaxStr = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } //discount (applied to order subtotal) if (order.OrderSubTotalDiscountExclTax > decimal.Zero) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //shipping if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); string orderShippingExclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); string orderShippingInclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //payment fee if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); string paymentMethodAdditionalFeeInclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //tax string taxStr = string.Empty; var taxRates = new SortedDictionary <decimal, decimal>(); bool displayTax = true; bool displayTaxRates = true; if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { displayTax = false; } else { if (order.OrderTax == 0 && _taxSettings.HideZeroTax) { displayTax = false; displayTaxRates = false; } else { taxRates = order.TaxRatesDictionary; displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); //TODO pass languageId to _priceFormatter.FormatPrice taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false); } } if (displayTax) { var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } if (displayTaxRates) { foreach (var item in taxRates) { string taxRate = String.Format(_localizationService.GetResource("PDFInvoice.TaxRate"), _priceFormatter.FormatTaxRate(item.Key)); //TODO pass languageId to _priceFormatter.FormatPrice string taxValue = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(item.Value, order.CurrencyRate), true, false); var p = new Paragraph(String.Format("{0} {1}", taxRate, taxValue), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } } //discount (applied to order total) if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); string orderDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //gift cards foreach (var gcuh in order.GiftCardUsageHistory) { string gcTitle = string.Format(_localizationService.GetResource("PDFInvoice.GiftCardInfo", lang.Id), gcuh.GiftCard.GiftCardCouponCode); string gcAmountStr = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false); var p = new Paragraph(String.Format("{0} {1}", gcTitle, gcAmountStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //reward points if (order.RedeemedRewardPointsEntry != null) { string rpTitle = string.Format(_localizationService.GetResource("PDFInvoice.RewardPoints", lang.Id), -order.RedeemedRewardPointsEntry.Points); string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false); var p = new Paragraph(String.Format("{0} {1}", rpTitle, rpAmount), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //order total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); //TODO pass languageId to _priceFormatter.FormatPrice string orderTotalStr = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false); var pTotal = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.OrderTotal", lang.Id), orderTotalStr), titleFont); pTotal.Alignment = Element.ALIGN_RIGHT; doc.Add(pTotal); #endregion #region Order notes if (_pdfSettings.RenderOrderNotes) { var orderNotes = order.OrderNotes .Where(on => on.DisplayToCustomer) .OrderByDescending(on => on.CreatedOnUtc) .ToList(); if (orderNotes.Count > 0) { doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.OrderNotes", lang.Id), titleFont)); doc.Add(new Paragraph(" ")); var notesTable = new PdfPTable(2); notesTable.WidthPercentage = 100f; notesTable.SetWidths(new[] { 30, 70 }); //created on cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.CreatedOn", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cell); //note cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.Note", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cell); foreach (var orderNote in orderNotes) { cell = new PdfPCell(); cell.AddElement(new Paragraph(_dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc).ToString(), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cell); cell = new PdfPCell(); cell.AddElement(new Paragraph(HtmlHelper.ConvertHtmlToPlainText(HtmlHelper.FormatText(orderNote.Note, false, true, false, false, false, false), true), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cell); } doc.Add(notesTable); } } #endregion doc.Close(); }
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.Status = order.OrderStatus; 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.Shipped) { model.OrderStatus = model.ShippingStatus; } 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.TrackingUrl = order.GetTrackingUrl(); } //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.PluginDescriptor.FriendlyName : order.PaymentMethodSystemName; //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); model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, 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, _workContext.WorkingLanguage, false), }); } } } 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 = Nop.Core.Html.HtmlHelper.FormatText(orderNote.Note, false, true, false, false, false, false), 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; } //picture var picture = opv.ProductVariant.GetDefaultProductVariantPicture(_pictureService); if (picture == null) { picture = _pictureService.GetPicturesByProductId(opv.ProductVariant.Product.Id, 1).FirstOrDefault(); } var pictureModel = new PictureModel() { ImageUrl = _pictureService.GetPictureUrl(picture, _mediaSettings.CartThumbPictureSize, true), Title = string.Format(_localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), opv.ProductVariant.Product.Name), AlternateText = string.Format(_localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), opv.ProductVariant.Name), }; opvModel.Picture = pictureModel; } //Order Items add Return Request var returnRequests = _orderService.SearchReturnRequests(_workContext.CurrentCustomer.Id, 0, null); model.HasReturnRequest = false; foreach (var returnRequest in returnRequests) { var opv = _orderService.GetOrderProductVariantById(returnRequest.OrderProductVariantId); if (opv.OrderId == model.Id) { model.HasReturnRequest = true; var pv = opv.ProductVariant; var request = new OrderDetailsModel.OrderProductVariantModel.OrderProductVariantReturnRequest() { RequestAction = returnRequest.RequestedAction, ReturnRequestStatusId = returnRequest.ReturnRequestStatusId, ReturnRequestStatus = returnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, _workContext), ReturnRequestDate = returnRequest.UpdatedOnUtc }; model.Items.Where(x => x.ProductId == pv.ProductId).FirstOrDefault().ItemsReturnRequest = request; } } return(model); }
protected SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; //return reasons if (_orderSettings.ReturnRequestReasons != null) { foreach (var rrr in _orderSettings.ReturnRequestReasons) { model.AvailableReturnReasons.Add(new SelectListItem() { Text = rrr, Value = rrr }); } } //return actions if (_orderSettings.ReturnRequestActions != null) { foreach (var rra in _orderSettings.ReturnRequestActions) { model.AvailableReturnActions.Add(new SelectListItem() { Text = rra, Value = rra }); } } //products var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null); foreach (var opv in orderProductVariants) { var opvModel = new SubmitReturnRequestModel.OrderProductVariantModel() { Id = opv.Id, ProductId = opv.ProductVariant.ProductId, ProductSeName = opv.ProductVariant.Product.GetSeName(), AttributeInfo = opv.AttributeDescription, Quantity = opv.Quantity }; //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 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); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate); opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } break; } } return(model); }
/// <summary> /// Convert a collection to a HTML table /// </summary> /// <param name="order">Order</param> /// <param name="languageId">Language identifier</param> /// <returns>HTML table of products</returns> protected virtual string ProductListToHtmlTable(Order order, int languageId) { var result = ""; var language = _languageService.GetLanguageById(languageId); var sb = new StringBuilder(); sb.AppendLine("<table border=\"0\" style=\"width:100%;\">"); #region Products sb.AppendLine(string.Format("<tr style=\"background-color:{0};text-align:center;\">", _templatesSettings.Color1)); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Name", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Price", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Quantity", languageId))); sb.AppendLine(string.Format("<th>{0}</th>", _localizationService.GetResource("Messages.Order.Product(s).Total", languageId))); sb.AppendLine("</tr>"); var table = order.OrderProductVariants.ToList(); for (int i = 0; i <= table.Count - 1; i++) { var opv = table[i]; var productVariant = opv.ProductVariant; if (productVariant == null) { continue; } sb.AppendLine(string.Format("<tr style=\"background-color: {0};text-align: center;\">", _templatesSettings.Color2)); //product name string productName = ""; //product name if (!String.IsNullOrEmpty(opv.ProductVariant.GetLocalized(x => x.Name, languageId))) { productName = string.Format("{0} ({1})", opv.ProductVariant.Product.GetLocalized(x => x.Name, languageId), opv.ProductVariant.GetLocalized(x => x.Name, languageId)); } else { productName = opv.ProductVariant.Product.GetLocalized(x => x.Name, languageId); } sb.AppendLine("<td style=\"padding: 0.6em 0.4em;text-align: left;\">" + HttpUtility.HtmlEncode(productName)); //add download link if (_downloadService.IsDownloadAllowed(opv)) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string downloadUrl = string.Format("{0}download/getdownload/{1}", _webHelper.GetStoreLocation(false), opv.OrderProductVariantGuid); string downloadLink = string.Format("<a class=\"link\" href=\"{0}\">{1}</a>", downloadUrl, _localizationService.GetResource("Messages.Order.Product(s).Download", languageId)); sb.AppendLine(" ("); sb.AppendLine(downloadLink); sb.AppendLine(")"); } //attributes if (!String.IsNullOrEmpty(opv.AttributeDescription)) { sb.AppendLine("<br />"); sb.AppendLine(opv.AttributeDescription); } //sku if (_catalogSettings.ShowProductSku) { var sku = opv.ProductVariant.FormatSku(opv.AttributesXml, _productAttributeParser); if (!String.IsNullOrEmpty(sku)) { sb.AppendLine("<br />"); sb.AppendLine(string.Format(_localizationService.GetResource("Messages.Order.Product(s).SKU", languageId), HttpUtility.HtmlEncode(sku))); } } sb.AppendLine("</td>"); string unitPriceStr = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceExclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate); unitPriceStr = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } break; } sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: right;\">{0}</td>", unitPriceStr)); sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: center;\">{0}</td>", opv.Quantity)); string priceStr = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceExclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } break; case TaxDisplayType.IncludingTax: { var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceInclTax, order.CurrencyRate); priceStr = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } break; } sb.AppendLine(string.Format("<td style=\"padding: 0.6em 0.4em;text-align: right;\">{0}</td>", priceStr)); sb.AppendLine("</tr>"); } #endregion #region Checkout Attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"1\"> </td><td colspan=\"3\" style=\"text-align:right\">"); sb.AppendLine(order.CheckoutAttributeDescription); sb.AppendLine("</td></tr>"); } #endregion #region Totals string cusSubTotal = string.Empty; bool dislaySubTotalDiscount = false; string cusSubTotalDiscount = string.Empty; string cusShipTotal = string.Empty; string cusPaymentMethodAdditionalFee = string.Empty; var taxRates = new SortedDictionary <decimal, decimal>(); string cusTaxTotal = string.Empty; string cusDiscount = string.Empty; string cusTotal = string.Empty; //subtotal, shipping, payment method fee switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { //subtotal var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); //discount (applied to order subtotal) var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero) { cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); dislaySubTotalDiscount = true; } //shipping var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); //payment method additional fee var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } break; case TaxDisplayType.IncludingTax: { //subtotal var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); cusSubTotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); //discount (applied to order subtotal) var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero) { cusSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); dislaySubTotalDiscount = true; } //shipping var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); //payment method additional fee var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } break; } //shipping bool dislayShipping = order.ShippingStatus != ShippingStatus.ShippingNotRequired; //payment method fee bool displayPaymentMethodFee = true; if (order.PaymentMethodAdditionalFeeExclTax == decimal.Zero) { displayPaymentMethodFee = 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 { taxRates = new SortedDictionary <decimal, decimal>(); foreach (var tr in order.TaxRatesDictionary) { taxRates.Add(tr.Key, _currencyService.ConvertCurrency(tr.Value, order.CurrencyRate)); } displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); string taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); cusTaxTotal = taxStr; } } //discount bool dislayDiscount = false; if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); cusDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); dislayDiscount = true; } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); cusTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, language); //subtotal sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotal", languageId), cusSubTotal)); //discount (applied to order subtotal) if (dislaySubTotalDiscount) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotalDiscount", languageId), cusSubTotalDiscount)); } //shipping if (dislayShipping) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.Shipping", languageId), cusShipTotal)); } //payment method fee if (displayPaymentMethodFee) { string paymentMethodFeeTitle = _localizationService.GetResource("Messages.Order.PaymentMethodAdditionalFee", languageId); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, paymentMethodFeeTitle, cusPaymentMethodAdditionalFee)); } //tax if (displayTax) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.Tax", languageId), cusTaxTotal)); } if (displayTaxRates) { foreach (var item in taxRates) { string taxRate = String.Format(_localizationService.GetResource("Messages.Order.TaxRateLine"), _priceFormatter.FormatTaxRate(item.Key)); string taxValue = _priceFormatter.FormatPrice(item.Value, true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, taxRate, taxValue)); } } //discount if (dislayDiscount) { sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.TotalDiscount", languageId), cusDiscount)); } //gift cards var gcuhC = order.GiftCardUsageHistory; foreach (var gcuh in gcuhC) { string giftCardText = String.Format(_localizationService.GetResource("Messages.Order.GiftCardInfo", languageId), HttpUtility.HtmlEncode(gcuh.GiftCard.GiftCardCouponCode)); string giftCardAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, giftCardText, giftCardAmount)); } //reward points if (order.RedeemedRewardPointsEntry != null) { string rpTitle = string.Format(_localizationService.GetResource("Messages.Order.RewardPoints", languageId), -order.RedeemedRewardPointsEntry.Points); string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language); sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, rpTitle, rpAmount)); } //total sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.OrderTotal", languageId), cusTotal)); #endregion sb.AppendLine("</table>"); result = sb.ToString(); return(result); }
private OrderDetailsModel.OrderItemModel PrepareOrderItemModel( Order order, OrderItem orderItem, CatalogSettings catalogSettings, ShoppingCartSettings shoppingCartSettings, MediaSettings mediaSettings) { var language = _services.WorkContext.WorkingLanguage; orderItem.Product.MergeWithCombination(orderItem.AttributesXml); var model = new OrderDetailsModel.OrderItemModel { Id = orderItem.Id, Sku = orderItem.Product.Sku, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), ProductType = orderItem.Product.ProductType, Quantity = orderItem.Quantity, AttributeInfo = orderItem.AttributeDescription }; var quantityUnit = _quantityUnitService.GetQuantityUnitById(orderItem.Product.QuantityUnitId); model.QuantityUnit = quantityUnit == null ? "" : quantityUnit.GetLocalized(x => x.Name); if (orderItem.Product.ProductType == ProductType.BundledProduct && orderItem.BundleData.HasValue()) { var bundleData = orderItem.GetBundleData(); var bundleItems = shoppingCartSettings.ShowProductBundleImagesOnShoppingCart ? _productService.GetBundleItems(orderItem.ProductId).ToDictionarySafe(x => x.Item.ProductId) : new Dictionary <int, ProductBundleItemData>(); model.BundlePerItemPricing = orderItem.Product.BundlePerItemPricing; model.BundlePerItemShoppingCart = bundleData.Any(x => x.PerItemShoppingCart); foreach (var bid in bundleData) { var bundleItemModel = new OrderDetailsModel.BundleItemModel { Sku = bid.Sku, ProductName = bid.ProductName, ProductSeName = bid.ProductSeName, VisibleIndividually = bid.VisibleIndividually, Quantity = bid.Quantity, DisplayOrder = bid.DisplayOrder, AttributeInfo = bid.AttributesInfo }; bundleItemModel.ProductUrl = _productUrlHelper.GetProductUrl(bid.ProductId, bundleItemModel.ProductSeName, bid.AttributesXml); if (model.BundlePerItemShoppingCart) { var priceWithDiscount = _currencyService.ConvertCurrency(bid.PriceWithDiscount, order.CurrencyRate); bundleItemModel.PriceWithDiscount = _priceFormatter.FormatPrice(priceWithDiscount, true, order.CustomerCurrencyCode, language, false, false); } // Bundle item picture. if (shoppingCartSettings.ShowProductBundleImagesOnShoppingCart && bundleItems.TryGetValue(bid.ProductId, out var bundleItem)) { bundleItemModel.HideThumbnail = bundleItem.Item.HideThumbnail; bundleItemModel.Picture = PrepareOrderItemPictureModel( bundleItem.Item.Product, mediaSettings.CartThumbBundleItemPictureSize, bid.ProductName, bid.AttributesXml, catalogSettings); } model.BundleItems.Add(bundleItemModel); } } // Unit price, subtotal. switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); model.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false, false); var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate); model.SubTotal = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false, false); } break; case TaxDisplayType.IncludingTax: { var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); model.UnitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true, false); var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate); model.SubTotal = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true, false); } break; } model.ProductUrl = _productUrlHelper.GetProductUrl(model.ProductSeName, orderItem); if (shoppingCartSettings.ShowProductImagesOnShoppingCart) { model.Picture = PrepareOrderItemPictureModel( orderItem.Product, mediaSettings.CartThumbPictureSize, model.ProductName, orderItem.AttributesXml, catalogSettings); } 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); //shipping info model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _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?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; } //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.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() { Id = orderNote.Id, HasDownload = orderNote.DownloadId > 0, Note = orderNote.FormatOrderNoteText(), CreatedOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc) }); } //purchased products model.ShowSku = _catalogSettings.ShowProductSku; var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { string imgUrl = string.Empty; if (orderItem.Product.ProductPictures.Count > 0) { var picture = orderItem.Product.ProductPictures.FirstOrDefault(); imgUrl = _pictureService.GetPictureUrl(picture.PictureId); } var orderItemModel = new OrderDetailsModel.OrderItemModel() { Id = orderItem.Id, 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, ProductImageUrl = imgUrl }; 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); } } return(model); }
protected SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; var language = Services.WorkContext.WorkingLanguage; string returnRequestReasons = _orderSettings.GetLocalized(x => x.ReturnRequestReasons, order.CustomerLanguageId, true, false); string returnRequestActions = _orderSettings.GetLocalized(x => x.ReturnRequestActions, order.CustomerLanguageId, true, false); // Return reasons. foreach (var rrr in returnRequestReasons.SplitSafe(",")) { model.AvailableReturnReasons.Add(new SelectListItem { Text = rrr, Value = rrr }); } // Return actions. foreach (var rra in returnRequestActions.SplitSafe(",")) { model.AvailableReturnActions.Add(new SelectListItem { Text = rra, Value = rra }); } // Products. var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { var orderItemModel = new SubmitReturnRequestModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, Quantity = orderItem.Quantity }; orderItemModel.ProductUrl = _productUrlHelper.GetProductUrl(orderItemModel.ProductSeName, orderItem); // Unit price. switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false); } break; case TaxDisplayType.IncludingTax: { var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true); } break; } model.Items.Add(orderItemModel); } return(model); }
protected SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) { throw new ArgumentNullException("order"); } if (model == null) { throw new ArgumentNullException("model"); } model.OrderId = order.Id; //return reasons if (_orderSettings.ReturnRequestReasons != null) { foreach (var rrr in _orderSettings.ReturnRequestReasons) { model.AvailableReturnReasons.Add(new SelectListItem() { Text = rrr, Value = rrr }); } } //return actions if (_orderSettings.ReturnRequestActions != null) { foreach (var rra in _orderSettings.ReturnRequestActions) { model.AvailableReturnActions.Add(new SelectListItem() { Text = rra, Value = rra }); } } //products var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); foreach (var orderItem in orderItems) { var orderItemModel = new SubmitReturnRequestModel.OrderItemModel() { Id = orderItem.Id, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, Quantity = orderItem.Quantity }; model.Items.Add(orderItemModel); //unit price 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); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); orderItemModel.UnitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } } return(model); }
private async Task PrepareOrderTotal(GetOrderDetails request, OrderDetailsModel model) { if (request.Order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal) { //including tax //order subtotal var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderSubtotalInclTax, request.Order.CurrencyRate); model.OrderSubtotal = await _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, true); //discount (applied to order subtotal) var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderSubTotalDiscountInclTax, request.Order.CurrencyRate); if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero) { model.OrderSubTotalDiscount = await _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, true); } } else { //excluding tax //order subtotal var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderSubtotalExclTax, request.Order.CurrencyRate); model.OrderSubtotal = await _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, false); //discount (applied to order subtotal) var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderSubTotalDiscountExclTax, request.Order.CurrencyRate); if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero) { model.OrderSubTotalDiscount = await _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, false); } } if (request.Order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax //order shipping var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderShippingInclTax, request.Order.CurrencyRate); model.OrderShipping = await _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, true); //payment method additional fee var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.PaymentMethodAdditionalFeeInclTax, request.Order.CurrencyRate); if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero) { model.PaymentMethodAdditionalFee = await _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, true); } } else { //excluding tax //order shipping var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderShippingExclTax, request.Order.CurrencyRate); model.OrderShipping = await _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, false); //payment method additional fee var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.PaymentMethodAdditionalFeeExclTax, request.Order.CurrencyRate); if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero) { model.PaymentMethodAdditionalFee = await _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, request.Order.CustomerCurrencyCode, request.Language, false); } } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(request.Order.OrderTotal, request.Order.CurrencyRate); model.OrderTotal = await _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, request.Order.CustomerCurrencyCode, false, request.Language); }
protected OrderDetailsModel PrepareOrderDetailsModel(Order order) { if (order == null) { throw new ArgumentNullException("order"); } var store = _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 model = new OrderDetailsModel(); model.MerchantCompanyInfo = companyInfoSettings; model.Id = order.Id; model.StoreId = order.StoreId; 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); } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, 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); model.Items.Add(orderItemModel); } return(model); }
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); }