示例#1
0
        /// <summary>
        /// Prepare paged campaign list model
        /// </summary>
        /// <param name="searchModel">Campaign search model</param>
        /// <returns>Campaign list model</returns>
        public virtual async Task<CampaignListModel> PrepareCampaignListModelAsync(CampaignSearchModel searchModel)
        {
            if (searchModel == null)
                throw new ArgumentNullException(nameof(searchModel));

            //get campaigns
            var campaigns = (await _campaignService.GetAllCampaignsAsync(searchModel.StoreId)).ToPagedList(searchModel);

            //prepare grid model
            var model = await new CampaignListModel().PrepareToGridAsync(searchModel, campaigns, () =>
            {
                return campaigns.SelectAwait(async campaign =>
                {
                    //fill in model values from the entity
                    var campaignModel = campaign.ToModel<CampaignModel>();

                    //convert dates to the user time
                    campaignModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(campaign.CreatedOnUtc, DateTimeKind.Utc);
                    if (campaign.DontSendBeforeDateUtc.HasValue)
                    {
                        campaignModel.DontSendBeforeDate = await _dateTimeHelper
                            .ConvertToUserTimeAsync(campaign.DontSendBeforeDateUtc.Value, DateTimeKind.Utc);
                    }

                    return campaignModel;
                });
            });

            return model;
        }
示例#2
0
        /// <summary>
        /// Prepare paged forum group list model
        /// </summary>
        /// <param name="searchModel">Forum group search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the forum group list model
        /// </returns>
        public virtual async Task <ForumGroupListModel> PrepareForumGroupListModelAsync(ForumGroupSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get forum groups
            var forumGroups = (await _forumService.GetAllForumGroupsAsync()).ToPagedList(searchModel);

            //prepare list model
            var model = await new ForumGroupListModel().PrepareToGridAsync(searchModel, forumGroups, () =>
            {
                return(forumGroups.SelectAwait(async forumGroup =>
                {
                    //fill in model values from the entity
                    var forumGroupModel = forumGroup.ToModel <ForumGroupModel>();

                    //convert dates to the user time
                    forumGroupModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(forumGroup.CreatedOnUtc, DateTimeKind.Utc);

                    return forumGroupModel;
                }));
            });

            return(model);
        }
        public async Task <IActionResult> LogList(TaxTransactionLogSearchModel searchModel)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(await AccessDeniedDataTablesJson());
            }

            //prepare filter parameters
            var createdFromValue = searchModel.CreatedFrom.HasValue
                ? (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedFrom.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync())
                : null;
            var createdToValue = searchModel.CreatedTo.HasValue
                ? (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedTo.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1)
                : null;

            //get tax transaction log
            var taxtransactionLog = await _taxTransactionLogService.GetTaxTransactionLogAsync(createdFromUtc : createdFromValue, createdToUtc : createdToValue,
                                                                                              pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare grid model
            var model = await new TaxTransactionLogListModel().PrepareToGridAsync(searchModel, taxtransactionLog, () =>
            {
                return(taxtransactionLog.SelectAwait(async logItem => new TaxTransactionLogModel
                {
                    Id = logItem.Id,
                    StatusCode = logItem.StatusCode,
                    Url = logItem.Url,
                    CustomerId = logItem.CustomerId,
                    CreatedDate = await _dateTimeHelper.ConvertToUserTimeAsync(logItem.CreatedDateUtc, DateTimeKind.Utc)
                }));
            });

            return(Json(model));
        }
示例#4
0
        /// <summary>
        /// Prepare blog comment model
        /// </summary>
        /// <param name="blogComment">Blog comment entity</param>
        /// <returns>Blog comment model</returns>
        protected virtual async Task <BlogCommentModel> PrepareBlogPostCommentModelAsync(BlogComment blogComment)
        {
            if (blogComment == null)
            {
                throw new ArgumentNullException(nameof(blogComment));
            }

            var customer = await _customerService.GetCustomerByIdAsync(blogComment.CustomerId);

            var model = new BlogCommentModel
            {
                Id                   = blogComment.Id,
                CustomerId           = blogComment.CustomerId,
                CustomerName         = await _customerService.FormatUsernameAsync(customer),
                CommentText          = blogComment.CommentText,
                CreatedOn            = await _dateTimeHelper.ConvertToUserTimeAsync(blogComment.CreatedOnUtc, DateTimeKind.Utc),
                AllowViewingProfiles = _customerSettings.AllowViewingProfiles && customer != null && !await _customerService.IsGuestAsync(customer)
            };

            if (_customerSettings.AllowCustomersToUploadAvatars)
            {
                model.CustomerAvatarUrl = await _pictureService.GetPictureUrlAsync(
                    await _genericAttributeService.GetAttributeAsync <int>(customer, NopCustomerDefaults.AvatarPictureIdAttribute),
                    _mediaSettings.AvatarPictureSize, _customerSettings.DefaultAvatarEnabled, defaultPictureType : PictureType.Avatar);
            }

            return(model);
        }
        /// <summary>
        /// Prepare paged return request list model
        /// </summary>
        /// <param name="searchModel">Return request search model</param>
        /// <returns>Return request list model</returns>
        public virtual async Task <ReturnRequestListModel> PrepareReturnRequestListModelAsync(ReturnRequestSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter emails
            var startDateValue = !searchModel.StartDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.StartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var endDateValue = !searchModel.EndDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.EndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);
            var returnRequestStatus = searchModel.ReturnRequestStatusId == -1 ? null : (ReturnRequestStatus?)searchModel.ReturnRequestStatusId;

            //get return requests
            var returnRequests = await _returnRequestService.SearchReturnRequestsAsync(customNumber : searchModel.CustomNumber,
                                                                                       rs : returnRequestStatus,
                                                                                       createdFromUtc : startDateValue,
                                                                                       createdToUtc : endDateValue,
                                                                                       pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new ReturnRequestListModel().PrepareToGridAsync(searchModel, returnRequests, () =>
            {
                return(returnRequests.SelectAwait(async returnRequest =>
                {
                    //fill in model values from the entity
                    var returnRequestModel = returnRequest.ToModel <ReturnRequestModel>();

                    var customer = await _customerService.GetCustomerByIdAsync(returnRequest.CustomerId);

                    //convert dates to the user time
                    returnRequestModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(returnRequest.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    returnRequestModel.CustomerInfo = (await _customerService.IsRegisteredAsync(customer))
                        ? customer.Email
                        : await _localizationService.GetResourceAsync("Admin.Customers.Guest");
                    returnRequestModel.ReturnRequestStatusStr = await _localizationService.GetLocalizedEnumAsync(returnRequest.ReturnRequestStatus);
                    var orderItem = await _orderService.GetOrderItemByIdAsync(returnRequest.OrderItemId);
                    if (orderItem == null)
                    {
                        return returnRequestModel;
                    }

                    var order = await _orderService.GetOrderByIdAsync(orderItem.OrderId);
                    var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                    returnRequestModel.ProductId = orderItem.ProductId;
                    returnRequestModel.ProductName = product.Name;
                    returnRequestModel.OrderId = order.Id;
                    returnRequestModel.AttributeInfo = orderItem.AttributeDescription;
                    returnRequestModel.CustomOrderNumber = order.CustomOrderNumber;

                    return returnRequestModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Prepare the news item model
        /// </summary>
        /// <param name="model">News item model</param>
        /// <param name="newsItem">News item</param>
        /// <param name="prepareComments">Whether to prepare news comment models</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the news item model
        /// </returns>
        public virtual async Task <NewsItemModel> PrepareNewsItemModelAsync(NewsItemModel model, NewsItem newsItem, bool prepareComments)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (newsItem == null)
            {
                throw new ArgumentNullException(nameof(newsItem));
            }

            model.Id              = newsItem.Id;
            model.MetaTitle       = newsItem.MetaTitle;
            model.MetaDescription = newsItem.MetaDescription;
            model.MetaKeywords    = newsItem.MetaKeywords;
            model.SeName          = await _urlRecordService.GetSeNameAsync(newsItem, newsItem.LanguageId, ensureTwoPublishedLanguages : false);

            model.Title         = newsItem.Title;
            model.Short         = newsItem.Short;
            model.Full          = newsItem.Full;
            model.AllowComments = newsItem.AllowComments;

            model.PreventNotRegisteredUsersToLeaveComments =
                await _customerService.IsGuestAsync(await _workContext.GetCurrentCustomerAsync()) &&
                !_newsSettings.AllowNotRegisteredUsersToLeaveComments;

            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(newsItem.StartDateUtc ?? newsItem.CreatedOnUtc, DateTimeKind.Utc);

            model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnNewsCommentPage;

            //number of news comments
            var store = await _storeContext.GetCurrentStoreAsync();

            var storeId = _newsSettings.ShowNewsCommentsPerStore ? store.Id : 0;

            model.NumberOfComments = await _newsService.GetNewsCommentsCountAsync(newsItem, storeId, true);

            if (prepareComments)
            {
                var newsComments = await _newsService.GetAllCommentsAsync(
                    newsItemId : newsItem.Id,
                    approved : true,
                    storeId : _newsSettings.ShowNewsCommentsPerStore?store.Id : 0);

                foreach (var nc in newsComments.OrderBy(comment => comment.CreatedOnUtc))
                {
                    var commentModel = await PrepareNewsCommentModelAsync(nc);

                    model.Comments.Add(commentModel);
                }
            }

            return(model);
        }
示例#7
0
        /// <summary>
        /// Prepare blog post model
        /// </summary>
        /// <param name="model">Blog post model</param>
        /// <param name="blogPost">Blog post entity</param>
        /// <param name="prepareComments">Whether to prepare blog comments</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task PrepareBlogPostModelAsync(BlogPostModel model, BlogPost blogPost, bool prepareComments)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (blogPost == null)
            {
                throw new ArgumentNullException(nameof(blogPost));
            }

            model.Id              = blogPost.Id;
            model.MetaTitle       = blogPost.MetaTitle;
            model.MetaDescription = blogPost.MetaDescription;
            model.MetaKeywords    = blogPost.MetaKeywords;
            model.SeName          = await _urlRecordService.GetSeNameAsync(blogPost, blogPost.LanguageId, ensureTwoPublishedLanguages : false);

            model.Title         = blogPost.Title;
            model.Body          = blogPost.Body;
            model.BodyOverview  = blogPost.BodyOverview;
            model.AllowComments = blogPost.AllowComments;

            model.PreventNotRegisteredUsersToLeaveComments =
                await _customerService.IsGuestAsync(await _workContext.GetCurrentCustomerAsync()) &&
                !_blogSettings.AllowNotRegisteredUsersToLeaveComments;

            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(blogPost.StartDateUtc ?? blogPost.CreatedOnUtc, DateTimeKind.Utc);

            model.Tags = await _blogService.ParseTagsAsync(blogPost);

            model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage;

            //number of blog comments
            var store = await _storeContext.GetCurrentStoreAsync();

            var storeId = _blogSettings.ShowBlogCommentsPerStore ? store.Id : 0;

            model.NumberOfComments = await _blogService.GetBlogCommentsCountAsync(blogPost, storeId, true);

            if (prepareComments)
            {
                var blogComments = await _blogService.GetAllCommentsAsync(
                    blogPostId : blogPost.Id,
                    approved : true,
                    storeId : storeId);

                foreach (var bc in blogComments)
                {
                    var commentModel = await PrepareBlogPostCommentModelAsync(bc);

                    model.Comments.Add(commentModel);
                }
            }
        }
示例#8
0
        private async Task <IEnumerable <CronTaskModel> > GetCronTaskModelsAsync(IDictionary <int, string> cronTasks)
        {
            var result = new List <CronTaskModel>();

            foreach (var ct in cronTasks)
            {
                var scheduleTask = await _scheduleTaskService.GetTaskByIdAsync(ct.Key);

                if (scheduleTask == null)
                {
                    continue;
                }

                var scheduleTaskModel = scheduleTask.ToModel <ScheduleTaskModel>();

                //convert dates to the user time
                if (scheduleTask.LastStartUtc.HasValue)
                {
                    scheduleTaskModel.LastStartUtc = (await _dateTimeHelper
                                                      .ConvertToUserTimeAsync(scheduleTask.LastStartUtc.Value, DateTimeKind.Utc)).ToString("G");
                }

                if (scheduleTask.LastEndUtc.HasValue)
                {
                    scheduleTaskModel.LastEndUtc = (await _dateTimeHelper
                                                    .ConvertToUserTimeAsync(scheduleTask.LastEndUtc.Value, DateTimeKind.Utc)).ToString("G");
                }

                if (scheduleTask.LastSuccessUtc.HasValue)
                {
                    scheduleTaskModel.LastSuccessUtc = (await _dateTimeHelper
                                                        .ConvertToUserTimeAsync(scheduleTask.LastSuccessUtc.Value, DateTimeKind.Utc)).ToString("G");
                }

                var cronNextOccurence = _cronTaskService.GetQuartzJobNextOccurrence(scheduleTask.Id);

                var model = new CronTaskModel()
                {
                    ScheduleTaskId     = scheduleTask.Id,
                    ScheduleTaskModel  = scheduleTaskModel,
                    CronExpression     = ct.Value,
                    ExecutionStatus    = _cronTaskService.GetQuartzJobExecutionStatus(scheduleTask.Id),
                    CronNextOccurrence = cronNextOccurence.HasValue ?
                                         (await _dateTimeHelper.ConvertToUserTimeAsync(cronNextOccurence.Value, DateTimeKind.Utc)).ToString("G") :
                                         string.Empty
                };

                result.Add(model);
            }

            return(result);
        }
示例#9
0
        /// <summary>
        /// Prepare the customer order list model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the customer order list model
        /// </returns>
        public virtual async Task <CustomerOrderListModel> PrepareCustomerOrderListModelAsync()
        {
            var model  = new CustomerOrderListModel();
            var orders = await _orderService.SearchOrdersAsync(storeId : (await _storeContext.GetCurrentStoreAsync()).Id,
                                                               customerId : (await _workContext.GetCurrentCustomerAsync()).Id);

            foreach (var order in orders)
            {
                var orderModel = new CustomerOrderListModel.OrderDetailsModel
                {
                    Id                     = order.Id,
                    CreatedOn              = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc),
                    OrderStatusEnum        = order.OrderStatus,
                    OrderStatus            = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus),
                    PaymentStatus          = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus),
                    ShippingStatus         = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus),
                    IsReturnRequestAllowed = await _orderProcessingService.IsReturnRequestAllowedAsync(order),
                    CustomOrderNumber      = order.CustomOrderNumber
                };
                var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);
                orderModel.OrderTotal = await _priceFormatter.FormatPriceAsync(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, (await _workContext.GetWorkingLanguageAsync()).Id);

                model.Orders.Add(orderModel);
            }

            var recurringPayments = await _orderService.SearchRecurringPaymentsAsync((await _storeContext.GetCurrentStoreAsync()).Id,
                                                                                     (await _workContext.GetCurrentCustomerAsync()).Id);

            foreach (var recurringPayment in recurringPayments)
            {
                var order = await _orderService.GetOrderByIdAsync(recurringPayment.InitialOrderId);

                var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel
                {
                    Id                  = recurringPayment.Id,
                    StartDate           = (await _dateTimeHelper.ConvertToUserTimeAsync(recurringPayment.StartDateUtc, DateTimeKind.Utc)).ToString(),
                    CycleInfo           = $"{recurringPayment.CycleLength} {await _localizationService.GetLocalizedEnumAsync(recurringPayment.CyclePeriod)}",
                    NextPayment         = await _orderProcessingService.GetNextPaymentDateAsync(recurringPayment) is DateTime nextPaymentDate ? (await _dateTimeHelper.ConvertToUserTimeAsync(nextPaymentDate, DateTimeKind.Utc)).ToString() : "",
                    TotalCycles         = recurringPayment.TotalCycles,
                    CyclesRemaining     = await _orderProcessingService.GetCyclesRemainingAsync(recurringPayment),
                    InitialOrderId      = order.Id,
                    InitialOrderNumber  = order.CustomOrderNumber,
                    CanCancel           = await _orderProcessingService.CanCancelRecurringPaymentAsync(await _workContext.GetCurrentCustomerAsync(), recurringPayment),
                    CanRetryLastPayment = await _orderProcessingService.CanRetryLastRecurringPaymentAsync(await _workContext.GetCurrentCustomerAsync(), recurringPayment)
                };

                model.RecurringOrders.Add(recurringPaymentModel);
            }

            return(model);
        }
        /// <summary>
        /// Prepare the private message model
        /// </summary>
        /// <param name="pm">Private message</param>
        /// <returns>Private message model</returns>
        public virtual async Task <PrivateMessageModel> PreparePrivateMessageModelAsync(PrivateMessage pm)
        {
            if (pm == null)
            {
                throw new ArgumentNullException(nameof(pm));
            }

            var fromCustomer = await _customerService.GetCustomerByIdAsync(pm.FromCustomerId);

            var toCustomer = await _customerService.GetCustomerByIdAsync(pm.ToCustomerId);

            var model = new PrivateMessageModel
            {
                Id                      = pm.Id,
                FromCustomerId          = pm.FromCustomerId,
                CustomerFromName        = await _customerService.FormatUsernameAsync(fromCustomer),
                AllowViewingFromProfile = _customerSettings.AllowViewingProfiles && !await _customerService.IsGuestAsync(fromCustomer),
                ToCustomerId            = pm.ToCustomerId,
                CustomerToName          = await _customerService.FormatUsernameAsync(toCustomer),
                AllowViewingToProfile   = _customerSettings.AllowViewingProfiles && !await _customerService.IsGuestAsync(toCustomer),
                Subject                 = pm.Subject,
                Message                 = _forumService.FormatPrivateMessageText(pm),
                CreatedOn               = await _dateTimeHelper.ConvertToUserTimeAsync(pm.CreatedOnUtc, DateTimeKind.Utc),
                IsRead                  = pm.IsRead,
            };

            return(model);
        }
        /// <summary>
        /// Prepare paged shopping cart item list model
        /// </summary>
        /// <param name="searchModel">Shopping cart item search model</param>
        /// <param name="customer">Customer</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the shopping cart item list model
        /// </returns>
        public virtual async Task <ShoppingCartItemListModel> PrepareShoppingCartItemListModelAsync(ShoppingCartItemSearchModel searchModel, Customer customer)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //get shopping cart items
            var items = (await _shoppingCartService.GetShoppingCartAsync(customer, searchModel.ShoppingCartType,
                                                                         searchModel.StoreId, searchModel.ProductId, searchModel.StartDate, searchModel.EndDate)).ToPagedList(searchModel);

            var isSearchProduct = searchModel.ProductId > 0;

            Product product = null;

            if (isSearchProduct)
            {
                product = await _productService.GetProductByIdAsync(searchModel.ProductId) ?? throw new Exception("Product is not found");
            }

            //prepare list model
            var model = await new ShoppingCartItemListModel().PrepareToGridAsync(searchModel, items, () =>
            {
                return(items
                       .OrderByDescending(item => item.CreatedOnUtc)
                       .SelectAwait(async item =>
                {
                    //fill in model values from the entity
                    var itemModel = item.ToModel <ShoppingCartItemModel>();

                    if (!isSearchProduct)
                    {
                        product = await _productService.GetProductByIdAsync(item.ProductId);
                    }

                    //convert dates to the user time
                    itemModel.UpdatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(item.UpdatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    itemModel.Store = (await _storeService.GetStoreByIdAsync(item.StoreId))?.Name ?? "Deleted";
                    itemModel.AttributeInfo = await _productAttributeFormatter.FormatAttributesAsync(product, item.AttributesXml, customer);
                    var(unitPrice, _, _) = await _shoppingCartService.GetUnitPriceAsync(item, true);
                    itemModel.UnitPrice = await _priceFormatter.FormatPriceAsync((await _taxService.GetProductPriceAsync(product, unitPrice)).price);
                    var(subTotal, _, _, _) = await _shoppingCartService.GetSubTotalAsync(item, true);
                    itemModel.Total = await _priceFormatter.FormatPriceAsync((await _taxService.GetProductPriceAsync(product, subTotal)).price);

                    //set product name since it does not survive mapping
                    itemModel.ProductName = product.Name;

                    return itemModel;
                }));
            });

            return(model);
        }
示例#12
0
        /// <summary>
        /// Prepare paged news item list model
        /// </summary>
        /// <param name="searchModel">News item search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the news item list model
        /// </returns>
        public virtual async Task <NewsItemListModel> PrepareNewsItemListModelAsync(NewsItemSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get news items
            var newsItems = await _newsService.GetAllNewsAsync(showHidden : true,
                                                               storeId : searchModel.SearchStoreId,
                                                               pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize,
                                                               title : searchModel.SearchTitle);

            //prepare list model
            var model = await new NewsItemListModel().PrepareToGridAsync(searchModel, newsItems, () =>
            {
                return(newsItems.SelectAwait(async newsItem =>
                {
                    //fill in model values from the entity
                    var newsItemModel = newsItem.ToModel <NewsItemModel>();

                    //little performance optimization: ensure that "Full" is not returned
                    newsItemModel.Full = string.Empty;

                    //convert dates to the user time
                    if (newsItem.StartDateUtc.HasValue)
                    {
                        newsItemModel.StartDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(newsItem.StartDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (newsItem.EndDateUtc.HasValue)
                    {
                        newsItemModel.EndDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(newsItem.EndDateUtc.Value, DateTimeKind.Utc);
                    }
                    newsItemModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(newsItem.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    newsItemModel.SeName = await _urlRecordService.GetSeNameAsync(newsItem, newsItem.LanguageId, true, false);
                    newsItemModel.LanguageName = (await _languageService.GetLanguageByIdAsync(newsItem.LanguageId))?.Name;
                    newsItemModel.ApprovedComments = await _newsService.GetNewsCommentsCountAsync(newsItem, isApproved: true);
                    newsItemModel.NotApprovedComments = await _newsService.GetNewsCommentsCountAsync(newsItem, isApproved: false);

                    return newsItemModel;
                }));
            });

            return(model);
        }
示例#13
0
        /// <summary>
        /// Prepare paged affiliated order list model
        /// </summary>
        /// <param name="searchModel">Affiliated order search model</param>
        /// <param name="affiliate">Affiliate</param>
        /// <returns>Affiliated order list model</returns>
        public virtual async Task <AffiliatedOrderListModel> PrepareAffiliatedOrderListModelAsync(AffiliatedOrderSearchModel searchModel, Affiliate affiliate)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (affiliate == null)
            {
                throw new ArgumentNullException(nameof(affiliate));
            }

            //get parameters to filter orders
            var startDateValue = !searchModel.StartDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.StartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var endDateValue = !searchModel.EndDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.EndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);
            var orderStatusIds = searchModel.OrderStatusId > 0 ? new List <int> {
                searchModel.OrderStatusId
            } : null;
            var paymentStatusIds = searchModel.PaymentStatusId > 0 ? new List <int> {
                searchModel.PaymentStatusId
            } : null;
            var shippingStatusIds = searchModel.ShippingStatusId > 0 ? new List <int> {
                searchModel.ShippingStatusId
            } : null;

            //get orders
            var orders = await _orderService.SearchOrdersAsync(createdFromUtc : startDateValue,
                                                               createdToUtc : endDateValue,
                                                               osIds : orderStatusIds,
                                                               psIds : paymentStatusIds,
                                                               ssIds : shippingStatusIds,
                                                               affiliateId : affiliate.Id,
                                                               pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new AffiliatedOrderListModel().PrepareToGridAsync(searchModel, orders, () =>
            {
                //fill in model values from the entity
                return(orders.SelectAwait(async order =>
                {
                    var affiliatedOrderModel = order.ToModel <AffiliatedOrderModel>();

                    //fill in additional values (not existing in the entity)
                    affiliatedOrderModel.OrderStatus = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus);
                    affiliatedOrderModel.PaymentStatus = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus);
                    affiliatedOrderModel.ShippingStatus = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus);
                    affiliatedOrderModel.OrderTotal = await _priceFormatter.FormatPriceAsync(order.OrderTotal, true, false);

                    affiliatedOrderModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc);

                    return affiliatedOrderModel;
                }));
            });

            return(model);
        }
示例#14
0
        /// <summary>
        /// Prepare paged log list model
        /// </summary>
        /// <param name="searchModel">Log search model</param>
        /// <returns>Log list model</returns>
        public virtual async Task <LogListModel> PrepareLogListModelAsync(LogSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter log
            var createdOnFromValue = searchModel.CreatedOnFrom.HasValue
                ? (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnFrom.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()) : null;
            var createdToFromValue = searchModel.CreatedOnTo.HasValue
                ? (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnTo.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1) : null;
            var logLevel = searchModel.LogLevelId > 0 ? (LogLevel?)searchModel.LogLevelId : null;

            //get log
            var logItems = await _logger.GetAllLogsAsync(message : searchModel.Message,
                                                         fromUtc : createdOnFromValue,
                                                         toUtc : createdToFromValue,
                                                         logLevel : logLevel,
                                                         pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new LogListModel().PrepareToGridAsync(searchModel, logItems, () =>
            {
                //fill in model values from the entity
                return(logItems.SelectAwait(async logItem =>
                {
                    //fill in model values from the entity
                    var logModel = logItem.ToModel <LogModel>();

                    //convert dates to the user time
                    logModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(logItem.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    logModel.LogLevel = await _localizationService.GetLocalizedEnumAsync(logItem.LogLevel);
                    logModel.ShortMessage = HtmlHelper.FormatText(logItem.ShortMessage, false, true, false, false, false, false);
                    logModel.FullMessage = string.Empty;
                    logModel.CustomerEmail = (await _customerService.GetCustomerByIdAsync(logItem.CustomerId ?? 0))?.Email ?? string.Empty;

                    return logModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Prepare paged recurring payment list model
        /// </summary>
        /// <param name="searchModel">Recurring payment search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the recurring payment list model
        /// </returns>
        public virtual async Task <RecurringPaymentListModel> PrepareRecurringPaymentListModelAsync(RecurringPaymentSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get recurringPayments
            var recurringPayments = await _orderService.SearchRecurringPaymentsAsync(showHidden : true,
                                                                                     pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new RecurringPaymentListModel().PrepareToGridAsync(searchModel, recurringPayments, () =>
            {
                return(recurringPayments.SelectAwait(async recurringPayment =>
                {
                    //fill in model values from the entity
                    var recurringPaymentModel = recurringPayment.ToModel <RecurringPaymentModel>();

                    var order = await _orderService.GetOrderByIdAsync(recurringPayment.InitialOrderId);
                    var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);

                    //convert dates to the user time
                    if ((await _orderProcessingService.GetNextPaymentDateAsync(recurringPayment)) is DateTime nextPaymentDate)
                    {
                        recurringPaymentModel.NextPaymentDate = (await _dateTimeHelper
                                                                 .ConvertToUserTimeAsync(nextPaymentDate, DateTimeKind.Utc)).ToString(CultureInfo.InvariantCulture);
                        recurringPaymentModel.CyclesRemaining = await _orderProcessingService.GetCyclesRemainingAsync(recurringPayment);
                    }

                    recurringPaymentModel.StartDate = (await _dateTimeHelper
                                                       .ConvertToUserTimeAsync(recurringPayment.StartDateUtc, DateTimeKind.Utc)).ToString(CultureInfo.InvariantCulture);

                    //fill in additional values (not existing in the entity)
                    recurringPaymentModel.CustomerId = customer.Id;
                    recurringPaymentModel.InitialOrderId = order.Id;

                    recurringPaymentModel.CyclePeriodStr = await _localizationService.GetLocalizedEnumAsync(recurringPayment.CyclePeriod);
                    recurringPaymentModel.CustomerEmail = (await _customerService.IsRegisteredAsync(customer))
                        ? customer.Email
                        : await _localizationService.GetResourceAsync("Admin.Customers.Guest");

                    return recurringPaymentModel;
                }));
            });
示例#16
0
        /// <summary>
        /// Prepare paged blog post list model
        /// </summary>
        /// <param name="searchModel">Blog post search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the blog post list model
        /// </returns>
        public virtual async Task <BlogPostListModel> PrepareBlogPostListModelAsync(BlogPostSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get blog posts
            var blogPosts = await _blogService.GetAllBlogPostsAsync(storeId : searchModel.SearchStoreId, showHidden : true,
                                                                    pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize, title : searchModel.SearchTitle);

            //prepare list model
            var model = await new BlogPostListModel().PrepareToGridAsync(searchModel, blogPosts, () =>
            {
                return(blogPosts.SelectAwait(async blogPost =>
                {
                    //fill in model values from the entity
                    var blogPostModel = blogPost.ToModel <BlogPostModel>();

                    //little performance optimization: ensure that "Body" is not returned
                    blogPostModel.Body = string.Empty;

                    //convert dates to the user time
                    if (blogPost.StartDateUtc.HasValue)
                    {
                        blogPostModel.StartDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(blogPost.StartDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (blogPost.EndDateUtc.HasValue)
                    {
                        blogPostModel.EndDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(blogPost.EndDateUtc.Value, DateTimeKind.Utc);
                    }
                    blogPostModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(blogPost.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    blogPostModel.LanguageName = (await _languageService.GetLanguageByIdAsync(blogPost.LanguageId))?.Name;
                    blogPostModel.ApprovedComments = await _blogService.GetBlogCommentsCountAsync(blogPost, isApproved: true);
                    blogPostModel.NotApprovedComments = await _blogService.GetBlogCommentsCountAsync(blogPost, isApproved: false);
                    blogPostModel.SeName = await _urlRecordService.GetSeNameAsync(blogPost, blogPost.LanguageId, true, false);

                    return blogPostModel;
                }));
            });

            return(model);
        }
示例#17
0
        /// <summary>
        /// Prepare paged schedule task list model
        /// </summary>
        /// <param name="searchModel">Schedule task search model</param>
        /// <returns>Schedule task list model</returns>
        public virtual async Task <ScheduleTaskListModel> PrepareScheduleTaskListModelAsync(ScheduleTaskSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get schedule tasks
            var scheduleTasks = (await _scheduleTaskService.GetAllTasksAsync(true)).ToPagedList(searchModel);

            //prepare list model
            var model = await new ScheduleTaskListModel().PrepareToGridAsync(searchModel, scheduleTasks, () =>
            {
                return(scheduleTasks.SelectAwait(async scheduleTask =>
                {
                    //fill in model values from the entity
                    var scheduleTaskModel = scheduleTask.ToModel <ScheduleTaskModel>();

                    //convert dates to the user time
                    if (scheduleTask.LastStartUtc.HasValue)
                    {
                        scheduleTaskModel.LastStartUtc = (await _dateTimeHelper
                                                          .ConvertToUserTimeAsync(scheduleTask.LastStartUtc.Value, DateTimeKind.Utc)).ToString("G");
                    }

                    if (scheduleTask.LastEndUtc.HasValue)
                    {
                        scheduleTaskModel.LastEndUtc = (await _dateTimeHelper
                                                        .ConvertToUserTimeAsync(scheduleTask.LastEndUtc.Value, DateTimeKind.Utc)).ToString("G");
                    }

                    if (scheduleTask.LastSuccessUtc.HasValue)
                    {
                        scheduleTaskModel.LastSuccessUtc = (await _dateTimeHelper
                                                            .ConvertToUserTimeAsync(scheduleTask.LastSuccessUtc.Value, DateTimeKind.Utc)).ToString("G");
                    }

                    return scheduleTaskModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Prepare paged product review list model
        /// </summary>
        /// <param name="searchModel">Product review search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the product review list model
        /// </returns>
        public virtual async Task <ProductReviewListModel> PrepareProductReviewListModelAsync(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, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var createdToFromValue = !searchModel.CreatedOnTo.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnTo.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);
            var isApprovedOnly = searchModel.SearchApprovedId == 0 ? null : searchModel.SearchApprovedId == 1 ? true : (bool?)false;
            var vendor         = await _workContext.GetCurrentVendorAsync();

            var vendorId = vendor?.Id ?? 0;

            //get product reviews
            var productReviews = await _productService.GetAllProductReviewsAsync(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 = await new ProductReviewListModel().PrepareToGridAsync(searchModel, productReviews, () =>
            {
                return(productReviews.SelectAwait(async productReview =>
                {
                    //fill in model values from the entity
                    var productReviewModel = productReview.ToModel <ProductReviewModel>();

                    //convert dates to the user time
                    productReviewModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(productReview.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    productReviewModel.StoreName = (await _storeService.GetStoreByIdAsync(productReview.StoreId))?.Name;
                    productReviewModel.ProductName = (await _productService.GetProductByIdAsync(productReview.ProductId))?.Name;
                    productReviewModel.CustomerInfo = (await _customerService.GetCustomerByIdAsync(productReview.CustomerId)) is Customer customer && (await _customerService.IsRegisteredAsync(customer))
                        ? customer.Email
                        : await _localizationService.GetResourceAsync("Admin.Customers.Guest");

                    productReviewModel.ReviewText = _htmlFormatter.FormatText(productReview.ReviewText, false, true, false, false, false, false);
                    productReviewModel.ReplyText = _htmlFormatter.FormatText(productReview.ReplyText, false, true, false, false, false, false);

                    return productReviewModel;
                }));
            });
示例#19
0
        /// <summary>
        /// Prepare paged queued email list model
        /// </summary>
        /// <param name="searchModel">Queued email search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the queued email list model
        /// </returns>
        public virtual async Task <QueuedEmailListModel> PrepareQueuedEmailListModelAsync(QueuedEmailSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter emails
            var startDateValue = !searchModel.SearchStartDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.SearchStartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var endDateValue = !searchModel.SearchEndDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.SearchEndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);

            //get queued emails
            var queuedEmails = await _queuedEmailService.SearchEmailsAsync(fromEmail : searchModel.SearchFromEmail,
                                                                           toEmail : searchModel.SearchToEmail,
                                                                           createdFromUtc : startDateValue,
                                                                           createdToUtc : endDateValue,
                                                                           loadNotSentItemsOnly : searchModel.SearchLoadNotSent,
                                                                           loadOnlyItemsToBeSent : false,
                                                                           maxSendTries : searchModel.SearchMaxSentTries,
                                                                           loadNewest : true,
                                                                           pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new QueuedEmailListModel().PrepareToGridAsync(searchModel, queuedEmails, () =>
            {
                return(queuedEmails.SelectAwait(async queuedEmail =>
                {
                    //fill in model values from the entity
                    var queuedEmailModel = queuedEmail.ToModel <QueuedEmailModel>();

                    //little performance optimization: ensure that "Body" is not returned
                    queuedEmailModel.Body = string.Empty;

                    //convert dates to the user time
                    queuedEmailModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(queuedEmail.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    var emailAccount = await _emailAccountService.GetEmailAccountByIdAsync(queuedEmail.EmailAccountId);
                    queuedEmailModel.EmailAccountName = GetEmailAccountName(emailAccount);
                    queuedEmailModel.PriorityName = await _localizationService.GetLocalizedEnumAsync(queuedEmail.Priority);

                    if (queuedEmail.DontSendBeforeDateUtc.HasValue)
                    {
                        queuedEmailModel.DontSendBeforeDate = await _dateTimeHelper
                                                              .ConvertToUserTimeAsync(queuedEmail.DontSendBeforeDateUtc.Value, DateTimeKind.Utc);
                    }

                    if (queuedEmail.SentOnUtc.HasValue)
                    {
                        queuedEmailModel.SentOn = await _dateTimeHelper.ConvertToUserTimeAsync(queuedEmail.SentOnUtc.Value, DateTimeKind.Utc);
                    }

                    return queuedEmailModel;
                }));
            });

            return(model);
        }
        public virtual async Task <IActionResult> Edit(GiftCardModel model, bool continueEditing)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageGiftCards))
            {
                return(AccessDeniedView());
            }

            //try to get a gift card with the specified id
            var giftCard = await _giftCardService.GetGiftCardByIdAsync(model.Id);

            if (giftCard == null)
            {
                return(RedirectToAction("List"));
            }

            var order = await _orderService.GetOrderByOrderItemAsync(giftCard.PurchasedWithOrderItemId ?? 0);

            model.PurchasedWithOrderId = order?.Id;
            model.RemainingAmountStr   = await _priceFormatter.FormatPriceAsync(await _giftCardService.GetGiftCardRemainingAmountAsync(giftCard), true, false);

            model.AmountStr = await _priceFormatter.FormatPriceAsync(giftCard.Amount, true, false);

            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(giftCard.CreatedOnUtc, DateTimeKind.Utc);

            model.PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode;
            model.PurchasedWithOrderNumber = order?.CustomOrderNumber;

            if (ModelState.IsValid)
            {
                giftCard = model.ToEntity(giftCard);
                await _giftCardService.UpdateGiftCardAsync(giftCard);

                //activity log
                await _customerActivityService.InsertActivityAsync("EditGiftCard",
                                                                   string.Format(await _localizationService.GetResourceAsync("ActivityLog.EditGiftCard"), giftCard.GiftCardCouponCode), giftCard);

                _notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.GiftCards.Updated"));

                if (!continueEditing)
                {
                    return(RedirectToAction("List"));
                }

                return(RedirectToAction("Edit", new { id = giftCard.Id }));
            }

            //prepare model
            model = await _giftCardModelFactory.PrepareGiftCardModelAsync(model, giftCard, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
示例#21
0
        public async Task <IActionResult> BatchList(BatchSearchModel searchModel)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageOrders))
            {
                return(await AccessDeniedDataTablesJson());
            }

            var status  = searchModel.StatusId > 0 ? (BatchStatus?)searchModel.StatusId : null;
            var batches = (await _easyPostService.GetAllBatchesAsync(status: status)).ToPagedList(searchModel);
            var model   = await new BatchListModel().PrepareToGridAsync(searchModel, batches, () => batches.SelectAwait(async batch =>
            {
                return(new BatchModel
                {
                    Id = batch.Id,
                    Status = CommonHelper.ConvertEnum(((BatchStatus)batch.StatusId).ToString()),
                    UpdatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(batch.UpdatedOnUtc, DateTimeKind.Utc),
                    CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(batch.CreatedOnUtc, DateTimeKind.Utc)
                });
            }));

            return(Json(model));
        }
示例#22
0
        /// <summary>
        /// Prepare paged poll list model
        /// </summary>
        /// <param name="searchModel">Poll search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the poll list model
        /// </returns>
        public virtual async Task <PollListModel> PreparePollListModelAsync(PollSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get polls
            var polls = await _pollService.GetPollsAsync(showHidden : true,
                                                         storeId : searchModel.SearchStoreId,
                                                         pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new PollListModel().PrepareToGridAsync(searchModel, polls, () =>
            {
                return(polls.SelectAwait(async poll =>
                {
                    //fill in model values from the entity
                    var pollModel = poll.ToModel <PollModel>();

                    //convert dates to the user time
                    if (poll.StartDateUtc.HasValue)
                    {
                        pollModel.StartDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(poll.StartDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (poll.EndDateUtc.HasValue)
                    {
                        pollModel.EndDateUtc = await _dateTimeHelper.ConvertToUserTimeAsync(poll.EndDateUtc.Value, DateTimeKind.Utc);
                    }

                    //fill in additional values (not existing in the entity)
                    pollModel.LanguageName = (await _languageService.GetLanguageByIdAsync(poll.LanguageId))?.Name;

                    return pollModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Prepare paged gift card list model
        /// </summary>
        /// <param name="searchModel">Gift card search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the gift card list model
        /// </returns>
        public virtual async Task <GiftCardListModel> PrepareGiftCardListModelAsync(GiftCardSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter gift cards
            var isActivatedOnly = searchModel.ActivatedId == 0 ? null : searchModel.ActivatedId == 1 ? true : (bool?)false;

            //get gift cards
            var giftCards = await _giftCardService.GetAllGiftCardsAsync(isGiftCardActivated : isActivatedOnly,
                                                                        giftCardCouponCode : searchModel.CouponCode,
                                                                        recipientName : searchModel.RecipientName,
                                                                        pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new GiftCardListModel().PrepareToGridAsync(searchModel, giftCards, () =>
            {
                return(giftCards.SelectAwait(async giftCard =>
                {
                    //fill in model values from the entity
                    var giftCardModel = giftCard.ToModel <GiftCardModel>();

                    //convert dates to the user time
                    giftCardModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(giftCard.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    var giftAmount = await _giftCardService.GetGiftCardRemainingAmountAsync(giftCard);
                    giftCardModel.RemainingAmountStr = await _priceFormatter.FormatPriceAsync(giftAmount, true, false);
                    giftCardModel.AmountStr = await _priceFormatter.FormatPriceAsync(giftCard.Amount, true, false);

                    return giftCardModel;
                }));
            });

            return(model);
        }
示例#24
0
        /// <summary>
        /// Update reward points balance if necessary
        /// </summary>
        /// <param name="query">Input query</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        protected virtual async Task UpdateRewardPointsBalanceAsync(IQueryable <RewardPointsHistory> query)
        {
            //get expired points
            var nowUtc        = DateTime.UtcNow;
            var expiredPoints = query
                                .Where(historyEntry => historyEntry.EndDateUtc < nowUtc && historyEntry.ValidPoints > 0)
                                .OrderBy(historyEntry => historyEntry.CreatedOnUtc).ThenBy(historyEntry => historyEntry.Id).ToList();

            //reduce the balance for these points
            foreach (var historyEntry in expiredPoints)
            {
                await InsertRewardPointsHistoryEntryAsync(new RewardPointsHistory
                {
                    CustomerId = historyEntry.CustomerId,
                    StoreId    = historyEntry.StoreId,
                    Points     = -historyEntry.ValidPoints.Value,
                    Message    = string.Format(await _localizationService.GetResourceAsync("RewardPoints.Expired"),
                                               await _dateTimeHelper.ConvertToUserTimeAsync(historyEntry.CreatedOnUtc, DateTimeKind.Utc)),
                    CreatedOnUtc = historyEntry.EndDateUtc.Value
                });

                historyEntry.ValidPoints = 0;
                await UpdateRewardPointsHistoryEntryAsync(historyEntry);
            }

            //get has not yet activated points, but it's time to do it
            var notActivatedPoints = query
                                     .Where(historyEntry => !historyEntry.PointsBalance.HasValue && historyEntry.CreatedOnUtc < nowUtc)
                                     .OrderBy(historyEntry => historyEntry.CreatedOnUtc).ThenBy(historyEntry => historyEntry.Id).ToList();

            if (!notActivatedPoints.Any())
            {
                return;
            }

            //get current points balance
            //LINQ to entities does not support Last method, thus order by desc and use First one
            var currentPointsBalance = query
                                       .OrderByDescending(historyEntry => historyEntry.CreatedOnUtc).ThenByDescending(historyEntry => historyEntry.Id)
                                       .FirstOrDefault(historyEntry => historyEntry.PointsBalance.HasValue)
                                       ?.PointsBalance ?? 0;

            //update appropriate records
            foreach (var historyEntry in notActivatedPoints)
            {
                currentPointsBalance      += historyEntry.Points;
                historyEntry.PointsBalance = currentPointsBalance;
                await UpdateRewardPointsHistoryEntryAsync(historyEntry);
            }
        }
示例#25
0
        /// <summary>
        /// Prepare return request model
        /// </summary>
        /// <param name="model">Return request model</param>
        /// <param name="returnRequest">Return request</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the return request model
        /// </returns>
        public virtual async Task <ReturnRequestModel> PrepareReturnRequestModelAsync(ReturnRequestModel model,
                                                                                      ReturnRequest returnRequest, bool excludeProperties = false)
        {
            if (returnRequest == null)
            {
                return(model);
            }

            //fill in model values from the entity
            model ??= returnRequest.ToModel <ReturnRequestModel>();

            var customer = await _customerService.GetCustomerByIdAsync(returnRequest.CustomerId);

            model.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(returnRequest.CreatedOnUtc, DateTimeKind.Utc);

            model.CustomerInfo = await _customerService.IsRegisteredAsync(customer)
                ? customer.Email : await _localizationService.GetResourceAsync("Admin.Customers.Guest");

            model.UploadedFileGuid       = (await _downloadService.GetDownloadByIdAsync(returnRequest.UploadedFileId))?.DownloadGuid ?? Guid.Empty;
            model.ReturnRequestStatusStr = await _localizationService.GetLocalizedEnumAsync(returnRequest.ReturnRequestStatus);

            var orderItem = await _orderService.GetOrderItemByIdAsync(returnRequest.OrderItemId);

            if (orderItem != null)
            {
                var order = await _orderService.GetOrderByIdAsync(orderItem.OrderId);

                var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                model.ProductId         = product.Id;
                model.ProductName       = product.Name;
                model.OrderId           = order.Id;
                model.AttributeInfo     = orderItem.AttributeDescription;
                model.CustomOrderNumber = order.CustomOrderNumber;
            }

            if (excludeProperties)
            {
                return(model);
            }

            model.ReasonForReturn       = returnRequest.ReasonForReturn;
            model.RequestedAction       = returnRequest.RequestedAction;
            model.CustomerComments      = returnRequest.CustomerComments;
            model.StaffNotes            = returnRequest.StaffNotes;
            model.ReturnRequestStatusId = returnRequest.ReturnRequestStatusId;

            return(model);
        }
示例#26
0
        /// <summary>
        /// Gets a report of customers registered in the last days
        /// </summary>
        /// <param name="days">Customers registered in the last days</param>
        /// <returns>Number of registered customers</returns>
        public virtual async Task <int> GetRegisteredCustomersReportAsync(int days)
        {
            var date = (await _dateTimeHelper.ConvertToUserTimeAsync(DateTime.Now)).AddDays(-days);

            var registeredCustomerRole = await _customerService.GetCustomerRoleBySystemNameAsync(NopCustomerDefaults.RegisteredRoleName);

            if (registeredCustomerRole == null)
            {
                return(0);
            }

            return((await _customerService.GetAllCustomersAsync(
                        date,
                        customerRoleIds: new[] { registeredCustomerRole.Id })).Count);
        }
示例#27
0
        /// <summary>
        /// Prepare paged activity log list model
        /// </summary>
        /// <param name="searchModel">Activity log search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the activity log list model
        /// </returns>
        public virtual async Task <ActivityLogListModel> PrepareActivityLogListModelAsync(ActivityLogSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter log
            var startDateValue = searchModel.CreatedOnFrom == null ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnFrom.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var endDateValue = searchModel.CreatedOnTo == null ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.CreatedOnTo.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);

            //get log
            var activityLog = await _customerActivityService.GetAllActivitiesAsync(createdOnFrom : startDateValue,
                                                                                   createdOnTo : endDateValue,
                                                                                   activityLogTypeId : searchModel.ActivityLogTypeId,
                                                                                   ipAddress : searchModel.IpAddress,
                                                                                   pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            if (activityLog is null)
            {
                return(new ActivityLogListModel());
            }

            //prepare list model
            var customerIds          = activityLog.GroupBy(logItem => logItem.CustomerId).Select(logItem => logItem.Key);
            var activityLogCustomers = await _customerService.GetCustomersByIdsAsync(customerIds.ToArray());

            var model = await new ActivityLogListModel().PrepareToGridAsync(searchModel, activityLog, () =>
            {
                return(activityLog.SelectAwait(async logItem =>
                {
                    //fill in model values from the entity
                    var logItemModel = logItem.ToModel <ActivityLogModel>();
                    logItemModel.ActivityLogTypeName = (await _customerActivityService.GetActivityTypeByIdAsync(logItem.ActivityLogTypeId))?.Name;

                    logItemModel.CustomerEmail = activityLogCustomers?.FirstOrDefault(x => x.Id == logItem.CustomerId)?.Email;

                    //convert dates to the user time
                    logItemModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(logItem.CreatedOnUtc, DateTimeKind.Utc);

                    return logItemModel;
                }));
            });

            return(model);
        }
示例#28
0
        public async Task CanPrepareBlogPostComment()
        {
            var blogComment = await _blogService.GetBlogCommentByIdAsync(1);

            var model = await _blogModelFactory.PrepareBlogPostCommentModelAsync(blogComment);

            var customer = await _customerService.GetCustomerByIdAsync(1);

            model.Id.Should().Be(blogComment.Id);
            model.CustomerId.Should().Be(blogComment.CustomerId);
            model.CustomerName.Should().Be(await _customerService.FormatUsernameAsync(customer));
            model.CommentText.Should().Be(blogComment.CommentText);
            model.CreatedOn.Should().Be(await _dateTimeHelper.ConvertToUserTimeAsync(blogComment.CreatedOnUtc, DateTimeKind.Utc));
            model.AllowViewingProfiles.Should().BeFalse();
            model.CustomerAvatarUrl.Should().BeNull();
        }
        /// <summary>
        /// Prepare paged newsletter subscription list model
        /// </summary>
        /// <param name="searchModel">Newsletter subscription search model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the newsletter subscription list model
        /// </returns>
        public virtual async Task <NewsletterSubscriptionListModel> PrepareNewsletterSubscriptionListModelAsync(NewsletterSubscriptionSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter newsletter subscriptions
            var isActivatedOnly = searchModel.ActiveId == 0 ? null : searchModel.ActiveId == 1 ? true : (bool?)false;
            var startDateValue  = !searchModel.StartDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.StartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
            var endDateValue = !searchModel.EndDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.EndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);

            //get newsletter subscriptions
            var newsletterSubscriptions = await _newsLetterSubscriptionService.GetAllNewsLetterSubscriptionsAsync(email : searchModel.SearchEmail,
                                                                                                                  customerRoleId : searchModel.CustomerRoleId,
                                                                                                                  storeId : searchModel.StoreId,
                                                                                                                  isActive : isActivatedOnly,
                                                                                                                  createdFromUtc : startDateValue,
                                                                                                                  createdToUtc : endDateValue,
                                                                                                                  pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new NewsletterSubscriptionListModel().PrepareToGridAsync(searchModel, newsletterSubscriptions, () =>
            {
                return(newsletterSubscriptions.SelectAwait(async subscription =>
                {
                    //fill in model values from the entity
                    var subscriptionModel = subscription.ToModel <NewsletterSubscriptionModel>();

                    //convert dates to the user time
                    subscriptionModel.CreatedOn = (await _dateTimeHelper.ConvertToUserTimeAsync(subscription.CreatedOnUtc, DateTimeKind.Utc)).ToString();

                    //fill in additional values (not existing in the entity)
                    subscriptionModel.StoreName = (await _storeService.GetStoreByIdAsync(subscription.StoreId))?.Name ?? "Deleted";

                    return subscriptionModel;
                }));
            });

            return(model);
        }
        /// <summary>
        /// Prepare paged discount usage history list model
        /// </summary>
        /// <param name="searchModel">Discount usage history search model</param>
        /// <param name="discount">Discount</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the discount usage history list model
        /// </returns>
        public virtual async Task <DiscountUsageHistoryListModel> PrepareDiscountUsageHistoryListModelAsync(DiscountUsageHistorySearchModel searchModel,
                                                                                                            Discount discount)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (discount == null)
            {
                throw new ArgumentNullException(nameof(discount));
            }

            //get discount usage history
            var history = await _discountService.GetAllDiscountUsageHistoryAsync(discountId : discount.Id,
                                                                                 pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize);

            //prepare list model
            var model = await new DiscountUsageHistoryListModel().PrepareToGridAsync(searchModel, history, () =>
            {
                return(history.SelectAwait(async historyEntry =>
                {
                    //fill in model values from the entity
                    var discountUsageHistoryModel = historyEntry.ToModel <DiscountUsageHistoryModel>();

                    //convert dates to the user time
                    discountUsageHistoryModel.CreatedOn = await _dateTimeHelper.ConvertToUserTimeAsync(historyEntry.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    var order = await _orderService.GetOrderByIdAsync(historyEntry.OrderId);
                    if (order != null)
                    {
                        discountUsageHistoryModel.OrderTotal = await _priceFormatter.FormatPriceAsync(order.OrderTotal, true, false);
                        discountUsageHistoryModel.CustomOrderNumber = order.CustomOrderNumber;
                    }

                    return discountUsageHistoryModel;
                }));
            });

            return(model);
        }