public string ToInfoString(AmazonPayApiData data) { var sb = new StringBuilder(); try { string[] strings = _localizationService.GetResource("Plugins.Payments.AmazonPay.MessageStrings").SplitSafe(";"); string state = data.State.Grow(data.ReasonCode, " "); if (data.ReasonDescription.HasValue()) { state = "{0} ({1})".FormatWith(state, data.ReasonDescription); } sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.MessageTyp), data.MessageType.NaIfEmpty())); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.State), state)); var stateDate = _dateTimeHelper.ConvertToUserTime(data.StateLastUpdate, DateTimeKind.Utc); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.StateUpdate), stateDate.ToString())); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.MessageId), data.MessageId.NaIfEmpty())); if (data.AuthorizationId.HasValue()) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.AuthorizationID), data.AuthorizationId)); } if (data.CaptureId.HasValue()) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.CaptureID), data.CaptureId)); } if (data.RefundId.HasValue()) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.RefundID), data.RefundId)); } sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.ReferenceID), data.ReferenceId.NaIfEmpty())); if (data.Fee != null && data.Fee.Amount != 0.0) { bool isSigned = (data.MessageType.IsCaseInsensitiveEqual("RefundNotification") || data.MessageType.IsCaseInsensitiveEqual("GetRefundDetails")); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.Fee), (isSigned ? "-" : "") + data.Fee.ToString())); } if (data.AuthorizedAmount != null && data.AuthorizedAmount.Amount != 0.0) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.AuthorizedAmount), data.AuthorizedAmount.ToString())); } if (data.CapturedAmount != null && data.CapturedAmount.Amount != 0.0) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.CapturedAmount), data.CapturedAmount.ToString())); } if (data.RefundedAmount != null && data.RefundedAmount.Amount != 0.0) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.RefundedAmount), data.RefundedAmount.ToString())); } if (data.CaptureNow.HasValue) { sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.CaptureNow), data.CaptureNow.Value.ToString())); } var creationDate = _dateTimeHelper.ConvertToUserTime(data.Creation, DateTimeKind.Utc); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.Creation), creationDate.ToString())); if (data.Expiration.HasValue) { var expirationDate = _dateTimeHelper.ConvertToUserTime(data.Expiration.Value, DateTimeKind.Utc); sb.AppendLine("{0}: {1}".FormatWith(strings.SafeGet((int)AmazonPayMessage.Expiration), expirationDate.ToString())); } } catch (Exception exc) { exc.Dump(); } return(sb.ToString()); }
/// <summary> /// Prepare system info model /// </summary> /// <param name="model">System info model</param> /// <returns>System info model</returns> public virtual SystemInfoModel PrepareSystemInfoModel(SystemInfoModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.NopVersion = NopVersion.CurrentVersion; model.ServerTimeZone = TimeZoneInfo.Local.StandardName; model.ServerLocalTime = DateTime.Now; model.UtcTime = DateTime.UtcNow; model.CurrentUserTime = _dateTimeHelper.ConvertToUserTime(DateTime.Now); model.HttpHost = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Host]; //ensure no exception is thrown try { model.OperatingSystem = Environment.OSVersion.VersionString; model.AspNetInfo = RuntimeEnvironment.GetSystemVersion(); model.IsFullTrust = AppDomain.CurrentDomain.IsFullyTrusted.ToString(); } catch { } foreach (var header in _httpContextAccessor.HttpContext.Request.Headers) { model.Headers.Add(new SystemInfoModel.HeaderModel { Name = header.Key, Value = header.Value }); } foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var loadedAssemblyModel = new SystemInfoModel.LoadedAssembly { FullName = assembly.FullName }; //ensure no exception is thrown try { loadedAssemblyModel.Location = assembly.IsDynamic ? null : assembly.Location; loadedAssemblyModel.IsDebug = assembly.GetCustomAttributes(typeof(DebuggableAttribute), false) .FirstOrDefault() is DebuggableAttribute attribute && attribute.IsJITOptimizerDisabled; //https://stackoverflow.com/questions/2050396/getting-the-date-of-a-net-assembly //we use a simple method because the more Jeff Atwood's solution doesn't work anymore //more info at https://blog.codinghorror.com/determining-build-date-the-hard-way/ loadedAssemblyModel.BuildDate = assembly.IsDynamic ? null : (DateTime?)TimeZoneInfo.ConvertTimeFromUtc(_fileProvider.GetLastWriteTimeUtc(assembly.Location), TimeZoneInfo.Local); } catch { } model.LoadedAssemblies.Add(loadedAssemblyModel); } model.CurrentStaticCacheManager = _cacheManager.GetType().Name; model.RedisEnabled = _nopConfig.RedisEnabled; model.UseRedisToStoreDataProtectionKeys = _nopConfig.UseRedisToStoreDataProtectionKeys; model.UseRedisForCaching = _nopConfig.UseRedisForCaching; model.UseRedisToStorePluginsInfo = _nopConfig.UseRedisToStorePluginsInfo; model.AzureBlobStorageEnabled = _nopConfig.AzureBlobStorageEnabled; return(model); }
public virtual ActionResult SystemInfo() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance)) { return(AccessDeniedView()); } var model = new SystemInfoModel(); model.NopVersion = NopVersion.CurrentVersion; try { model.OperatingSystem = Environment.OSVersion.VersionString; } catch (Exception) { } try { model.AspNetInfo = RuntimeEnvironment.GetSystemVersion(); } catch (Exception) { } try { model.IsFullTrust = AppDomain.CurrentDomain.IsFullyTrusted.ToString(); } catch (Exception) { } model.ServerTimeZone = TimeZone.CurrentTimeZone.StandardName; model.ServerLocalTime = DateTime.Now; model.UtcTime = DateTime.UtcNow; model.CurrentUserTime = _dateTimeHelper.ConvertToUserTime(DateTime.Now); model.HttpHost = _webHelper.ServerVariables("HTTP_HOST"); foreach (var key in _httpContext.Request.ServerVariables.AllKeys) { if (key.StartsWith("ALL_")) { continue; } model.ServerVariables.Add(new SystemInfoModel.ServerVariableModel { Name = key, Value = _httpContext.Request.ServerVariables[key] }); } //Environment.GetEnvironmentVariable("USERNAME"); var trustLevel = CommonHelper.GetTrustLevel(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var loadedAssembly = new SystemInfoModel.LoadedAssembly { FullName = assembly.FullName, }; //ensure no exception is thrown try { var canGetLocation = trustLevel >= AspNetHostingPermissionLevel.High && !assembly.IsDynamic; loadedAssembly.Location = canGetLocation ? assembly.Location : null; loadedAssembly.IsDebug = IsDebugAssembly(assembly); loadedAssembly.BuildDate = canGetLocation ? (DateTime?)GetBuildDate(assembly, TimeZoneInfo.Local) : null; } catch (Exception) { } model.LoadedAssemblies.Add(loadedAssembly); } return(View(model)); }
protected OrderDetailsModel PrepareOrderDetailsModel(Order order) { if (order == null) { throw new ArgumentNullException("order"); } var model = new OrderDetailsModel(); model.Id = order.Id; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc); model.OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext); model.IsReOrderAllowed = _orderSettings.IsReOrderAllowed; model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order); model.DisplayPdfInvoice = _pdfSettings.Enabled; //shipping info model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext); if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { model.IsShippable = true; model.ShippingAddress = order.ShippingAddress.ToModel(); model.ShippingMethod = order.ShippingMethod; model.OrderWeight = order.OrderWeight; var baseWeight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId); if (baseWeight != null) { model.BaseWeightIn = baseWeight.Name; } //shipments var shipments = order.Shipments.OrderBy(x => x.ShippedDateUtc).ToList(); foreach (var shipment in shipments) { var shipmentModel = new OrderDetailsModel.ShipmentBriefModel() { Id = shipment.Id, TrackingNumber = shipment.TrackingNumber, ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc, DateTimeKind.Utc), }; if (shipment.DeliveryDateUtc.HasValue) { shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc); } model.Shipments.Add(shipmentModel); } } //billing info model.BillingAddress = order.BillingAddress.ToModel(); //VAT number model.VatNumber = order.VatNumber; //payment method var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); model.PaymentMethod = paymentMethod != null?paymentMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) : order.PaymentMethodSystemName; model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order); //totals) switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { //order subtotal var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); //discount (applied to order subtotal) var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero) { model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } //order shipping var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); //payment method additional fee var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero) { model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } } break; case TaxDisplayType.IncludingTax: { //order subtotal var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); //discount (applied to order subtotal) var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero) { model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } //order shipping var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); //payment method additional fee var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero) { model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } } break; } //tax bool displayTax = true; bool displayTaxRates = true; if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { displayTax = false; displayTaxRates = false; } else { if (order.OrderTax == 0 && _taxSettings.HideZeroTax) { displayTax = false; displayTaxRates = false; } else { displayTaxRates = _taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); //TODO pass languageId to _priceFormatter.FormatPrice model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); foreach (var tr in order.TaxRatesDictionary) { model.TaxRates.Add(new OrderDetailsModel.TaxRate() { Rate = _priceFormatter.FormatTaxRate(tr.Key), //TODO pass languageId to _priceFormatter.FormatPrice Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage), }); } } } model.DisplayTaxRates = displayTaxRates; model.DisplayTax = displayTax; //discount (applied to order total) var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); if (orderDiscountInCustomerCurrency > decimal.Zero) { model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); } //gift cards foreach (var gcuh in order.GiftCardUsageHistory) { model.GiftCards.Add(new OrderDetailsModel.GiftCard() { CouponCode = gcuh.GiftCard.GiftCardCouponCode, Amount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage), }); } //reward points if (order.RedeemedRewardPointsEntry != null) { model.RedeemedRewardPoints = -order.RedeemedRewardPointsEntry.Points; model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); } //total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); //checkout attributes model.CheckoutAttributeInfo = order.CheckoutAttributeDescription; //order notes foreach (var orderNote in order.OrderNotes .Where(on => on.DisplayToCustomer) .OrderByDescending(on => on.CreatedOnUtc) .ToList()) { model.OrderNotes.Add(new OrderDetailsModel.OrderNote() { Note = orderNote.FormatOrderNoteText(), CreatedOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc) }); } //purchased products model.ShowSku = _catalogSettings.ShowProductSku; var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null); foreach (var opv in orderProductVariants) { var opvModel = new OrderDetailsModel.OrderProductVariantModel() { Id = opv.Id, Sku = opv.ProductVariant.Sku, ProductId = opv.ProductVariant.ProductId, ProductSeName = opv.ProductVariant.Product.GetSeName(), Quantity = opv.Quantity, AttributeInfo = opv.AttributeDescription, }; //product name if (!String.IsNullOrEmpty(opv.ProductVariant.GetLocalized(x => x.Name))) { opvModel.ProductName = string.Format("{0} ({1})", opv.ProductVariant.Product.GetLocalized(x => x.Name), opv.ProductVariant.GetLocalized(x => x.Name)); } else { opvModel.ProductName = opv.ProductVariant.Product.GetLocalized(x => x.Name); } model.Items.Add(opvModel); //unit price, subtotal switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceExclTax, order.CurrencyRate); opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceExclTax, order.CurrencyRate); opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate); opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.PriceInclTax, order.CurrencyRate); opvModel.SubTotal = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } break; } } return(model); }
public List <DataSet> GetTransActivityDataSet(string period, string category, IEnumerable <TransActivityModel> models) { var result = new List <DataSet>(); var query = models.AsQueryable(); var nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); var features = _httpContextAccessor.HttpContext?.Features?.Get <IRequestCultureFeature>(); var culture = features?.RequestCulture.Culture; switch (period) { case "year": var yearAgoDt = nowDt.AddYears(-1).AddMonths(1); var yearToSearch = new DateTime(yearAgoDt.Year, yearAgoDt.Month, 1); for (var i = 0; i <= 12; i++) { query = query.Where(item => yearToSearch <= item.CreatedOn); query = query.Where(item => yearToSearch.AddMonths(1) >= item.CreatedOn); result.Add(new DataSet { label = yearToSearch.Date.ToString("Y", culture), data = query.Count(item => item.Category == category).ToString() }); yearToSearch = yearToSearch.AddMonths(1); } break; case "month": var monthAgoDt = nowDt.AddDays(-30); var monthToSearch = new DateTime(monthAgoDt.Year, monthAgoDt.Month, monthAgoDt.Day); for (var i = 0; i <= 30; i++) { query = query.Where(item => monthToSearch <= item.CreatedOn); query = query.Where(item => monthToSearch.AddDays(1) >= item.CreatedOn); result.Add(new DataSet { label = monthToSearch.Date.ToString("M", culture), data = query.Count(item => item.Category == category).ToString() }); monthToSearch = monthToSearch.AddDays(1); } break; case "week": var weekAgoDt = nowDt.AddDays(-7); var weekToSearch = new DateTime(weekAgoDt.Year, weekAgoDt.Month, weekAgoDt.Day); for (var i = 0; i <= 7; i++) { query = query.Where(item => weekToSearch <= item.CreatedOn); query = query.Where(item => weekToSearch.AddDays(1) >= item.CreatedOn); result.Add(new DataSet { label = weekToSearch.Date.ToString("d dddd", culture), data = query.Count(item => item.Category == category).ToString() }); weekToSearch = weekToSearch.AddDays(1); } break; } return(result); }
public virtual IActionResult AffiliatedOrderListGrid(DataSourceRequest command, AffiliateModel.AffiliatedOrderListModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageAffiliates)) { return(AccessDeniedKendoGridJson()); } var affiliate = _affiliateService.GetAffiliateById(model.AffliateId); if (affiliate == null) { throw new ArgumentException("No affiliate found with the specified id"); } var startDateValue = (model.StartDate == null) ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.StartDate.Value, _dateTimeHelper.CurrentTimeZone); var endDateValue = (model.EndDate == null) ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1); var orderStatusIds = model.OrderStatusId > 0 ? new List <int>() { model.OrderStatusId } : null; var paymentStatusIds = model.PaymentStatusId > 0 ? new List <int>() { model.PaymentStatusId } : null; var shippingStatusIds = model.ShippingStatusId > 0 ? new List <int>() { model.ShippingStatusId } : null; var orders = _orderService.SearchOrders( createdFromUtc: startDateValue, createdToUtc: endDateValue, osIds: orderStatusIds, psIds: paymentStatusIds, ssIds: shippingStatusIds, affiliateId: affiliate.Id, pageIndex: command.Page - 1, pageSize: command.PageSize); var gridModel = new DataSourceResult { Data = orders.Select(order => { var orderModel = new AffiliateModel.AffiliatedOrderModel { Id = order.Id, OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext), OrderStatusId = order.OrderStatusId, PaymentStatus = order.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext), ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext), OrderTotal = _priceFormatter.FormatPrice(order.OrderTotal, true, false), CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc), CustomOrderNumber = order.CustomOrderNumber }; return(orderModel); }), Total = orders.TotalCount }; return(Json(gridModel)); }
/// <summary> /// Prepare the customer order list model /// </summary> /// <returns>Customer order list model</returns> public virtual CustomerOrderListModel PrepareCustomerOrderListModel(int?page) { var model = new CustomerOrderListModel(); var pageSize = 5; var orders = _orderService.SearchOrders(storeId: _storeContext.CurrentStore.Id, customerId: _workContext.CurrentCustomer.Id, pageIndex: --page ?? 0, pageSize: pageSize); 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 }; var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); orderModel.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _workContext.WorkingLanguage); model.Orders.Add(orderModel); } model.PagerModel = new PagerModel { PageSize = orders.PageSize, TotalRecords = orders.TotalCount, PageIndex = orders.PageIndex, ShowTotalSummary = false, RouteActionName = "CustomerOrdersListPaged", UseRouteLinks = true, RouteValues = new OrdersListRouteValues { pageNumber = page ?? 0 } }; 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); }
public ActionResult LogList(GridCommand command, LogListModel model) { var gridModel = new GridModel <LogModel>(); if (_permissionService.Authorize(StandardPermissionProvider.ManageSystemLog)) { DateTime?createdOnFromValue = (model.CreatedOnFrom == null) ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.CreatedOnFrom.Value, _dateTimeHelper.CurrentTimeZone); DateTime?createdToFromValue = (model.CreatedOnTo == null) ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.CreatedOnTo.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1); LogLevel?logLevel = model.LogLevelId > 0 ? (LogLevel?)(model.LogLevelId) : null; var logItems = _logService.GetAllLogs( createdOnFromValue, createdToFromValue, model.Logger, model.Message, logLevel, command.Page - 1, command.PageSize); gridModel.Data = logItems.Select(x => { var logModel = new LogModel { Id = x.Id, LogLevelHint = s_logLevelHintMap[x.LogLevel], LogLevel = x.LogLevel.GetLocalizedEnum(_localizationService, _workContext), ShortMessage = x.ShortMessage, FullMessage = x.FullMessage, IpAddress = x.IpAddress, CustomerId = x.CustomerId, CustomerEmail = x.Customer != null ? x.Customer.Email : null, PageUrl = x.PageUrl, ReferrerUrl = x.ReferrerUrl, CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc), Logger = x.Logger, LoggerShort = TruncateLoggerName(x.Logger), HttpMethod = x.HttpMethod, UserName = x.UserName }; return(logModel); }); gridModel.Total = logItems.TotalCount; } else { gridModel.Data = Enumerable.Empty <LogModel>(); NotifyAccessDenied(); } return(new JsonResult { Data = gridModel }); }
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments) { Guard.NotNull(blogPost, nameof(blogPost)); Guard.NotNull(model, nameof(model)); MiniMapper.Map(blogPost, model); model.SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc); model.AddNewComment.DisplayCaptcha = _captchaSettings.CanDisplayCaptcha && _captchaSettings.ShowOnBlogCommentPage; model.Comments.AllowComments = blogPost.AllowComments; model.Comments.NumberOfComments = blogPost.ApprovedCommentCount; model.Comments.AllowCustomersToUploadAvatars = _customerSettings.AllowCustomersToUploadAvatars; model.DisplayAdminLink = _services.Permissions.Authorize(Permissions.System.AccessBackend, _services.WorkContext.CurrentCustomer); model.HasBgImage = blogPost.PreviewDisplayType == PreviewDisplayType.DefaultSectionBg || blogPost.PreviewDisplayType == PreviewDisplayType.PreviewSectionBg; model.PictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.MediaFileId); if (blogPost.PreviewDisplayType == PreviewDisplayType.Default || blogPost.PreviewDisplayType == PreviewDisplayType.DefaultSectionBg) { model.PreviewPictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.MediaFileId); } else if (blogPost.PreviewDisplayType == PreviewDisplayType.Preview || blogPost.PreviewDisplayType == PreviewDisplayType.PreviewSectionBg) { model.PreviewPictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.PreviewMediaFileId); } if (blogPost.PreviewDisplayType == PreviewDisplayType.Preview || blogPost.PreviewDisplayType == PreviewDisplayType.Default || blogPost.PreviewDisplayType == PreviewDisplayType.Bare) { model.SectionBg = string.Empty; } // tags model.Tags = blogPost.ParseTags().Select(x => new BlogPostTagModel { Name = x, SeName = SeoHelper.GetSeName(x, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, true, _seoSettings.SeoNameCharConversion) }).ToList(); if (prepareComments) { var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc); foreach (var bc in blogComments) { var isGuest = bc.Customer.IsGuest(); var commentModel = new CommentModel(model.Comments) { Id = bc.Id, CustomerId = bc.CustomerId, CustomerName = bc.Customer.FormatUserName(_customerSettings, T, false), CommentText = bc.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc), CreatedOnPretty = bc.CreatedOnUtc.RelativeFormat(true, "f"), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && !isGuest }; commentModel.Avatar = bc.Customer.ToAvatarModel(_genericAttributeService, _mediaService, _customerSettings, _mediaSettings, Url, commentModel.CustomerName); model.Comments.Comments.Add(commentModel); } } Services.DisplayControl.Announce(blogPost); }
public async Task <IViewComponentResult> InvokeAsync(string customerProfileId, int pageNumber) { var customer = await _customerService.GetCustomerById(customerProfileId); if (customer == null) { return(Content("")); } if (pageNumber > 0) { pageNumber -= 1; } var pageSize = _forumSettings.LatestCustomerPostsPageSize; var list = await _forumService.GetAllPosts("", customer.Id, string.Empty, false, pageNumber, pageSize); var latestPosts = new List <PostsModel>(); foreach (var forumPost in list) { var posted = string.Empty; if (_forumSettings.RelativeDateTimeFormattingEnabled) { posted = forumPost.CreatedOnUtc.ToString("f"); } else { posted = _dateTimeHelper.ConvertToUserTime(forumPost.CreatedOnUtc, DateTimeKind.Utc).ToString("f"); } var forumtopic = await _forumService.GetTopicById(forumPost.TopicId); if (forumtopic != null) { latestPosts.Add(new PostsModel { ForumTopicId = forumPost.TopicId, ForumTopicTitle = forumtopic.Subject, ForumTopicSlug = forumtopic.GetSeName(), ForumPostText = forumPost.FormatPostText(), Posted = posted }); } } var pagerModel = new PagerModel(_localizationService) { PageSize = list.PageSize, TotalRecords = list.TotalCount, PageIndex = list.PageIndex, ShowTotalSummary = false, RouteActionName = "CustomerProfilePaged", UseRouteLinks = true, RouteValues = new RouteValues { pageNumber = pageNumber, id = customerProfileId } }; var model = new ProfilePostsModel { PagerModel = pagerModel, Posts = latestPosts, }; return(View(model)); }
protected ShipmentDetailsModel PrepareShipmentDetailsModel(Shipment shipment) { if (shipment == null) { throw new ArgumentNullException("shipment"); } var order = shipment.Order; if (order == null) { throw new SmartException(T("Order.NotFound", shipment.OrderId)); } var store = Services.StoreService.GetStoreById(order.StoreId) ?? Services.StoreContext.CurrentStore; var catalogSettings = Services.Settings.LoadSetting <CatalogSettings>(store.Id); var shippingSettings = Services.Settings.LoadSetting <ShippingSettings>(store.Id); var model = new ShipmentDetailsModel { Id = shipment.Id, TrackingNumber = shipment.TrackingNumber, TrackingNumberUrl = shipment.TrackingUrl }; if (shipment.ShippedDateUtc.HasValue) { model.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc); } if (shipment.DeliveryDateUtc.HasValue) { model.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc); } var srcm = _shippingService.LoadShippingRateComputationMethodBySystemName(order.ShippingRateComputationMethodSystemName); if (srcm != null && srcm.IsShippingRateComputationMethodActive(shippingSettings)) { var shipmentTracker = srcm.Value.ShipmentTracker; if (shipmentTracker != null) { // The URL entered by the merchant takes precedence over an automatically generated URL. if (model.TrackingNumberUrl.IsEmpty()) { model.TrackingNumberUrl = shipmentTracker.GetUrl(shipment.TrackingNumber); } if (shippingSettings.DisplayShipmentEventsToCustomers) { var shipmentEvents = shipmentTracker.GetShipmentEvents(shipment.TrackingNumber); if (shipmentEvents != null) { foreach (var shipmentEvent in shipmentEvents) { var shipmentEventCountry = _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode); var shipmentStatusEventModel = new ShipmentDetailsModel.ShipmentStatusEventModel { Country = shipmentEventCountry != null?shipmentEventCountry.GetLocalized(x => x.Name) : shipmentEvent.CountryCode, Date = shipmentEvent.Date, EventName = shipmentEvent.EventName, Location = shipmentEvent.Location }; model.ShipmentStatusEvents.Add(shipmentStatusEventModel); } } } } } // Products in this shipment. model.ShowSku = catalogSettings.ShowProductSku; foreach (var shipmentItem in shipment.ShipmentItems) { var orderItem = _orderService.GetOrderItemById(shipmentItem.OrderItemId); if (orderItem == null) { continue; } orderItem.Product.MergeWithCombination(orderItem.AttributesXml); var shipmentItemModel = new ShipmentDetailsModel.ShipmentItemModel { Id = shipmentItem.Id, Sku = orderItem.Product.Sku, ProductId = orderItem.Product.Id, ProductName = orderItem.Product.GetLocalized(x => x.Name), ProductSeName = orderItem.Product.GetSeName(), AttributeInfo = orderItem.AttributeDescription, QuantityOrdered = orderItem.Quantity, QuantityShipped = shipmentItem.Quantity }; shipmentItemModel.ProductUrl = _productUrlHelper.GetProductUrl(shipmentItemModel.ProductSeName, orderItem); model.Items.Add(shipmentItemModel); } model.Order = _orderHelper.PrepareOrderDetailsModel(order); return(model); }
public ActionResult Info(int customerProfileId) { var customer = _customerService.GetCustomerById(customerProfileId); if (customer == null) { return(RedirectToRoute("HomePage")); } //avatar bool avatarEnabled = false; string avatarUrl = _pictureService.GetDefaultPictureUrl(_mediaSettings.AvatarPictureSize, PictureType.Avatar); if (_customerSettings.AllowCustomersToUploadAvatars) { avatarEnabled = true; var customerAvatarId = customer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId); if (customerAvatarId != 0) { avatarUrl = _pictureService.GetPictureUrl(customerAvatarId, _mediaSettings.AvatarPictureSize, false); } else { if (!_customerSettings.DefaultAvatarEnabled) { avatarEnabled = false; } } } //location bool locationEnabled = false; string location = string.Empty; if (_customerSettings.ShowCustomersLocation) { locationEnabled = true; var countryId = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId); var country = _countryService.GetCountryById(countryId); if (country != null) { location = country.GetLocalized(x => x.Name); } else { locationEnabled = false; } } //private message bool pmEnabled = _forumSettings.AllowPrivateMessages && !customer.IsGuest(); //total forum posts bool totalPostsEnabled = false; int totalPosts = 0; if (_forumSettings.ForumsEnabled && _forumSettings.ShowCustomersPostCount) { totalPostsEnabled = true; totalPosts = customer.GetAttribute <int>(SystemCustomerAttributeNames.ForumPostCount); } //registration date bool joinDateEnabled = false; string joinDate = string.Empty; if (_customerSettings.ShowCustomersJoinDate) { joinDateEnabled = true; joinDate = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc).ToString("f"); } //birth date bool dateOfBirthEnabled = false; string dateOfBirth = string.Empty; if (_customerSettings.DateOfBirthEnabled) { var dob = customer.GetAttribute <DateTime?>(SystemCustomerAttributeNames.DateOfBirth); if (dob.HasValue) { dateOfBirthEnabled = true; dateOfBirth = dob.Value.ToString("D"); } } var model = new ProfileInfoModel() { CustomerProfileId = customer.Id, AvatarEnabled = avatarEnabled, AvatarUrl = avatarUrl, LocationEnabled = locationEnabled, Location = location, PMEnabled = pmEnabled, TotalPostsEnabled = totalPostsEnabled, TotalPosts = totalPosts.ToString(), JoinDateEnabled = joinDateEnabled, JoinDate = joinDate, DateOfBirthEnabled = dateOfBirthEnabled, DateOfBirth = dateOfBirth, }; return(PartialView(model)); }
protected virtual OrderDetailsModel PrepareOrderDetailsModel(Order order) { if (order == null) { throw new ArgumentNullException("order"); } var model = new OrderDetailsModel(); model.Id = order.Id; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc); model.OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext); model.IsReOrderAllowed = _orderSettings.IsReOrderAllowed; model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order); //shipping info model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext); if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { model.IsShippable = true; model.PickUpInStore = order.PickUpInStore; if (!order.PickUpInStore) { 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) { 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, }; 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); }
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); }
private async Task PrepareKnowledgebaseArticleModel(KnowledgebaseArticleModel model, KnowledgebaseArticle article, ICustomerService customerService) { model.Content = article.GetLocalized(y => y.Content, _workContext.WorkingLanguage.Id); model.Name = article.GetLocalized(y => y.Name, _workContext.WorkingLanguage.Id); model.Id = article.Id; model.ParentCategoryId = article.ParentCategoryId; model.SeName = article.GetLocalized(y => y.SeName, _workContext.WorkingLanguage.Id); model.AllowComments = article.AllowComments; model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnArticleCommentPage; var articleComments = await _knowledgebaseService.GetArticleCommentsByArticleId(article.Id); foreach (var ac in articleComments) { var customer = await customerService.GetCustomerById(ac.CustomerId); var commentModel = new KnowledgebaseArticleCommentModel { Id = ac.Id, CustomerId = ac.CustomerId, CustomerName = customer.FormatUserName(_customerSettings.CustomerNameFormat), CommentText = ac.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(ac.CreatedOnUtc, DateTimeKind.Utc), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && customer != null && !customer.IsGuest(), }; if (_customerSettings.AllowCustomersToUploadAvatars) { commentModel.CustomerAvatarUrl = await _pictureService.GetPictureUrl( customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType : PictureType.Avatar); } model.Comments.Add(commentModel); } foreach (var id in article.RelatedArticles) { var a = await _knowledgebaseService.GetPublicKnowledgebaseArticle(id); if (a != null) { model.RelatedArticles.Add(new KnowledgebaseArticleModel { SeName = a.SeName, Id = a.Id, Name = a.Name }); } } var category = await _knowledgebaseService.GetKnowledgebaseCategory(article.ParentCategoryId); if (category != null) { string breadcrumbCacheKey = string.Format(ModelCacheEventConst.KNOWLEDGEBASE_CATEGORY_BREADCRUMB_KEY, article.ParentCategoryId, string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), _storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id); model.CategoryBreadcrumb = await _cacheManager.GetAsync(breadcrumbCacheKey, async() => (await category.GetCategoryBreadCrumb(_knowledgebaseService, _aclService, _storeMappingService)) .Select(catBr => new KnowledgebaseCategoryModel { Id = catBr.Id, Name = catBr.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id), SeName = catBr.GetSeName(_workContext.WorkingLanguage.Id) }) .ToList() ); } }
/// <summary> /// Prepare paged product review list model /// </summary> /// <param name="searchModel">Product review search model</param> /// <returns>Product review list model</returns> public virtual ProductReviewListModel PrepareProductReviewListModel(ProductReviewSearchModel searchModel) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } //get parameters to filter reviews var createdOnFromValue = !searchModel.CreatedOnFrom.HasValue ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnFrom.Value, _dateTimeHelper.CurrentTimeZone); var createdToFromValue = !searchModel.CreatedOnTo.HasValue ? null : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnTo.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1); var isApprovedOnly = searchModel.SearchApprovedId == 0 ? null : searchModel.SearchApprovedId == 1 ? true : (bool?)false; var vendorId = _workContext.CurrentVendor?.Id ?? 0; //get product reviews var productReviews = _productService.GetAllProductReviews(showHidden: true, customerId: 0, approved: isApprovedOnly, fromUtc: createdOnFromValue, toUtc: createdToFromValue, message: searchModel.SearchText, storeId: searchModel.SearchStoreId, productId: searchModel.SearchProductId, vendorId: vendorId, pageIndex: searchModel.Page - 1, pageSize: searchModel.PageSize); //prepare list model var model = new ProductReviewListModel { Data = productReviews.Select(productReview => { //fill in model values from the entity var productReviewModel = new ProductReviewModel { Id = productReview.Id, StoreName = productReview.Store.Name, ProductId = productReview.ProductId, ProductName = productReview.Product.Name, CustomerId = productReview.CustomerId, Rating = productReview.Rating, Title = productReview.Title, IsApproved = productReview.IsApproved }; //convert dates to the user time productReviewModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(productReview.CreatedOnUtc, DateTimeKind.Utc); //fill in additional values (not existing in the entity) productReviewModel.CustomerInfo = productReview.Customer.IsRegistered() ? productReview.Customer.Email : _localizationService.GetResource("Admin.Customers.Guest"); productReviewModel.ReviewText = HtmlHelper.FormatText(productReview.ReviewText, false, true, false, false, false, false); productReviewModel.ReplyText = HtmlHelper.FormatText(productReview.ReplyText, false, true, false, false, false, false); return(productReviewModel); }), Total = productReviews.TotalCount }; return(model); }
private async Task PrepareCartItems(ShoppingCartModel model, GetShoppingCart request) { #region Cart items foreach (var sci in request.Cart) { var product = await _productService.GetProductById(sci.ProductId); if (product == null) { continue; } var cartItemModel = new ShoppingCartModel.ShoppingCartItemModel { Id = sci.Id, Sku = product.FormatSku(sci.AttributesXml, _productAttributeParser), IsCart = sci.ShoppingCartType == ShoppingCartType.ShoppingCart, ProductId = product.Id, WarehouseId = sci.WarehouseId, ProductName = product.GetLocalized(x => x.Name, request.Language.Id), ProductSeName = product.GetSeName(request.Language.Id), Quantity = sci.Quantity, AttributeInfo = await _productAttributeFormatter.FormatAttributes(product, sci.AttributesXml), }; //allow editing? //1. setting enabled? //2. simple product? //3. has attribute or gift card? //4. visible individually? cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing && product.ProductType == ProductType.SimpleProduct && (!String.IsNullOrEmpty(cartItemModel.AttributeInfo) || product.IsGiftCard) && product.VisibleIndividually; //disable removal? //1. do other items require this one? if (product.RequireOtherProducts) { cartItemModel.DisableRemoval = product.RequireOtherProducts && product.ParseRequiredProductIds().Intersect(request.Cart.Select(x => x.ProductId)).Any(); } //warehouse if (!string.IsNullOrEmpty(cartItemModel.WarehouseId)) { cartItemModel.WarehouseName = (await _warehouseService.GetWarehouseById(cartItemModel.WarehouseId))?.Name; } //vendor if (!string.IsNullOrEmpty(product.VendorId)) { var vendor = await _vendorService.GetVendorById(product.VendorId); if (vendor != null) { cartItemModel.VendorId = product.VendorId; cartItemModel.VendorName = vendor.Name; cartItemModel.VendorSeName = vendor.GetSeName(request.Language.Id); } } //allowed quantities var allowedQuantities = product.ParseAllowedQuantities(); foreach (var qty in allowedQuantities) { cartItemModel.AllowedQuantities.Add(new SelectListItem { Text = qty.ToString(), Value = qty.ToString(), Selected = sci.Quantity == qty }); } //recurring info if (product.IsRecurring) { cartItemModel.RecurringInfo = string.Format(_localizationService.GetResource("ShoppingCart.RecurringPeriod"), product.RecurringCycleLength, product.RecurringCyclePeriod.GetLocalizedEnum(_localizationService, request.Language.Id)); } //reservation info if (product.ProductType == ProductType.Reservation) { if (sci.RentalEndDateUtc == default(DateTime) || sci.RentalEndDateUtc == null) { cartItemModel.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.StartDate"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat)); } else { cartItemModel.ReservationInfo = string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Date"), sci.RentalStartDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat), sci.RentalEndDateUtc?.ToString(_shoppingCartSettings.ReservationDateFormat)); } if (!string.IsNullOrEmpty(sci.Parameter)) { cartItemModel.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Option"), sci.Parameter); cartItemModel.Parameter = sci.Parameter; } if (!string.IsNullOrEmpty(sci.Duration)) { cartItemModel.ReservationInfo += "<br>" + string.Format(_localizationService.GetResource("ShoppingCart.Reservation.Duration"), sci.Duration); } } if (sci.ShoppingCartType == ShoppingCartType.Auctions) { cartItemModel.DisableRemoval = true; cartItemModel.AuctionInfo = _localizationService.GetResource("ShoppingCart.auctionwonon") + " " + _dateTimeHelper.ConvertToUserTime(product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc).ToString(); } //unit prices if (product.CallForPrice) { cartItemModel.UnitPrice = _localizationService.GetResource("Products.CallForPrice"); cartItemModel.SubTotal = _localizationService.GetResource("Products.CallForPrice"); cartItemModel.UnitPriceWithoutDiscount = _localizationService.GetResource("Products.CallForPrice"); } else { var unitprices = await _priceCalculationService.GetUnitPrice(sci, product, true); decimal discountAmount = unitprices.discountAmount; List <AppliedDiscount> appliedDiscounts = unitprices.appliedDiscounts; var productprices = await _taxService.GetProductPrice(product, unitprices.unitprice); decimal taxRate = productprices.taxRate; cartItemModel.UnitPriceWithoutDiscountValue = (await _taxService.GetProductPrice(product, (await _priceCalculationService.GetUnitPrice(sci, product, false)).unitprice)).productprice; cartItemModel.UnitPriceWithoutDiscount = _priceFormatter.FormatPrice(cartItemModel.UnitPriceWithoutDiscountValue); cartItemModel.UnitPriceValue = productprices.productprice; cartItemModel.UnitPrice = _priceFormatter.FormatPrice(productprices.productprice); if (appliedDiscounts != null && appliedDiscounts.Any()) { var discount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault().DiscountId); if (discount != null && discount.MaximumDiscountedQuantity.HasValue) { cartItemModel.DiscountedQty = discount.MaximumDiscountedQuantity.Value; } foreach (var disc in appliedDiscounts) { cartItemModel.Discounts.Add(disc.DiscountId); } } //sub total var subtotal = await _priceCalculationService.GetSubTotal(sci, product, true); decimal shoppingCartItemDiscountBase = subtotal.discountAmount; List <AppliedDiscount> scDiscounts = subtotal.appliedDiscounts; var shoppingCartItemSubTotalWithDiscount = (await _taxService.GetProductPrice(product, subtotal.subTotal)).productprice; cartItemModel.SubTotal = _priceFormatter.FormatPrice(shoppingCartItemSubTotalWithDiscount); cartItemModel.SubTotalValue = shoppingCartItemSubTotalWithDiscount; //display an applied discount amount if (shoppingCartItemDiscountBase > decimal.Zero) { shoppingCartItemDiscountBase = (await _taxService.GetProductPrice(product, shoppingCartItemDiscountBase)).productprice; if (shoppingCartItemDiscountBase > decimal.Zero) { cartItemModel.Discount = _priceFormatter.FormatPrice(shoppingCartItemDiscountBase); } } } //picture if (_shoppingCartSettings.ShowProductImagesOnShoppingCart) { cartItemModel.Picture = await PrepareCartItemPicture(product, sci.AttributesXml, request.Language.Id, request.Store.Id); } //item warnings var itemWarnings = await _shoppingCartService.GetShoppingCartItemWarnings(request.Customer, sci, product, false); foreach (var warning in itemWarnings) { cartItemModel.Warnings.Add(warning); } model.Items.Add(cartItemModel); } #endregion }
public OrderAverageReportLineSummary OrderAverageReport(int storeId, OrderStatus os) { var item = new OrderAverageReportLineSummary(); item.OrderStatus = os; DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone; //today var t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); if (!timeZone.IsInvalidTime(t1)) { DateTime?startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); var todayResult = GetOrderAverageReportLine(storeId: storeId, os: os, startTimeUtc: startTime1); item.SumTodayOrders = todayResult.SumOrders; item.CountTodayOrders = todayResult.CountOrders; } //week DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; var today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow)); if (!timeZone.IsInvalidTime(t2)) { DateTime?startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); var weekResult = GetOrderAverageReportLine(storeId: storeId, os: os, startTimeUtc: startTime2); item.SumThisWeekOrders = weekResult.SumOrders; item.CountThisWeekOrders = weekResult.CountOrders; } //month var t3 = new DateTime(nowDt.Year, nowDt.Month, 1); if (!timeZone.IsInvalidTime(t3)) { DateTime?startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); var monthResult = GetOrderAverageReportLine(storeId: storeId, os: os, startTimeUtc: startTime3); item.SumThisMonthOrders = monthResult.SumOrders; item.CountThisMonthOrders = monthResult.CountOrders; } //year var t4 = new DateTime(nowDt.Year, 1, 1); if (!timeZone.IsInvalidTime(t4)) { DateTime?startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); var yearResult = GetOrderAverageReportLine(storeId: storeId, os: os, startTimeUtc: startTime4); item.SumThisYearOrders = yearResult.SumOrders; item.CountThisYearOrders = yearResult.CountOrders; } //all time var allTimeResult = GetOrderAverageReportLine(storeId: storeId, os: os); item.SumAllTimeOrders = allTimeResult.SumOrders; item.CountAllTimeOrders = allTimeResult.CountOrders; return(item); }
public static ScheduleTaskModel ToScheduleTaskModel(this ScheduleTask task, ILocalizationService localization, IDateTimeHelper dateTimeHelper, UrlHelper urlHelper) { var now = DateTime.UtcNow; TimeSpan?dueIn = null; if (task.NextRunUtc.HasValue) { dueIn = task.NextRunUtc.Value - now; } var nextRunPretty = ""; bool isOverdue = false; if (dueIn.HasValue) { if (dueIn.Value.TotalSeconds > 0) { nextRunPretty = dueIn.Value.Prettify(); } else { nextRunPretty = localization.GetResource("Common.Waiting") + "..."; isOverdue = true; } } var isRunning = task.IsRunning; var lastStartOn = task.LastStartUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastStartUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var lastEndOn = task.LastEndUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastEndUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var lastSuccessOn = task.LastSuccessUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastSuccessUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var nextRunOn = task.NextRunUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.NextRunUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var model = new ScheduleTaskModel { Id = task.Id, Name = task.Name, CronExpression = task.CronExpression, CronDescription = CronExpression.GetFriendlyDescription(task.CronExpression), Enabled = task.Enabled, StopOnError = task.StopOnError, LastStart = lastStartOn, LastStartPretty = task.LastStartUtc.HasValue ? task.LastStartUtc.Value.RelativeFormat(true, "f") : "", LastEnd = lastEndOn, LastEndPretty = lastEndOn.HasValue ? lastEndOn.Value.ToString("G") : "", LastSuccess = lastSuccessOn, LastSuccessPretty = lastSuccessOn.HasValue ? lastSuccessOn.Value.ToString("G") : "", NextRun = nextRunOn, NextRunPretty = nextRunPretty, LastError = task.LastError.EmptyNull(), IsRunning = isRunning, CancelUrl = urlHelper.Action("CancelJob", "ScheduleTask", new { id = task.Id }), ExecuteUrl = urlHelper.Action("RunJob", "ScheduleTask", new { id = task.Id }), EditUrl = urlHelper.Action("Edit", "ScheduleTask", new { id = task.Id }), ProgressPercent = task.ProgressPercent, ProgressMessage = task.ProgressMessage, IsOverdue = isOverdue, Duration = "" }; var span = TimeSpan.Zero; if (task.LastStartUtc.HasValue) { span = model.IsRunning ? now - task.LastStartUtc.Value : task.LastEndUtc.Value - task.LastStartUtc.Value; if (span > TimeSpan.Zero) { model.Duration = span.ToString("g"); } } return(model); }
public virtual void AddOrderTokens(IList <Token> tokens, Order order, int languageId) { tokens.Add(new Token("Order.OrderNumber", order.Id.ToString())); tokens.Add(new Token("Order.CustomerFullName", string.Format("{0} {1}", order.BillingAddress.FirstName, order.BillingAddress.LastName))); tokens.Add(new Token("Order.CustomerEmail", order.BillingAddress.Email)); tokens.Add(new Token("Order.BillingFirstName", order.BillingAddress.FirstName)); tokens.Add(new Token("Order.BillingLastName", order.BillingAddress.LastName)); tokens.Add(new Token("Order.BillingPhoneNumber", order.BillingAddress.PhoneNumber)); tokens.Add(new Token("Order.BillingEmail", order.BillingAddress.Email)); tokens.Add(new Token("Order.BillingFaxNumber", order.BillingAddress.FaxNumber)); tokens.Add(new Token("Order.BillingCompany", order.BillingAddress.Company)); tokens.Add(new Token("Order.BillingAddress1", order.BillingAddress.Address1)); tokens.Add(new Token("Order.BillingAddress2", order.BillingAddress.Address2)); tokens.Add(new Token("Order.BillingCity", order.BillingAddress.City)); tokens.Add(new Token("Order.BillingStateProvince", order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.BillingZipPostalCode", order.BillingAddress.ZipPostalCode)); tokens.Add(new Token("Order.BillingCountry", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.ShippingMethod", order.ShippingMethod)); tokens.Add(new Token("Order.ShippingFirstName", order.ShippingAddress != null ? order.ShippingAddress.FirstName : "")); tokens.Add(new Token("Order.ShippingLastName", order.ShippingAddress != null ? order.ShippingAddress.LastName : "")); tokens.Add(new Token("Order.ShippingPhoneNumber", order.ShippingAddress != null ? order.ShippingAddress.PhoneNumber : "")); tokens.Add(new Token("Order.ShippingEmail", order.ShippingAddress != null ? order.ShippingAddress.Email : "")); tokens.Add(new Token("Order.ShippingFaxNumber", order.ShippingAddress != null ? order.ShippingAddress.FaxNumber : "")); tokens.Add(new Token("Order.ShippingCompany", order.ShippingAddress != null ? order.ShippingAddress.Company : "")); tokens.Add(new Token("Order.ShippingAddress1", order.ShippingAddress != null ? order.ShippingAddress.Address1 : "")); tokens.Add(new Token("Order.ShippingAddress2", order.ShippingAddress != null ? order.ShippingAddress.Address2 : "")); tokens.Add(new Token("Order.ShippingCity", order.ShippingAddress != null ? order.ShippingAddress.City : "")); tokens.Add(new Token("Order.ShippingStateProvince", order.ShippingAddress != null && order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name) : "")); tokens.Add(new Token("Order.ShippingZipPostalCode", order.ShippingAddress != null ? order.ShippingAddress.ZipPostalCode : "")); tokens.Add(new Token("Order.ShippingCountry", order.ShippingAddress != null && order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name) : "")); var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); var paymentMethodName = paymentMethod != null?paymentMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) : order.PaymentMethodSystemName; tokens.Add(new Token("Order.PaymentMethod", paymentMethodName)); tokens.Add(new Token("Order.VatNumber", order.VatNumber)); tokens.Add(new Token("Order.Product(s)", ProductListToHtmlTable(order, languageId), true)); var language = _languageService.GetLanguageById(languageId); if (language != null && !String.IsNullOrEmpty(language.LanguageCulture)) { DateTime createdOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, TimeZoneInfo.Utc, _dateTimeHelper.GetCustomerTimeZone(order.Customer)); tokens.Add(new Token("Order.CreatedOn", createdOn.ToString("D", new CultureInfo(language.LanguageCulture)))); } else { tokens.Add(new Token("Order.CreatedOn", order.CreatedOnUtc.ToString("D"))); } //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) tokens.Add(new Token("Order.OrderURLForCustomer", string.Format("{0}orderdetails/{1}", _webHelper.GetStoreLocation(false), order.Id), true)); //event notification _eventPublisher.EntityTokensAdded(order, tokens); }
public async Task <ShipmentDetailsModel> Handle(GetShipmentDetails request, CancellationToken cancellationToken) { if (request.Shipment == null) { throw new ArgumentNullException("shipment"); } var model = new ShipmentDetailsModel(); model.Id = request.Shipment.Id; model.ShipmentNumber = request.Shipment.ShipmentNumber; if (request.Shipment.ShippedDateUtc.HasValue) { model.ShippedDate = _dateTimeHelper.ConvertToUserTime(request.Shipment.ShippedDateUtc.Value, DateTimeKind.Utc); } if (request.Shipment.DeliveryDateUtc.HasValue) { model.DeliveryDate = _dateTimeHelper.ConvertToUserTime(request.Shipment.DeliveryDateUtc.Value, DateTimeKind.Utc); } //tracking number and shipment information if (!string.IsNullOrEmpty(request.Shipment.TrackingNumber)) { model.TrackingNumber = request.Shipment.TrackingNumber; var srcm = _shippingService.LoadShippingRateComputationMethodBySystemName(request.Order.ShippingRateComputationMethodSystemName); if (srcm != null && srcm.PluginDescriptor.Installed && srcm.IsShippingRateComputationMethodActive(_shippingSettings)) { var shipmentTracker = srcm.ShipmentTracker; if (shipmentTracker != null) { model.TrackingNumberUrl = await shipmentTracker.GetUrl(request.Shipment.TrackingNumber); if (_shippingSettings.DisplayShipmentEventsToCustomers) { var shipmentEvents = await shipmentTracker.GetShipmentEvents(request.Shipment.TrackingNumber); if (shipmentEvents != null) { foreach (var shipmentEvent in shipmentEvents) { var shipmentStatusEventModel = new ShipmentDetailsModel.ShipmentStatusEventModel(); shipmentStatusEventModel.Date = shipmentEvent.Date; shipmentStatusEventModel.EventName = shipmentEvent.EventName; shipmentStatusEventModel.Location = shipmentEvent.Location; model.ShipmentStatusEvents.Add(shipmentStatusEventModel); } } } } } } //products in this shipment model.ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage; foreach (var shipmentItem in request.Shipment.ShipmentItems) { var orderItem = request.Order.OrderItems.Where(x => x.Id == shipmentItem.OrderItemId).FirstOrDefault(); if (orderItem == null) { continue; } var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId); var shipmentItemModel = new ShipmentDetailsModel.ShipmentItemModel { Id = shipmentItem.Id, Sku = product.FormatSku(orderItem.AttributesXml, _productAttributeParser), ProductId = orderItem.ProductId, ProductName = product.GetLocalized(x => x.Name, request.Language.Id), ProductSeName = product.GetSeName(request.Language.Id), AttributeInfo = orderItem.AttributeDescription, QuantityOrdered = orderItem.Quantity, QuantityShipped = shipmentItem.Quantity, }; model.Items.Add(shipmentItemModel); } //shipment notes model.ShipmentNotes = await PrepareShipmentNotesModel(request); //order details model model.Order = await PrepareOrderModel(request); return(model); }
/// <summary> /// Get order average report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="os">Order status</param> /// <returns>Result</returns> public virtual OrderAverageReportLineSummary OrderAverageReport(int storeId, OrderStatus os) { var item = new OrderAverageReportLineSummary { OrderStatus = os }; var orderStatuses = new List <int> { (int)os }; var nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); var timeZone = _dateTimeHelper.CurrentTimeZone; //today var t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime?startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); var todayResult = GetOrderAverageReportLine(storeId, osIds: orderStatuses, startTimeUtc: startTime1); item.SumTodayOrders = todayResult.SumOrders; item.CountTodayOrders = todayResult.CountOrders; //week var fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; var today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); var t2 = today.AddDays(-(today.DayOfWeek - fdow)); DateTime?startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); var weekResult = GetOrderAverageReportLine(storeId, osIds: orderStatuses, startTimeUtc: startTime2); item.SumThisWeekOrders = weekResult.SumOrders; item.CountThisWeekOrders = weekResult.CountOrders; //month var t3 = new DateTime(nowDt.Year, nowDt.Month, 1); DateTime?startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); var monthResult = GetOrderAverageReportLine(storeId, osIds: orderStatuses, startTimeUtc: startTime3); item.SumThisMonthOrders = monthResult.SumOrders; item.CountThisMonthOrders = monthResult.CountOrders; //year var t4 = new DateTime(nowDt.Year, 1, 1); DateTime?startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); var yearResult = GetOrderAverageReportLine(storeId, osIds: orderStatuses, startTimeUtc: startTime4); item.SumThisYearOrders = yearResult.SumOrders; item.CountThisYearOrders = yearResult.CountOrders; //all time var allTimeResult = GetOrderAverageReportLine(storeId, osIds: orderStatuses); item.SumAllTimeOrders = allTimeResult.SumOrders; item.CountAllTimeOrders = allTimeResult.CountOrders; return(item); }
public async Task <IActionResult> Index(int id, int?page) { var customer = await _db.Customers.FindByIdAsync(id, false); if (!_customerSettings.AllowViewingProfiles || customer == null || customer.IsGuest()) { return(NotFound()); } var name = customer.FormatUserName(_customerSettings, T, true); var model = new ProfileIndexModel { Id = customer.Id, ProfileTitle = T("Profile.ProfileOf", name), //PostsPage = page ?? 0, //PagingPosts = page.HasValue, //ForumsEnabled = _forumSettings.ForumsEnabled }; // INFO: (mh) (core) Model preparation for old Info action starts here. // TODO: (mh) (core) Make prepare model method so we dont always must refer to model.ProfileInfo... model.ProfileInfo.Id = id; model.ProfileInfo.Avatar = customer.ToAvatarModel(null, true); // Location. if (_customerSettings.ShowCustomersLocation) { model.ProfileInfo.LocationEnabled = true; var country = await _db.Countries.FindByIdAsync(customer.GenericAttributes.CountryId ?? 0); if (country != null) { model.ProfileInfo.Location = country.GetLocalized(x => x.Name); } else { model.ProfileInfo.LocationEnabled = false; } } // TODO: (mh) (core) Forum module must handle this somehow. Also ask if forum is enabled (because now PMs can be sent even if the Forum is turned off). // Private message. //model.ProfileInfo.PMEnabled = _forumSettings.AllowPrivateMessages && !customer.IsGuest(); // TODO: (mh) (core) Forum module must handle this somehow. // Total forum posts. //if (_forumSettings.ForumsEnabled && _forumSettings.ShowCustomersPostCount) //{ // model.TotalPostsEnabled = true; // model.TotalPosts = customer.GetAttribute<int>(SystemCustomerAttributeNames.ForumPostCount, _genericAttributeService); //} // Registration date. if (_customerSettings.ShowCustomersJoinDate) { model.ProfileInfo.JoinDateEnabled = true; model.ProfileInfo.JoinDate = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc).ToString("f"); } // Birth date. if (_customerSettings.DateOfBirthEnabled && customer.BirthDate.HasValue) { model.ProfileInfo.DateOfBirthEnabled = true; model.ProfileInfo.DateOfBirth = customer.BirthDate.Value.ToString("D"); } return(View(model)); }
public ActionResult Index() { var model = new List <GoogleAnaliticsStats>(); var scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(); string clientId = _googleAnliticsSettings.ClientId; string keyPassword = "******"; var todayStat = new GoogleAnaliticsStatisticModel(); var week = new GoogleAnaliticsStatisticModel(); var mounth = new GoogleAnaliticsStatisticModel(); var year = new GoogleAnaliticsStatisticModel(); var download = _downloadService.GetDownloadById(_googleAnliticsSettings.PrivateKeyId); DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone; //today DateTime t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); if (!timeZone.IsInvalidTime(t1)) { DateTime startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); todayStat = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime1, nowDt); } DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; DateTime today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow)); if (!timeZone.IsInvalidTime(t2)) { DateTime startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); week = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime2, nowDt); } DateTime t3 = new DateTime(nowDt.Year, nowDt.Month, 1); if (!timeZone.IsInvalidTime(t3)) { DateTime startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); mounth = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime3, nowDt); } DateTime t4 = new DateTime(nowDt.Year, 1, 1); if (!timeZone.IsInvalidTime(t4)) { DateTime startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); year = GetAnaliticsDataMethod(scope, clientId, keyPassword, download, startTime4, nowDt); } model.Add(new GoogleAnaliticsStats() { Name = "Visitors", Today = todayStat.Visitors, Weekly = week.Visitors, Mounthly = mounth.Visitors, Year = year.Visitors }); model.Add(new GoogleAnaliticsStats() { Name = "Unique page views", Today = todayStat.UniquePageViews, Weekly = week.UniquePageViews, Mounthly = mounth.UniquePageViews, Year = year.UniquePageViews }); model.Add(new GoogleAnaliticsStats() { Name = "Average time on site", Today = todayStat.AverageTimeOnSite, Weekly = week.AverageTimeOnSite, Mounthly = mounth.AverageTimeOnSite, Year = year.AverageTimeOnSite }); model.Add(new GoogleAnaliticsStats() { Name = "Exit rate", Today = todayStat.ExitRate, Weekly = week.ExitRate, Mounthly = mounth.ExitRate, Year = year.ExitRate }); model.Add(new GoogleAnaliticsStats() { Name = "New to old visitors rate", Today = todayStat.NewToOldVisitorsRate, Weekly = week.NewToOldVisitorsRate, Mounthly = mounth.NewToOldVisitorsRate, Year = year.NewToOldVisitorsRate }); return(View(model)); }
public virtual async Task <ShipmentModel> PrepareShipmentModel(Shipment shipment, bool prepareProducts, bool prepareShipmentEvent = false) { //measures var baseWeight = await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId); var baseWeightIn = baseWeight != null ? baseWeight.Name : ""; var baseDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId); var baseDimensionIn = baseDimension != null ? baseDimension.Name : ""; var order = await _orderService.GetOrderById(shipment.OrderId); var model = new ShipmentModel { Id = shipment.Id, ShipmentNumber = shipment.ShipmentNumber, OrderId = shipment.OrderId, OrderNumber = order != null ? order.OrderNumber : 0, OrderCode = order != null ? order.Code : "", TrackingNumber = shipment.TrackingNumber, TotalWeight = shipment.TotalWeight.HasValue ? string.Format("{0:F2} [{1}]", shipment.TotalWeight, baseWeightIn) : "", ShippedDate = shipment.ShippedDateUtc.HasValue ? _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc) : new DateTime?(), ShippedDateUtc = shipment.ShippedDateUtc, CanShip = !shipment.ShippedDateUtc.HasValue, DeliveryDate = shipment.DeliveryDateUtc.HasValue ? _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc) : new DateTime?(), DeliveryDateUtc = shipment.DeliveryDateUtc, CanDeliver = shipment.ShippedDateUtc.HasValue && !shipment.DeliveryDateUtc.HasValue, AdminComment = shipment.AdminComment, GenericAttributes = shipment.GenericAttributes }; if (prepareProducts) { foreach (var shipmentItem in shipment.ShipmentItems) { var orderItem = order.OrderItems.Where(x => x.Id == shipmentItem.OrderItemId).FirstOrDefault(); if (orderItem == null) { continue; } if (_workContext.CurrentVendor != null) { if (orderItem.VendorId != _workContext.CurrentVendor.Id) { continue; } } //quantities var qtyInThisShipment = shipmentItem.Quantity; var maxQtyToAdd = await orderItem.GetTotalNumberOfItemsCanBeAddedToShipment(_orderService, _shipmentService); var qtyOrdered = shipmentItem.Quantity; var qtyInAllShipments = await orderItem.GetTotalNumberOfItemsInAllShipment(_orderService, _shipmentService); var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId); if (product != null) { var warehouse = await _shippingService.GetWarehouseById(shipmentItem.WarehouseId); var shipmentItemModel = new ShipmentModel.ShipmentItemModel { Id = shipmentItem.Id, OrderItemId = orderItem.Id, ProductId = orderItem.ProductId, ProductName = product.Name, Sku = product.FormatSku(orderItem.AttributesXml, _productAttributeParser), AttributeInfo = orderItem.AttributeDescription, ShippedFromWarehouse = warehouse != null ? warehouse.Name : null, ShipSeparately = product.ShipSeparately, ItemWeight = orderItem.ItemWeight.HasValue ? string.Format("{0:F2} [{1}]", orderItem.ItemWeight, baseWeightIn) : "", ItemDimensions = string.Format("{0:F2} x {1:F2} x {2:F2} [{3}]", product.Length, product.Width, product.Height, baseDimensionIn), QuantityOrdered = qtyOrdered, QuantityInThisShipment = qtyInThisShipment, QuantityInAllShipments = qtyInAllShipments, QuantityToAdd = maxQtyToAdd, }; model.Items.Add(shipmentItemModel); } } } if (prepareShipmentEvent && !String.IsNullOrEmpty(shipment.TrackingNumber)) { var srcm = _shippingService.LoadShippingRateComputationMethodBySystemName(order.ShippingRateComputationMethodSystemName); if (srcm != null && srcm.PluginDescriptor.Installed && srcm.IsShippingRateComputationMethodActive(_shippingSettings)) { var shipmentTracker = srcm.ShipmentTracker; if (shipmentTracker != null) { model.TrackingNumberUrl = await shipmentTracker.GetUrl(shipment.TrackingNumber); if (_shippingSettings.DisplayShipmentEventsToStoreOwner) { var shipmentEvents = await shipmentTracker.GetShipmentEvents(shipment.TrackingNumber); if (shipmentEvents != null) { foreach (var shipmentEvent in shipmentEvents) { var shipmentStatusEventModel = new ShipmentModel.ShipmentStatusEventModel(); var shipmentEventCountry = await _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode); shipmentStatusEventModel.Country = shipmentEventCountry != null ? shipmentEventCountry.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id) : shipmentEvent.CountryCode; shipmentStatusEventModel.Date = shipmentEvent.Date; shipmentStatusEventModel.EventName = shipmentEvent.EventName; shipmentStatusEventModel.Location = shipmentEvent.Location; model.ShipmentStatusEvents.Add(shipmentStatusEventModel); } } } } } } return(model); }
public virtual ForumTopicPageModel PrepareForumTopicPage(ForumTopic forumTopic, int pageNumber) { var posts = _forumService.GetAllPosts(forumTopic.Id, "", string.Empty, pageNumber - 1, _forumSettings.PostsPageSize); //prepare model var model = new ForumTopicPageModel(); model.Id = forumTopic.Id; model.Subject = forumTopic.Subject; model.SeName = forumTopic.GetSeName(); var currentcustomer = _workContext.CurrentCustomer; model.IsCustomerAllowedToEditTopic = _forumService.IsCustomerAllowedToEditTopic(currentcustomer, forumTopic); model.IsCustomerAllowedToDeleteTopic = _forumService.IsCustomerAllowedToDeleteTopic(currentcustomer, forumTopic); model.IsCustomerAllowedToMoveTopic = _forumService.IsCustomerAllowedToMoveTopic(currentcustomer, forumTopic); model.IsCustomerAllowedToSubscribe = _forumService.IsCustomerAllowedToSubscribe(currentcustomer); if (model.IsCustomerAllowedToSubscribe) { model.WatchTopicText = _localizationService.GetResource("Forum.WatchTopic"); var forumTopicSubscription = _forumService.GetAllSubscriptions(currentcustomer.Id, "", forumTopic.Id, 0, 1).FirstOrDefault(); if (forumTopicSubscription != null) { model.WatchTopicText = _localizationService.GetResource("Forum.UnwatchTopic"); } } model.PostsPageIndex = posts.PageIndex; model.PostsPageSize = posts.PageSize; model.PostsTotalRecords = posts.TotalCount; foreach (var post in posts) { var customer = EngineContext.Current.Resolve <ICustomerService>().GetCustomerById(post.CustomerId); var forumPostModel = new ForumPostModel { Id = post.Id, ForumTopicId = post.TopicId, ForumTopicSeName = forumTopic.GetSeName(), FormattedText = post.FormatPostText(), IsCurrentCustomerAllowedToEditPost = _forumService.IsCustomerAllowedToEditPost(currentcustomer, post), IsCurrentCustomerAllowedToDeletePost = _forumService.IsCustomerAllowedToDeletePost(currentcustomer, post), CustomerId = post.CustomerId, AllowViewingProfiles = _customerSettings.AllowViewingProfiles, CustomerName = customer.FormatUserName(), IsCustomerForumModerator = customer.IsForumModerator(), IsCustomerGuest = customer.IsGuest(), ShowCustomersPostCount = _forumSettings.ShowCustomersPostCount, ForumPostCount = customer.GetAttribute <int>(SystemCustomerAttributeNames.ForumPostCount), ShowCustomersJoinDate = _customerSettings.ShowCustomersJoinDate, CustomerJoinDate = customer.CreatedOnUtc, AllowPrivateMessages = _forumSettings.AllowPrivateMessages, SignaturesEnabled = _forumSettings.SignaturesEnabled, FormattedSignature = customer.GetAttribute <string>(SystemCustomerAttributeNames.Signature).FormatForumSignatureText(), }; //created on string if (_forumSettings.RelativeDateTimeFormattingEnabled) { forumPostModel.PostCreatedOnStr = post.CreatedOnUtc.ToString("f"); } else { forumPostModel.PostCreatedOnStr = _dateTimeHelper.ConvertToUserTime(post.CreatedOnUtc, DateTimeKind.Utc).ToString("f"); } //avatar if (_customerSettings.AllowCustomersToUploadAvatars) { forumPostModel.CustomerAvatarUrl = _pictureService.GetPictureUrl( customer.GetAttribute <string>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType: PictureType.Avatar); } //location forumPostModel.ShowCustomersLocation = _customerSettings.ShowCustomersLocation; if (_customerSettings.ShowCustomersLocation) { var countryId = customer.GetAttribute <string>(SystemCustomerAttributeNames.CountryId); var country = _countryService.GetCountryById(countryId); forumPostModel.CustomerLocation = country != null?country.GetLocalized(x => x.Name) : string.Empty; } if (_forumSettings.AllowPostVoting) { forumPostModel.AllowPostVoting = true; forumPostModel.VoteCount = post.VoteCount; var postVote = _forumService.GetPostVote(post.Id, _workContext.CurrentCustomer.Id); if (postVote != null) { forumPostModel.VoteIsUp = postVote.IsUp; } } // page number is needed for creating post link in _ForumPost partial view forumPostModel.CurrentTopicPage = pageNumber; model.ForumPostModels.Add(forumPostModel); } return(model); }
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments) { if (blogPost == null) { throw new ArgumentNullException("blogPost"); } if (model == null) { throw new ArgumentNullException("model"); } model.Id = blogPost.Id; model.MetaTitle = blogPost.MetaTitle; model.MetaDescription = blogPost.MetaDescription; model.MetaKeywords = blogPost.MetaKeywords; model.SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false); model.Title = blogPost.Title; model.Body = blogPost.Body; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc); model.Tags = blogPost.ParseTags().Select(x => new BlogPostTagModel { Name = x, SeName = SeoHelper.GetSeName(x, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoNameCharConversion) }).ToList(); model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage; model.Comments.AllowComments = blogPost.AllowComments; model.Comments.AvatarPictureSize = _mediaSettings.AvatarPictureSize; model.Comments.NumberOfComments = blogPost.ApprovedCommentCount; model.Comments.AllowCustomersToUploadAvatars = _customerSettings.AllowCustomersToUploadAvatars; if (prepareComments) { var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc); foreach (var bc in blogComments) { var commentModel = new CommentModel(model.Comments) { Id = bc.Id, CustomerId = bc.CustomerId, CustomerName = bc.Customer.FormatUserName(), CommentText = bc.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc), CreatedOnPretty = bc.CreatedOnUtc.RelativeFormat(true, "f"), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && bc.Customer != null && !bc.Customer.IsGuest() }; if (_customerSettings.AllowCustomersToUploadAvatars) { var customer = bc.Customer; string avatarUrl = _pictureService.GetPictureUrl(customer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, false); if (String.IsNullOrEmpty(avatarUrl) && _customerSettings.DefaultAvatarEnabled) { avatarUrl = _pictureService.GetDefaultPictureUrl(_mediaSettings.AvatarPictureSize, PictureType.Avatar); } commentModel.CustomerAvatarUrl = avatarUrl; } model.Comments.Comments.Add(commentModel); } } Services.DisplayControl.Announce(blogPost); }
private bool PrepareReturnRequestModel(ReturnRequestModel model, ReturnRequest returnRequest, bool excludeProperties) { if (model == null) { throw new ArgumentNullException("model"); } if (returnRequest == null) { throw new ArgumentNullException("returnRequest"); } var orderItem = _orderService.GetOrderItemById(returnRequest.OrderItemId); if (orderItem == null) { return(false); } var store = _storeService.GetStoreById(returnRequest.StoreId); model.Id = returnRequest.Id; model.ProductId = orderItem.ProductId; model.ProductSku = orderItem.Product.Sku; model.ProductName = orderItem.Product.Name; model.ProductTypeName = orderItem.Product.GetProductTypeLabel(_localizationService); model.ProductTypeLabelHint = orderItem.Product.ProductTypeLabelHint; model.StoreName = (store != null ? store.Name : "".NaIfEmpty()); model.OrderId = orderItem.OrderId; model.OrderNumber = orderItem.Order.GetOrderNumber(); model.CustomerId = returnRequest.CustomerId; model.CustomerFullName = returnRequest.Customer.GetFullName().NaIfEmpty(); model.CanSendEmailToCustomer = returnRequest.Customer.FindEmail().HasValue(); model.Quantity = returnRequest.Quantity; model.ReturnRequestStatusStr = returnRequest.ReturnRequestStatus.GetLocalizedEnum(_localizationService, _workContext); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.CreatedOnUtc, DateTimeKind.Utc); model.UpdatedOn = _dateTimeHelper.ConvertToUserTime(returnRequest.UpdatedOnUtc, DateTimeKind.Utc); if (!excludeProperties) { model.ReasonForReturn = returnRequest.ReasonForReturn; model.RequestedAction = returnRequest.RequestedAction; if (returnRequest.RequestedActionUpdatedOnUtc.HasValue) { model.RequestedActionUpdated = _dateTimeHelper.ConvertToUserTime(returnRequest.RequestedActionUpdatedOnUtc.Value, DateTimeKind.Utc); } model.CustomerComments = returnRequest.CustomerComments; model.StaffNotes = returnRequest.StaffNotes; model.AdminComment = returnRequest.AdminComment; model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId; } string unspec = _localizationService.GetResource("Common.Unspecified"); model.AvailableReasonForReturn.Add(new SelectListItem() { Text = unspec, Value = "" }); model.AvailableRequestedAction.Add(new SelectListItem() { Text = unspec, Value = "" }); // that's what we also offer in frontend string returnRequestReasons = _orderSettings.GetLocalized(x => x.ReturnRequestReasons, orderItem.Order.CustomerLanguageId, true, false); string returnRequestActions = _orderSettings.GetLocalized(x => x.ReturnRequestActions, orderItem.Order.CustomerLanguageId, true, false); foreach (var rrr in returnRequestReasons.SplitSafe(",")) { model.AvailableReasonForReturn.Add(new SelectListItem() { Text = rrr, Value = rrr, Selected = (rrr == returnRequest.ReasonForReturn) }); } foreach (var rra in returnRequestActions.SplitSafe(",")) { model.AvailableRequestedAction.Add(new SelectListItem() { Text = rra, Value = rra, Selected = (rra == returnRequest.RequestedAction) }); } var urlHelper = new UrlHelper(Request.RequestContext); model.AutoUpdateOrderItem.Id = returnRequest.Id; model.AutoUpdateOrderItem.Caption = _localizationService.GetResource("Admin.ReturnRequests.Accept.Caption"); model.AutoUpdateOrderItem.PostUrl = urlHelper.Action("Accept", "ReturnRequest"); model.AutoUpdateOrderItem.ShowUpdateTotals = (orderItem.Order.OrderStatusId <= (int)OrderStatus.Pending); model.AutoUpdateOrderItem.ShowUpdateRewardPoints = (orderItem.Order.OrderStatusId > (int)OrderStatus.Pending && orderItem.Order.RewardPointsWereAdded); model.AutoUpdateOrderItem.UpdateTotals = model.AutoUpdateOrderItem.ShowUpdateTotals; model.AutoUpdateOrderItem.UpdateRewardPoints = orderItem.Order.RewardPointsWereAdded; model.ReturnRequestInfo = TempData[AutoUpdateOrderItemContext.InfoKey] as string; return(true); }
public async Task <OrderDetailsModel> Handle(GetOrderDetails request, CancellationToken cancellationToken) { var model = new OrderDetailsModel(); model.Id = request.Order.Id; model.OrderNumber = request.Order.OrderNumber; model.OrderCode = request.Order.Code; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(request.Order.CreatedOnUtc, DateTimeKind.Utc); model.OrderStatus = request.Order.OrderStatus.GetLocalizedEnum(_localizationService, request.Language.Id); model.IsReOrderAllowed = _orderSettings.IsReOrderAllowed; model.IsReturnRequestAllowed = await _mediator.Send(new IsReturnRequestAllowedQuery() { Order = request.Order }); model.PdfInvoiceDisabled = _pdfSettings.DisablePdfInvoicesForPendingOrders && request.Order.OrderStatus == OrderStatus.Pending; model.ShowAddOrderNote = _orderSettings.AllowCustomerToAddOrderNote; //shipping info await PrepareShippingInfo(request, model); //billing info model.BillingAddress = await _mediator.Send(new GetAddressModel() { Language = request.Language, Model = null, Address = request.Order.BillingAddress, ExcludeProperties = false, }); //VAT number model.VatNumber = request.Order.VatNumber; //payment method await PreparePaymentMethod(request, model); //custom values model.CustomValues = request.Order.DeserializeCustomValues(); //order subtotal await PrepareOrderTotal(request, model); //tax await PrepareTax(request, model); //discount (applied to order total) await PrepareDiscount(request, model); //gift cards await PrepareGiftCards(request, model); //reward points await PrepareRewardPoints(request, model); //checkout attributes model.CheckoutAttributeInfo = request.Order.CheckoutAttributeDescription; //order notes await PrepareOrderNotes(request, model); //allow cancel order if (_orderSettings.UserCanCancelUnpaidOrder) { if (request.Order.OrderStatus == OrderStatus.Pending && request.Order.PaymentStatus == Domain.Payments.PaymentStatus.Pending && (request.Order.ShippingStatus == ShippingStatus.ShippingNotRequired || request.Order.ShippingStatus == ShippingStatus.NotYetShipped)) { model.UserCanCancelUnpaidOrder = true; } } //purchased products await PrepareOrderItems(request, model); return(model); }
/// <summary> /// Get order average report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="os">Order status</param> /// <returns>Result</returns> public virtual OrderAverageReportLineSummary OrderAverageReport(int storeId, OrderStatus os) { var item = new OrderAverageReportLineSummary(); item.OrderStatus = os; DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone; var orderStatusId = new int[] { (int)os }; //today DateTime t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); if (!timeZone.IsInvalidTime(t1)) { DateTime?startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); DateTime?endTime1 = null; var todayResult = GetOrderAverageReportLine(storeId, orderStatusId, null, null, startTime1, endTime1, null); item.SumTodayOrders = todayResult.SumOrders; item.CountTodayOrders = todayResult.CountOrders; } //week DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; DateTime today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow)); if (!timeZone.IsInvalidTime(t2)) { DateTime?startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); DateTime?endTime2 = null; var weekResult = GetOrderAverageReportLine(storeId, orderStatusId, null, null, startTime2, endTime2, null); item.SumThisWeekOrders = weekResult.SumOrders; item.CountThisWeekOrders = weekResult.CountOrders; } //month DateTime t3 = new DateTime(nowDt.Year, nowDt.Month, 1); if (!timeZone.IsInvalidTime(t3)) { DateTime?startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); DateTime?endTime3 = null; var monthResult = GetOrderAverageReportLine(storeId, orderStatusId, null, null, startTime3, endTime3, null); item.SumThisMonthOrders = monthResult.SumOrders; item.CountThisMonthOrders = monthResult.CountOrders; } //year DateTime t4 = new DateTime(nowDt.Year, 1, 1); if (!timeZone.IsInvalidTime(t4)) { DateTime?startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); DateTime?endTime4 = null; var yearResult = GetOrderAverageReportLine(storeId, orderStatusId, null, null, startTime4, endTime4, null); item.SumThisYearOrders = yearResult.SumOrders; item.CountThisYearOrders = yearResult.CountOrders; } //all time DateTime?startTime5 = null; DateTime?endTime5 = null; var allTimeResult = GetOrderAverageReportLine(storeId, orderStatusId, null, null, startTime5, endTime5, null); item.SumAllTimeOrders = allTimeResult.SumOrders; item.CountAllTimeOrders = allTimeResult.CountOrders; return(item); }
public static ScheduleTaskModel ToScheduleTaskModel(this ScheduleTask task, ILocalizationService localization, IDateTimeHelper dateTimeHelper, UrlHelper urlHelper) { var now = DateTime.UtcNow; TimeSpan? dueIn = null; if (task.NextRunUtc.HasValue) { dueIn = task.NextRunUtc.Value - now; } var nextRunPretty = ""; bool isOverdue = false; if (dueIn.HasValue) { if (dueIn.Value.TotalSeconds > 0) { nextRunPretty = dueIn.Value.Prettify(); } else { nextRunPretty = localization.GetResource("Common.Waiting") + "..."; isOverdue = true; } } var isRunning = task.IsRunning; var lastStartOn = task.LastStartUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastStartUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var lastEndOn = task.LastEndUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastEndUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var lastSuccessOn = task.LastSuccessUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.LastSuccessUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var nextRunOn = task.NextRunUtc.HasValue ? dateTimeHelper.ConvertToUserTime(task.NextRunUtc.Value, DateTimeKind.Utc) : (DateTime?)null; var model = new ScheduleTaskModel { Id = task.Id, Name = task.Name, CronExpression = task.CronExpression, CronDescription = CronExpression.GetFriendlyDescription(task.CronExpression), Enabled = task.Enabled, StopOnError = task.StopOnError, LastStart = lastStartOn, LastStartPretty = task.LastStartUtc.HasValue ? task.LastStartUtc.Value.RelativeFormat(true, "f") : "", LastEnd = lastEndOn, LastEndPretty = lastEndOn.HasValue ? lastEndOn.Value.ToString("G") : "", LastSuccess = lastSuccessOn, LastSuccessPretty = lastSuccessOn.HasValue ? lastSuccessOn.Value.ToString("G") : "", NextRun = nextRunOn, NextRunPretty = nextRunPretty, LastError = task.LastError.EmptyNull(), IsRunning = isRunning, CancelUrl = urlHelper.Action("CancelJob", "ScheduleTask", new { id = task.Id }), ExecuteUrl = urlHelper.Action("RunJob", "ScheduleTask", new { id = task.Id }), EditUrl = urlHelper.Action("Edit", "ScheduleTask", new { id = task.Id }), ProgressPercent = task.ProgressPercent, ProgressMessage = task.ProgressMessage, IsOverdue = isOverdue, Duration = "" }; var span = TimeSpan.Zero; if (task.LastStartUtc.HasValue) { span = model.IsRunning ? now - task.LastStartUtc.Value : task.LastEndUtc.Value - task.LastStartUtc.Value; if (span > TimeSpan.Zero) { model.Duration = span.ToString("g"); } } return model; }