Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Grand.Business.Marketing - Code cleanup (ReSharper)
support0b9c545da1b7
diff --git a/src/Business/Grand.Business.Marketing/Extensions/NewsletterPublisherExtensions.cs b/src/Business/Grand.Business.Marketing/Extensions/NewsletterPublisherExtensions.csindex 3fc067075..c2f3fb7d7 100644--- a/src/Business/Grand.Business.Marketing/Extensions/NewsletterPublisherExtensions.cs+++ b/src/Business/Grand.Business.Marketing/Extensions/NewsletterPublisherExtensions.cs@@ -1,30 +1,27 @@using Grand.Business.Core.Events.Marketing;using MediatR;-namespace Grand.Business.Marketing.Extensions+namespace Grand.Business.Marketing.Extensions;++public static class NewsletterPublisherExtensions{- public static class NewsletterPublisherExtensions+ /// <summary>+ /// Publishes the newsletter subscribe event.+ /// </summary>+ /// <param name="mediator">mediator</param>+ /// <param name="email">The email.</param>+ public static async Task PublishNewsletterSubscribe(this IMediator mediator, string email){- /// <summary>- /// Publishes the newsletter subscribe event.- /// </summary>- /// <param name="mediator">mediator</param>- /// <param name="email">The email.</param>- public static async Task PublishNewsletterSubscribe(this IMediator mediator, string email)- {- await mediator.Publish(new EmailSubscribedEvent(email));- }-- /// <summary>- /// Publishes the newsletter unsubscribe event.- /// </summary>- /// <param name="mediator">Mediator</param>- /// <param name="email">The email.</param>- public static async Task PublishNewsletterUnsubscribe(this IMediator mediator, string email)- {- await mediator.Publish(new EmailUnsubscribedEvent(email));- }-+ await mediator.Publish(new EmailSubscribedEvent(email));+ }+ /// <summary>+ /// Publishes the newsletter unsubscribe event.+ /// </summary>+ /// <param name="mediator">Mediator</param>+ /// <param name="email">The email.</param>+ public static async Task PublishNewsletterUnsubscribe(this IMediator mediator, string email)+ {+ await mediator.Publish(new EmailUnsubscribedEvent(email));}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.csindex da7df1bc0..d7aabb6bd 100644--- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs@@ -3,342 +3,336 @@ using Grand.Business.Core.Interfaces.Common.Stores;using Grand.Business.Core.Interfaces.Marketing.Campaigns;using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Utilities.Messages.DotLiquidDrops;+using Grand.Data;using Grand.Domain;+using Grand.Domain.Common;using Grand.Domain.Customers;-using Grand.Data;using Grand.Domain.Messages;using Grand.Infrastructure;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Campaigns+namespace Grand.Business.Marketing.Services.Campaigns;++public class CampaignService(+ IRepository<Campaign> campaignRepository,+ IRepository<CampaignHistory> campaignHistoryRepository,+ IRepository<NewsLetterSubscription> newsLetterSubscriptionRepository,+ IRepository<Customer> customerRepository,+ IEmailSender emailSender,+ IQueuedEmailService queuedEmailService,+ IStoreService storeService,+ IMediator mediator,+ ILanguageService languageService,+ IWorkContext workContext)+ : ICampaignService{- public class CampaignService(- IRepository<Campaign> campaignRepository,- IRepository<CampaignHistory> campaignHistoryRepository,- IRepository<NewsLetterSubscription> newsLetterSubscriptionRepository,- IRepository<Customer> customerRepository,- IEmailSender emailSender,- IQueuedEmailService queuedEmailService,- IStoreService storeService,- IMediator mediator,- ILanguageService languageService,- IWorkContext workContext)- : ICampaignService+ /// <summary>+ /// Inserts a campaign+ /// </summary>+ /// <param name="campaign">Campaign</param>+ public virtual async Task InsertCampaign(Campaign campaign){- /// <summary>- /// Inserts a campaign- /// </summary>- /// <param name="campaign">Campaign</param>- public virtual async Task InsertCampaign(Campaign campaign)- {- ArgumentNullException.ThrowIfNull(campaign);-- await campaignRepository.InsertAsync(campaign);+ ArgumentNullException.ThrowIfNull(campaign);- //event notification- await mediator.EntityInserted(campaign);- }-- /// <summary>- /// Inserts a campaign history- /// </summary>- /// <param name="campaignHistory">Campaign</param>- public virtual async Task InsertCampaignHistory(CampaignHistory campaignHistory)- {- ArgumentNullException.ThrowIfNull(campaignHistory);+ await campaignRepository.InsertAsync(campaign);- await campaignHistoryRepository.InsertAsync(campaignHistory);+ //event notification+ await mediator.EntityInserted(campaign);+ }- }+ /// <summary>+ /// Inserts a campaign history+ /// </summary>+ /// <param name="campaignHistory">Campaign</param>+ public virtual async Task InsertCampaignHistory(CampaignHistory campaignHistory)+ {+ ArgumentNullException.ThrowIfNull(campaignHistory);- /// <summary>- /// Updates a campaign- /// </summary>- /// <param name="campaign">Campaign</param>- public virtual async Task UpdateCampaign(Campaign campaign)- {- ArgumentNullException.ThrowIfNull(campaign);+ await campaignHistoryRepository.InsertAsync(campaignHistory);+ }- await campaignRepository.UpdateAsync(campaign);+ /// <summary>+ /// Updates a campaign+ /// </summary>+ /// <param name="campaign">Campaign</param>+ public virtual async Task UpdateCampaign(Campaign campaign)+ {+ ArgumentNullException.ThrowIfNull(campaign);- //event notification- await mediator.EntityUpdated(campaign);- }+ await campaignRepository.UpdateAsync(campaign);- /// <summary>- /// Deleted a queued email- /// </summary>- /// <param name="campaign">Campaign</param>- public virtual async Task DeleteCampaign(Campaign campaign)- {- ArgumentNullException.ThrowIfNull(campaign);+ //event notification+ await mediator.EntityUpdated(campaign);+ }- await campaignRepository.DeleteAsync(campaign);+ /// <summary>+ /// Deleted a queued email+ /// </summary>+ /// <param name="campaign">Campaign</param>+ public virtual async Task DeleteCampaign(Campaign campaign)+ {+ ArgumentNullException.ThrowIfNull(campaign);- //event notification- await mediator.EntityDeleted(campaign);- }+ await campaignRepository.DeleteAsync(campaign);- /// <summary>- /// Gets a campaign by identifier- /// </summary>- /// <param name="campaignId">Campaign identifier</param>- /// <returns>Campaign</returns>- public virtual Task<Campaign> GetCampaignById(string campaignId)- {- return campaignRepository.GetByIdAsync(campaignId);+ //event notification+ await mediator.EntityDeleted(campaign);+ }- }+ /// <summary>+ /// Gets a campaign by identifier+ /// </summary>+ /// <param name="campaignId">Campaign identifier</param>+ /// <returns>Campaign</returns>+ public virtual Task<Campaign> GetCampaignById(string campaignId)+ {+ return campaignRepository.GetByIdAsync(campaignId);+ }- /// <summary>- /// Gets all campaigns- /// </summary>- /// <returns>Campaigns</returns>- public virtual async Task<IList<Campaign>> GetAllCampaigns()- {+ /// <summary>+ /// Gets all campaigns+ /// </summary>+ /// <returns>Campaigns</returns>+ public virtual async Task<IList<Campaign>> GetAllCampaigns()+ {+ var query = from c in campaignRepository.Table+ orderby c.CreatedOnUtc+ select c;+ return await Task.FromResult(query.ToList());+ }- var query = from c in campaignRepository.Table- orderby c.CreatedOnUtc- select c;- return await Task.FromResult(query.ToList());- }+ public virtual async Task<IPagedList<CampaignHistory>> GetCampaignHistory(Campaign campaign, int pageIndex = 0,+ int pageSize = int.MaxValue)+ {+ ArgumentNullException.ThrowIfNull(campaign);- public virtual async Task<IPagedList<CampaignHistory>> GetCampaignHistory(Campaign campaign, int pageIndex = 0, int pageSize = int.MaxValue)- {- ArgumentNullException.ThrowIfNull(campaign);+ var query = from c in campaignHistoryRepository.Table+ where c.CampaignId == campaign.Id+ orderby c.CreatedDateUtc descending+ select c;+ return await PagedList<CampaignHistory>.Create(query, pageIndex, pageSize);+ }- var query = from c in campaignHistoryRepository.Table- where c.CampaignId == campaign.Id- orderby c.CreatedDateUtc descending- select c;- return await PagedList<CampaignHistory>.Create(query, pageIndex, pageSize);- }- public virtual async Task<IPagedList<NewsLetterSubscription>> CustomerSubscriptions(Campaign campaign, int pageIndex = 0, int pageSize = int.MaxValue)+ public virtual async Task<IPagedList<NewsLetterSubscription>> CustomerSubscriptions(Campaign campaign,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ ArgumentNullException.ThrowIfNull(campaign);++ PagedList<NewsLetterSubscription> model;+ if (campaign.CustomerCreatedDateFrom.HasValue || campaign.CustomerCreatedDateTo.HasValue ||+ campaign.CustomerHasShoppingCart is not (CampaignCondition.All and CampaignCondition.All) ||+ campaign.CustomerLastActivityDateFrom.HasValue || campaign.CustomerLastActivityDateTo.HasValue ||+ campaign.CustomerLastPurchaseDateFrom.HasValue || campaign.CustomerLastPurchaseDateTo.HasValue ||+ campaign.CustomerTags.Count > 0 || campaign.CustomerGroups.Count > 0){- ArgumentNullException.ThrowIfNull(campaign);-- PagedList<NewsLetterSubscription> model;- if (campaign.CustomerCreatedDateFrom.HasValue || campaign.CustomerCreatedDateTo.HasValue ||- campaign.CustomerHasShoppingCart is not (CampaignCondition.All and CampaignCondition.All) ||- campaign.CustomerLastActivityDateFrom.HasValue || campaign.CustomerLastActivityDateTo.HasValue ||- campaign.CustomerLastPurchaseDateFrom.HasValue || campaign.CustomerLastPurchaseDateTo.HasValue ||- campaign.CustomerTags.Count > 0 || campaign.CustomerGroups.Count > 0)+ var query = from o in newsLetterSubscriptionRepository.Table+ where o.Active && o.CustomerId != "" &&+ (o.StoreId == campaign.StoreId || string.IsNullOrEmpty(campaign.StoreId))+ join c in customerRepository.Table on o.CustomerId equals c.Id into joined+ from customers in joined+ select new CampaignCustomerHelp {+ CustomerEmail = customers.Email,+ Email = o.Email,+ CustomerId = customers.Id,+ CreatedOnUtc = customers.CreatedOnUtc,+ CustomerTags = customers.CustomerTags,+ CustomerGroups = customers.Groups,+ NewsletterCategories = o.Categories,+ HasShoppingCartItems = customers.ShoppingCartItems.Any(),+ LastActivityDateUtc = customers.LastActivityDateUtc,+ LastPurchaseDateUtc = customers.LastPurchaseDateUtc,+ NewsLetterSubscriptionGuid = o.NewsLetterSubscriptionGuid+ };++ //create date+ if (campaign.CustomerCreatedDateFrom.HasValue)+ query = query.Where(x => x.CreatedOnUtc >= campaign.CustomerCreatedDateFrom.Value);+ if (campaign.CustomerCreatedDateTo.HasValue)+ query = query.Where(x => x.CreatedOnUtc <= campaign.CustomerCreatedDateTo.Value);++ //last activity+ if (campaign.CustomerLastActivityDateFrom.HasValue)+ query = query.Where(x => x.LastActivityDateUtc >= campaign.CustomerLastActivityDateFrom.Value);+ if (campaign.CustomerLastActivityDateTo.HasValue)+ query = query.Where(x => x.LastActivityDateUtc <= campaign.CustomerLastActivityDateTo.Value);++ //last purchase+ if (campaign.CustomerLastPurchaseDateFrom.HasValue)+ query = query.Where(x => x.LastPurchaseDateUtc >= campaign.CustomerLastPurchaseDateFrom.Value);+ if (campaign.CustomerLastPurchaseDateTo.HasValue)+ query = query.Where(x => x.LastPurchaseDateUtc <= campaign.CustomerLastPurchaseDateTo.Value);++ switch (campaign.CustomerHasShoppingCart){-- var query = from o in newsLetterSubscriptionRepository.Table- where o.Active && o.CustomerId != "" && (o.StoreId == campaign.StoreId || string.IsNullOrEmpty(campaign.StoreId))- join c in customerRepository.Table on o.CustomerId equals c.Id into joined- from customers in joined- select new CampaignCustomerHelp {- CustomerEmail = customers.Email,- Email = o.Email,- CustomerId = customers.Id,- CreatedOnUtc = customers.CreatedOnUtc,- CustomerTags = customers.CustomerTags,- CustomerGroups = customers.Groups,- NewsletterCategories = o.Categories,- HasShoppingCartItems = customers.ShoppingCartItems.Any(),- LastActivityDateUtc = customers.LastActivityDateUtc,- LastPurchaseDateUtc = customers.LastPurchaseDateUtc,- NewsLetterSubscriptionGuid = o.NewsLetterSubscriptionGuid- };-- //create date- if (campaign.CustomerCreatedDateFrom.HasValue)- query = query.Where(x => x.CreatedOnUtc >= campaign.CustomerCreatedDateFrom.Value);- if (campaign.CustomerCreatedDateTo.HasValue)- query = query.Where(x => x.CreatedOnUtc <= campaign.CustomerCreatedDateTo.Value);-- //last activity- if (campaign.CustomerLastActivityDateFrom.HasValue)- query = query.Where(x => x.LastActivityDateUtc >= campaign.CustomerLastActivityDateFrom.Value);- if (campaign.CustomerLastActivityDateTo.HasValue)- query = query.Where(x => x.LastActivityDateUtc <= campaign.CustomerLastActivityDateTo.Value);-- //last purchase- if (campaign.CustomerLastPurchaseDateFrom.HasValue)- query = query.Where(x => x.LastPurchaseDateUtc >= campaign.CustomerLastPurchaseDateFrom.Value);- if (campaign.CustomerLastPurchaseDateTo.HasValue)- query = query.Where(x => x.LastPurchaseDateUtc <= campaign.CustomerLastPurchaseDateTo.Value);-- switch (campaign.CustomerHasShoppingCart)- {- //customer has shopping carts- case CampaignCondition.True:- query = query.Where(x => x.HasShoppingCartItems);- break;- case CampaignCondition.False:- query = query.Where(x => !x.HasShoppingCartItems);- break;- }-- switch (campaign.CustomerHasOrders)- {- //customer has order- case CampaignCondition.True:- query = query.Where(x => x.IsHasOrders);- break;- case CampaignCondition.False:- query = query.Where(x => !x.IsHasOrders);- break;- }-- //tags- if (campaign.CustomerTags.Count > 0)- {- foreach (var item in campaign.CustomerTags)- {- query = query.Where(x => x.CustomerTags.Contains(item));- }- }- //roles- if (campaign.CustomerGroups.Count > 0)- {- foreach (var item in campaign.CustomerGroups)- {- query = query.Where(x => x.CustomerGroups.Any(z => z == item));- }- }- //categories news- if (campaign.NewsletterCategories.Count > 0)- {- foreach (var item in campaign.NewsletterCategories)- {- query = query.Where(x => x.NewsletterCategories.Contains(item));- }- }- model = await PagedList<NewsLetterSubscription>.Create(query.Select(x => new NewsLetterSubscription { CustomerId = x.CustomerId, Email = x.Email, NewsLetterSubscriptionGuid = x.NewsLetterSubscriptionGuid }), pageIndex, pageSize);+ //customer has shopping carts+ case CampaignCondition.True:+ query = query.Where(x => x.HasShoppingCartItems);+ break;+ case CampaignCondition.False:+ query = query.Where(x => !x.HasShoppingCartItems);+ break;}- else++ switch (campaign.CustomerHasOrders){- var query = from o in newsLetterSubscriptionRepository.Table- where o.Active && (o.StoreId == campaign.StoreId || string.IsNullOrEmpty(campaign.StoreId))- select o;-- if (campaign.NewsletterCategories.Count > 0)- {- foreach (var item in campaign.NewsletterCategories)- {- query = query.Where(x => x.Categories.Contains(item));- }- }- model = await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);+ //customer has order+ case CampaignCondition.True:+ query = query.Where(x => x.IsHasOrders);+ break;+ case CampaignCondition.False:+ query = query.Where(x => !x.IsHasOrders);+ break;}- return await Task.FromResult(model);+ //tags+ if (campaign.CustomerTags.Count > 0)+ foreach (var item in campaign.CustomerTags)+ query = query.Where(x => x.CustomerTags.Contains(item));+ //roles+ if (campaign.CustomerGroups.Count > 0)+ foreach (var item in campaign.CustomerGroups)+ query = query.Where(x => x.CustomerGroups.Any(z => z == item));+ //categories news+ if (campaign.NewsletterCategories.Count > 0)+ foreach (var item in campaign.NewsletterCategories)+ query = query.Where(x => x.NewsletterCategories.Contains(item));+ model = await PagedList<NewsLetterSubscription>.Create(+ query.Select(x => new NewsLetterSubscription {+ CustomerId = x.CustomerId, Email = x.Email,+ NewsLetterSubscriptionGuid = x.NewsLetterSubscriptionGuid+ }), pageIndex, pageSize);}-- private class CampaignCustomerHelp+ else{- public string CustomerId { get; set; }- public string CustomerEmail { get; set; }- public string Email { get; set; }- public DateTime CreatedOnUtc { get; set; }- public DateTime LastActivityDateUtc { get; set; }- public DateTime? LastPurchaseDateUtc { get; set; }- public bool HasShoppingCartItems { get; set; }- public bool IsHasOrders { get; set; }- public ICollection<string> CustomerTags { get; set; }- public ICollection<string> NewsletterCategories { get; set; }- public ICollection<string> CustomerGroups { get; set; } = new List<string>();- public Guid NewsLetterSubscriptionGuid { get; set; }+ var query = from o in newsLetterSubscriptionRepository.Table+ where o.Active && (o.StoreId == campaign.StoreId || string.IsNullOrEmpty(campaign.StoreId))+ select o;++ if (campaign.NewsletterCategories.Count > 0)+ foreach (var item in campaign.NewsletterCategories)+ query = query.Where(x => x.Categories.Contains(item));+ model = await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);}- /// <summary>- /// Sends a campaign to specified emails- /// </summary>- /// <param name="campaign">Campaign</param>- /// <param name="emailAccount">Email account</param>- /// <param name="subscriptions">Subscriptions</param>- /// <returns>Total emails sent</returns>- public virtual async Task<int> SendCampaign(Campaign campaign, EmailAccount emailAccount,- IEnumerable<NewsLetterSubscription> subscriptions)- {- ArgumentNullException.ThrowIfNull(campaign);- ArgumentNullException.ThrowIfNull(emailAccount);-- var totalEmailsSent = 0;- var language = await languageService.GetLanguageById(campaign.LanguageId) ?? (await languageService.GetAllLanguages()).FirstOrDefault();+ return await Task.FromResult(model);+ }- foreach (var subscription in subscriptions)- {- Customer customer = null;+ /// <summary>+ /// Sends a campaign to specified emails+ /// </summary>+ /// <param name="campaign">Campaign</param>+ /// <param name="emailAccount">Email account</param>+ /// <param name="subscriptions">Subscriptions</param>+ /// <returns>Total emails sent</returns>+ public virtual async Task<int> SendCampaign(Campaign campaign, EmailAccount emailAccount,+ IEnumerable<NewsLetterSubscription> subscriptions)+ {+ ArgumentNullException.ThrowIfNull(campaign);+ ArgumentNullException.ThrowIfNull(emailAccount);- if (!string.IsNullOrEmpty(subscription.CustomerId)) customer = await customerRepository.GetByIdAsync(subscription.CustomerId);- customer ??= customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant());+ var totalEmailsSent = 0;+ var language = await languageService.GetLanguageById(campaign.LanguageId) ??+ (await languageService.GetAllLanguages()).FirstOrDefault();- //ignore deleted or inactive customers when sending newsletter campaigns- if (customer != null && (!customer.Active || customer.Deleted))- continue;+ foreach (var subscription in subscriptions)+ {+ Customer customer = null;- var builder = new LiquidObjectBuilder(mediator);- var store = await storeService.GetStoreById(campaign.StoreId) ?? (await storeService.GetAllStores()).FirstOrDefault();+ if (!string.IsNullOrEmpty(subscription.CustomerId))+ customer = await customerRepository.GetByIdAsync(subscription.CustomerId);+ customer ??= customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant());- builder.AddStoreTokens(store, language, emailAccount)- .AddNewsLetterSubscriptionTokens(subscription, store, workContext.CurrentHost);+ //ignore deleted or inactive customers when sending newsletter campaigns+ if (customer != null && (!customer.Active || customer.Deleted))+ continue;- if (customer != null)- {- builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)- .AddShoppingCartTokens(customer, store, language);- }+ var builder = new LiquidObjectBuilder(mediator);+ var store = await storeService.GetStoreById(campaign.StoreId) ??+ (await storeService.GetAllStores()).FirstOrDefault();- var email = new QueuedEmail();+ builder.AddStoreTokens(store, language, emailAccount)+ .AddNewsLetterSubscriptionTokens(subscription, store, workContext.CurrentHost);- var liquidObject = await builder.BuildAsync();- liquidObject.Email = new LiquidEmail(email.Id);+ if (customer != null)+ builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)+ .AddShoppingCartTokens(customer, store, language);- var body = LiquidExtensions.Render(liquidObject, campaign.Body);- var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);+ var email = new QueuedEmail();- email.PriorityId = QueuedEmailPriority.Low;- email.From = emailAccount.Email;- email.FromName = emailAccount.DisplayName;- email.To = subscription.Email;- email.Subject = subject;- email.Body = body;- email.EmailAccountId = emailAccount.Id;- email.Reference = Domain.Common.Reference.Campaign;- email.ObjectId = campaign.Id;+ var liquidObject = await builder.BuildAsync();+ liquidObject.Email = new LiquidEmail(email.Id);- await queuedEmailService.InsertQueuedEmail(email);- await InsertCampaignHistory(new CampaignHistory { CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId });+ var body = LiquidExtensions.Render(liquidObject, campaign.Body);+ var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);- totalEmailsSent++;- }- return totalEmailsSent;+ email.PriorityId = QueuedEmailPriority.Low;+ email.From = emailAccount.Email;+ email.FromName = emailAccount.DisplayName;+ email.To = subscription.Email;+ email.Subject = subject;+ email.Body = body;+ email.EmailAccountId = emailAccount.Id;+ email.Reference = Reference.Campaign;+ email.ObjectId = campaign.Id;++ await queuedEmailService.InsertQueuedEmail(email);+ await InsertCampaignHistory(new CampaignHistory {+ CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email,+ CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId+ });++ totalEmailsSent++;}- /// <summary>- /// Sends a campaign to specified email- /// </summary>- /// <param name="campaign">Campaign</param>- /// <param name="emailAccount">Email account</param>- /// <param name="email">Email</param>- public virtual async Task SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)- {- ArgumentNullException.ThrowIfNull(campaign);- ArgumentNullException.ThrowIfNull(emailAccount);+ return totalEmailsSent;+ }- var language = await languageService.GetLanguageById(campaign.LanguageId) ?? (await languageService.GetAllLanguages()).FirstOrDefault();+ /// <summary>+ /// Sends a campaign to specified email+ /// </summary>+ /// <param name="campaign">Campaign</param>+ /// <param name="emailAccount">Email account</param>+ /// <param name="email">Email</param>+ public virtual async Task SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)+ {+ ArgumentNullException.ThrowIfNull(campaign);+ ArgumentNullException.ThrowIfNull(emailAccount);- var store = await storeService.GetStoreById(campaign.StoreId) ?? (await storeService.GetAllStores()).FirstOrDefault();+ var language = await languageService.GetLanguageById(campaign.LanguageId) ??+ (await languageService.GetAllLanguages()).FirstOrDefault();- var builder = new LiquidObjectBuilder(mediator);- builder.AddStoreTokens(store, language, emailAccount);- var customer = customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant());- if (customer != null)- {- builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)- .AddShoppingCartTokens(customer, store, language);- }+ var store = await storeService.GetStoreById(campaign.StoreId) ??+ (await storeService.GetAllStores()).FirstOrDefault();- var liquidObject = await builder.BuildAsync();- var body = LiquidExtensions.Render(liquidObject, campaign.Body);- var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);+ var builder = new LiquidObjectBuilder(mediator);+ builder.AddStoreTokens(store, language, emailAccount);+ var customer = customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant());+ if (customer != null)+ builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)+ .AddShoppingCartTokens(customer, store, language);- await emailSender.SendEmail(emailAccount, subject, body, emailAccount.Email, emailAccount.DisplayName, email, null);- }+ var liquidObject = await builder.BuildAsync();+ var body = LiquidExtensions.Render(liquidObject, campaign.Body);+ var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);++ await emailSender.SendEmail(emailAccount, subject, body, emailAccount.Email, emailAccount.DisplayName, email,+ null);+ }++ private class CampaignCustomerHelp+ {+ public string CustomerId { get; set; }+ public string CustomerEmail { get; set; }+ public string Email { get; set; }+ public DateTime CreatedOnUtc { get; set; }+ public DateTime LastActivityDateUtc { get; set; }+ public DateTime? LastPurchaseDateUtc { get; set; }+ public bool HasShoppingCartItems { get; set; }+ public bool IsHasOrders { get; }+ public ICollection<string> CustomerTags { get; set; }+ public ICollection<string> NewsletterCategories { get; set; }+ public ICollection<string> CustomerGroups { get; set; } = new List<string>();+ public Guid NewsLetterSubscriptionGuid { get; set; }}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.csindex 0f7eb3338..73e9216af 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs@@ -9,357 +9,339 @@ using Grand.Infrastructure;using Grand.SharedKernel.Extensions;using System.Net;-namespace Grand.Business.Marketing.Services.Contacts+namespace Grand.Business.Marketing.Services.Contacts;++/// <summary>+/// Contact attribute parser+/// </summary>+public class ContactAttributeParser : IContactAttributeParser{+ private readonly IContactAttributeService _contactAttributeService;+ private readonly IWorkContext _workContext;++ public ContactAttributeParser(+ IContactAttributeService contactAttributeService,+ IWorkContext workContext+ )+ {+ _contactAttributeService = contactAttributeService;+ _workContext = workContext;+ }+/// <summary>- /// Contact attribute parser+ /// Gets selected contact attributes/// </summary>- public class ContactAttributeParser : IContactAttributeParser+ /// <param name="customAttributes">Attributes</param>+ /// <returns>Selected contact attributes</returns>+ public virtual async Task<IList<ContactAttribute>> ParseContactAttributes(+ IList<CustomAttribute> customAttributes){- private readonly IContactAttributeService _contactAttributeService;- private readonly IWorkContext _workContext;-- public ContactAttributeParser(- IContactAttributeService contactAttributeService,- IWorkContext workContext- )- {- _contactAttributeService = contactAttributeService;- _workContext = workContext;- }-- /// <summary>- /// Gets selected contact attributes- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <returns>Selected contact attributes</returns>- public virtual async Task<IList<ContactAttribute>> ParseContactAttributes(- IList<CustomAttribute> customAttributes)- {- var result = new List<ContactAttribute>();- if (customAttributes == null || !customAttributes.Any())- return result;-- foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))- {- var attribute = await _contactAttributeService.GetContactAttributeById(customAttribute.Key);- if (attribute != null)- {- result.Add(attribute);- }- }-+ var result = new List<ContactAttribute>();+ if (customAttributes == null || !customAttributes.Any())return result;- }- /// <summary>- /// Get contact attribute values- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <returns>Contact attribute values</returns>- public virtual async Task<IList<ContactAttributeValue>> ParseContactAttributeValues(- IList<CustomAttribute> customAttributes)+ foreach (var customAttribute in customAttributes.GroupBy(x => x.Key)){- var values = new List<ContactAttributeValue>();- if (customAttributes == null || !customAttributes.Any())- return values;-- var attributes = await ParseContactAttributes(customAttributes);- foreach (var attribute in attributes)- {- if (!attribute.ShouldHaveValues())- continue;+ var attribute = await _contactAttributeService.GetContactAttributeById(customAttribute.Key);+ if (attribute != null) result.Add(attribute);+ }- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- values.AddRange(from valueStr in valuesStr- where !string.IsNullOrEmpty(valueStr)- select attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr)- into value- where value != null- select value);- }+ return result;+ }+ /// <summary>+ /// Get contact attribute values+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <returns>Contact attribute values</returns>+ public virtual async Task<IList<ContactAttributeValue>> ParseContactAttributeValues(+ IList<CustomAttribute> customAttributes)+ {+ var values = new List<ContactAttributeValue>();+ if (customAttributes == null || !customAttributes.Any())return values;- }- /// <summary>- /// Adds an attribute- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="ca">Contact attribute</param>- /// <param name="value">Value</param>- /// <returns>Attributes</returns>- public virtual IList<CustomAttribute> AddContactAttribute(IList<CustomAttribute> customAttributes,- ContactAttribute ca, string value)+ var attributes = await ParseContactAttributes(customAttributes);+ foreach (var attribute in attributes){- customAttributes ??= new List<CustomAttribute>();- customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });- return customAttributes;+ if (!attribute.ShouldHaveValues())+ continue;++ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);+ values.AddRange(from valueStr in valuesStr+ where !string.IsNullOrEmpty(valueStr)+ select attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr)+ into value+ where value != null+ select value);}- /// <summary>- /// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified- /// </summary>- /// <param name="attribute">Contact attribute</param>- /// <param name="customAttributes">Selected attributes</param>- /// <returns>Result</returns>- public virtual async Task<bool?> IsConditionMet(ContactAttribute attribute,- IList<CustomAttribute> customAttributes)- {- ArgumentNullException.ThrowIfNull(attribute);- customAttributes ??= new List<CustomAttribute>();+ return values;+ }- var conditionAttribute = attribute.ConditionAttribute;- if (!conditionAttribute.Any())- //no condition- return null;+ /// <summary>+ /// Adds an attribute+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="ca">Contact attribute</param>+ /// <param name="value">Value</param>+ /// <returns>Attributes</returns>+ public virtual IList<CustomAttribute> AddContactAttribute(IList<CustomAttribute> customAttributes,+ ContactAttribute ca, string value)+ {+ customAttributes ??= new List<CustomAttribute>();+ customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });+ return customAttributes;+ }- //load an attribute this one depends on- var dependOnAttribute = (await ParseContactAttributes(conditionAttribute)).FirstOrDefault();- if (dependOnAttribute == null)- return true;+ /// <summary>+ /// Check whether condition of some attribute is met (if specified). Return "null" if not condition is specified+ /// </summary>+ /// <param name="attribute">Contact attribute</param>+ /// <param name="customAttributes">Selected attributes</param>+ /// <returns>Result</returns>+ public virtual async Task<bool?> IsConditionMet(ContactAttribute attribute,+ IList<CustomAttribute> customAttributes)+ {+ ArgumentNullException.ThrowIfNull(attribute);+ customAttributes ??= new List<CustomAttribute>();- var valuesThatShouldBeSelected = conditionAttribute.Where(x => x.Key == dependOnAttribute.Id)- .Select(x => x.Value)- //a workaround here:- //ConditionAttribute can contain "empty" values (nothing is selected)- //but in other cases (like below) we do not store empty values- //that's why we remove empty values here- .Where(x => !string.IsNullOrEmpty(x))- .ToList();+ var conditionAttribute = attribute.ConditionAttribute;+ if (!conditionAttribute.Any())+ //no condition+ return null;- var selectedValues = customAttributes.Where(x => x.Key == dependOnAttribute.Id).Select(x => x.Value)- .ToList();- if (valuesThatShouldBeSelected.Count != selectedValues.Count)- return false;+ //load an attribute this one depends on+ var dependOnAttribute = (await ParseContactAttributes(conditionAttribute)).FirstOrDefault();+ if (dependOnAttribute == null)+ return true;- //compare values- var allFound = true;- foreach (var t1 in valuesThatShouldBeSelected)- {- var found = false;- foreach (var t2 in selectedValues.Where(t2 => t1 == t2))- found = true;- if (!found)- allFound = false;- }+ var valuesThatShouldBeSelected = conditionAttribute.Where(x => x.Key == dependOnAttribute.Id)+ .Select(x => x.Value)+ //a workaround here:+ //ConditionAttribute can contain "empty" values (nothing is selected)+ //but in other cases (like below) we do not store empty values+ //that's why we remove empty values here+ .Where(x => !string.IsNullOrEmpty(x))+ .ToList();- return allFound;- }+ var selectedValues = customAttributes.Where(x => x.Key == dependOnAttribute.Id).Select(x => x.Value)+ .ToList();+ if (valuesThatShouldBeSelected.Count != selectedValues.Count)+ return false;- /// <summary>- /// Remove an attribute- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="attribute">Contact attribute</param>- /// <returns>Updated result</returns>- public virtual IList<CustomAttribute> RemoveContactAttribute(IList<CustomAttribute> customAttributes,- ContactAttribute attribute)+ //compare values+ var allFound = true;+ foreach (var t1 in valuesThatShouldBeSelected){- return customAttributes.Where(x => x.Key != attribute.Id).ToList();+ var found = false;+ foreach (var t2 in selectedValues.Where(t2 => t1 == t2))+ found = true;+ if (!found)+ allFound = false;}- /// <summary>- /// Formats attributes- /// </summary>- /// <param name="language">Language</param>- /// <param name="customAttributes">Attributes </param>- /// <param name="customer">Customer</param>- /// <param name="separator">Separator</param>- /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>- /// <returns>Attributes</returns>- public virtual async Task<string> FormatAttributes(- Language language,- IList<CustomAttribute> customAttributes,- Customer customer,- string separator = "<br />",- bool htmlEncode = true,- bool allowHyperlinks = true)- {- var result = new StringBuilder();- if (customAttributes == null || !customAttributes.Any())- return result.ToString();+ return allFound;+ }- var attributes = await ParseContactAttributes(customAttributes);- for (var i = 0; i < attributes.Count; i++)+ /// <summary>+ /// Remove an attribute+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="attribute">Contact attribute</param>+ /// <returns>Updated result</returns>+ public virtual IList<CustomAttribute> RemoveContactAttribute(IList<CustomAttribute> customAttributes,+ ContactAttribute attribute)+ {+ return customAttributes.Where(x => x.Key != attribute.Id).ToList();+ }++ /// <summary>+ /// Formats attributes+ /// </summary>+ /// <param name="language">Language</param>+ /// <param name="customAttributes">Attributes </param>+ /// <param name="customer">Customer</param>+ /// <param name="separator">Separator</param>+ /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>+ /// <returns>Attributes</returns>+ public virtual async Task<string> FormatAttributes(+ Language language,+ IList<CustomAttribute> customAttributes,+ Customer customer,+ string separator = "<br />",+ bool htmlEncode = true,+ bool allowHyperlinks = true)+ {+ var result = new StringBuilder();+ if (customAttributes == null || !customAttributes.Any())+ return result.ToString();++ var attributes = await ParseContactAttributes(customAttributes);+ for (var i = 0; i < attributes.Count; i++)+ {+ var attribute = attributes[i];+ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();+ for (var j = 0; j < valuesStr.Count; j++){- var attribute = attributes[i];- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();- for (var j = 0; j < valuesStr.Count; j++)+ var valueStr = valuesStr[j];+ var formattedAttribute = "";+ if (!attribute.ShouldHaveValues()){- var valueStr = valuesStr[j];- var formattedAttribute = "";- if (!attribute.ShouldHaveValues())+ switch (attribute.AttributeControlType){- switch (attribute.AttributeControlType)+ //no values+ case AttributeControlType.MultilineTextbox:+ {+ //multiline text box+ var attributeName = attribute.GetTranslation(a => a.Name, language.Id);+ //encode (if required)+ if (htmlEncode)+ attributeName = WebUtility.HtmlEncode(attributeName);+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input+ break;+ }+ case AttributeControlType.FileUpload:{- //no values- case AttributeControlType.MultilineTextbox:+ //file upload+ if (Guid.TryParse(valueStr, out var downloadGuid)){- //multiline text box+ var attributeText = string.Empty;var attributeName = attribute.GetTranslation(a => a.Name, language.Id);- //encode (if required)- if (htmlEncode)- attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";- //we never encode multiline text box input- break;- }- case AttributeControlType.FileUpload:- {- //file upload- if (Guid.TryParse(valueStr, out var downloadGuid))+ if (allowHyperlinks){- var attributeText = string.Empty;- var attributeName = attribute.GetTranslation(a => a.Name, language.Id);- if (allowHyperlinks)- {- var downloadLink =- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";- attributeText =- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";- }-- formattedAttribute = $"{attributeName}: {attributeText}";+ var downloadLink =+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";+ attributeText =+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";}- break;- }- default:- {- //other attributes (text box, datepicker)- formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";- //encode (if required)- if (htmlEncode)- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);- break;+ formattedAttribute = $"{attributeName}: {attributeText}";}++ break;}- }- else- {- var attributeValue = attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr);- if (attributeValue != null)+ default:{- formattedAttribute =- $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";+ //other attributes (text box, datepicker)+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";+ //encode (if required)+ if (htmlEncode)+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);+ break;}-- //encode (if required)- if (htmlEncode)- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}+ }+ else+ {+ var attributeValue = attribute.ContactAttributeValues.FirstOrDefault(x => x.Id == valueStr);+ if (attributeValue != null)+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";- if (string.IsNullOrEmpty(formattedAttribute)) continue;- if (i != 0 || j != 0)- result.Append(separator);- result.Append(formattedAttribute);+ //encode (if required)+ if (htmlEncode)+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}- }- return result.ToString();+ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);+ }}- public async Task<IList<CustomAttribute>> GetParseContactAttributes(IList<CustomAttribute> model)- {- var customAttributes = new List<CustomAttribute>();- var contactAttributes = await _contactAttributeService.GetAllContactAttributes();- foreach (var attribute in contactAttributes)+ return result.ToString();+ }++ public async Task<IList<CustomAttribute>> GetParseContactAttributes(IList<CustomAttribute> model)+ {+ var customAttributes = new List<CustomAttribute>();+ var contactAttributes = await _contactAttributeService.GetAllContactAttributes();+ foreach (var attribute in contactAttributes)+ switch (attribute.AttributeControlType){- switch (attribute.AttributeControlType)+ case AttributeControlType.DropdownList:+ case AttributeControlType.RadioList:+ case AttributeControlType.ColorSquares:+ case AttributeControlType.ImageSquares:{- case AttributeControlType.DropdownList:- case AttributeControlType.RadioList:- case AttributeControlType.ColorSquares:- case AttributeControlType.ImageSquares:- {- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- {- customAttributes = AddContactAttribute(customAttributes,- attribute, ctrlAttributes).ToList();- }- }- break;- case AttributeControlType.Checkboxes:- {- var cblAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = AddContactAttribute(customAttributes,+ attribute, ctrlAttributes).ToList();+ }+ break;+ case AttributeControlType.Checkboxes:+ {+ var cblAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- {- foreach (var item in cblAttributes.Split(','))- {- customAttributes = AddContactAttribute(customAttributes, attribute, item).ToList();- }- }- }- break;- case AttributeControlType.ReadonlyCheckboxes:+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes.Split(','))+ customAttributes = AddContactAttribute(customAttributes, attribute, item).ToList();+ }+ break;+ case AttributeControlType.ReadonlyCheckboxes:+ {+ //load read-only (already server-side selected) values+ var attributeValues = attribute.ContactAttributeValues;+ foreach (var selectedAttributeId in attributeValues+ .Where(v => v.IsPreSelected)+ .Select(v => v.Id)+ .ToList())+ customAttributes = AddContactAttribute(customAttributes,+ attribute, selectedAttributeId).ToList();+ }+ break;+ case AttributeControlType.TextBox:+ case AttributeControlType.MultilineTextbox:+ {+ var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes)){- //load read-only (already server-side selected) values- var attributeValues = attribute.ContactAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- {- customAttributes = AddContactAttribute(customAttributes,- attribute, selectedAttributeId).ToList();- }+ var enteredText = ctrlAttributes.Trim();+ customAttributes = AddContactAttribute(customAttributes,+ attribute, enteredText).ToList();}- break;- case AttributeControlType.TextBox:- case AttributeControlType.MultilineTextbox:+ }+ break;+ case AttributeControlType.Datepicker:+ {+ var date = model.FirstOrDefault(x => x.Key == attribute.Id + "_day")?.Value;+ var month = model.FirstOrDefault(x => x.Key == attribute.Id + "_month")?.Value;+ var year = model.FirstOrDefault(x => x.Key == attribute.Id + "_year")?.Value;+ DateTime? selectedDate = null;+ try{- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- {- var enteredText = ctrlAttributes.Trim();- customAttributes = AddContactAttribute(customAttributes,- attribute, enteredText).ToList();- }+ selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(date));}- break;- case AttributeControlType.Datepicker:- {- var date = model.FirstOrDefault(x => x.Key == attribute.Id + "_day")?.Value;- var month = model.FirstOrDefault(x => x.Key == attribute.Id + "_month")?.Value;- var year = model.FirstOrDefault(x => x.Key == attribute.Id + "_year")?.Value;- DateTime? selectedDate = null;- try- {- selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(date));- }- catch { }+ catch { }- if (selectedDate.HasValue)- {- customAttributes = AddContactAttribute(customAttributes,- attribute, selectedDate.Value.ToString("D")).ToList();- }- }- break;- case AttributeControlType.FileUpload:- {- var guid = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (Guid.TryParse(guid, out Guid downloadGuid))- customAttributes = AddContactAttribute(customAttributes,- attribute, downloadGuid.ToString()).ToList();- }- break;+ if (selectedDate.HasValue)+ customAttributes = AddContactAttribute(customAttributes,+ attribute, selectedDate.Value.ToString("D")).ToList();}+ break;+ case AttributeControlType.FileUpload:+ {+ var guid = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (Guid.TryParse(guid, out var downloadGuid))+ customAttributes = AddContactAttribute(customAttributes,+ attribute, downloadGuid.ToString()).ToList();+ }+ break;}- //validate conditional attributes (if specified)- foreach (var attribute in contactAttributes)- {- var conditionMet = await IsConditionMet(attribute, customAttributes);- if (conditionMet.HasValue && !conditionMet.Value)- customAttributes = RemoveContactAttribute(customAttributes, attribute).ToList();- }-- return customAttributes;+ //validate conditional attributes (if specified)+ foreach (var attribute in contactAttributes)+ {+ var conditionMet = await IsConditionMet(attribute, customAttributes);+ if (conditionMet.HasValue && !conditionMet.Value)+ customAttributes = RemoveContactAttribute(customAttributes, attribute).ToList();}++ return customAttributes;}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.csindex d737fa0a0..d925f303d 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs@@ -1,6 +1,6 @@using Grand.Business.Core.Interfaces.Marketing.Contacts;-using Grand.Domain.Customers;using Grand.Data;+using Grand.Domain.Customers;using Grand.Domain.Messages;using Grand.Infrastructure;using Grand.Infrastructure.Caching;@@ -9,148 +9,145 @@ using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Contacts+namespace Grand.Business.Marketing.Services.Contacts;++/// <summary>+/// Contact attribute service+/// </summary>+public class ContactAttributeService : IContactAttributeService{+ #region Ctor+/// <summary>- /// Contact attribute service+ /// Ctor/// </summary>- public class ContactAttributeService : IContactAttributeService+ public ContactAttributeService(ICacheBase cacheBase,+ IRepository<ContactAttribute> contactAttributeRepository,+ IMediator mediator,+ IWorkContext workContext, AccessControlConfig accessControlConfig){- #region Fields-- private readonly IRepository<ContactAttribute> _contactAttributeRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;- private readonly IWorkContext _workContext;- private readonly AccessControlConfig _accessControlConfig;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- public ContactAttributeService(ICacheBase cacheBase,- IRepository<ContactAttribute> contactAttributeRepository,- IMediator mediator,- IWorkContext workContext, AccessControlConfig accessControlConfig)- {- _cacheBase = cacheBase;- _contactAttributeRepository = contactAttributeRepository;- _mediator = mediator;- _workContext = workContext;- _accessControlConfig = accessControlConfig;- }+ _cacheBase = cacheBase;+ _contactAttributeRepository = contactAttributeRepository;+ _mediator = mediator;+ _workContext = workContext;+ _accessControlConfig = accessControlConfig;+ }- #endregion+ #endregion- #region Methods+ #region Fields- #region Contact attributes+ private readonly IRepository<ContactAttribute> _contactAttributeRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;+ private readonly IWorkContext _workContext;+ private readonly AccessControlConfig _accessControlConfig;- /// <summary>- /// Deletes a contact attribute- /// </summary>- /// <param name="contactAttribute">Contact attribute</param>- public virtual async Task DeleteContactAttribute(ContactAttribute contactAttribute)- {- ArgumentNullException.ThrowIfNull(contactAttribute);+ #endregion- await _contactAttributeRepository.DeleteAsync(contactAttribute);+ #region Methods- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);+ #region Contact attributes- //event notification- await _mediator.EntityDeleted(contactAttribute);- }+ /// <summary>+ /// Deletes a contact attribute+ /// </summary>+ /// <param name="contactAttribute">Contact attribute</param>+ public virtual async Task DeleteContactAttribute(ContactAttribute contactAttribute)+ {+ ArgumentNullException.ThrowIfNull(contactAttribute);- /// <summary>- /// Gets all contact attributes- /// </summary>- /// <param name="storeId">Store identifier</param>- /// <param name="ignoreAcl"></param>- /// <returns>Contact attributes</returns>- public virtual async Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "", bool ignoreAcl = false)- {- var key = string.Format(CacheKey.CONTACTATTRIBUTES_ALL_KEY, storeId, ignoreAcl);- return await _cacheBase.GetAsync(key, async () =>- {- var query = from p in _contactAttributeRepository.Table- select p;-- query = query.OrderBy(c => c.DisplayOrder);-- if ((string.IsNullOrEmpty(storeId) || _accessControlConfig.IgnoreStoreLimitations) &&- (ignoreAcl || _accessControlConfig.IgnoreAcl)) return await Task.FromResult(query.ToList());- if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)- {- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();- query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;- }- //Store acl- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)- {- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;- }- return await Task.FromResult(query.ToList());-- });- }-- /// <summary>- /// Gets a contact attribute- /// </summary>- /// <param name="contactAttributeId">Contact attribute identifier</param>- /// <returns>Contact attribute</returns>- public virtual Task<ContactAttribute> GetContactAttributeById(string contactAttributeId)- {- var key = string.Format(CacheKey.CONTACTATTRIBUTES_BY_ID_KEY, contactAttributeId);- return _cacheBase.GetAsync(key, () => _contactAttributeRepository.GetByIdAsync(contactAttributeId));- }-- /// <summary>- /// Inserts a contact attribute- /// </summary>- /// <param name="contactAttribute">Contact attribute</param>- public virtual async Task InsertContactAttribute(ContactAttribute contactAttribute)+ await _contactAttributeRepository.DeleteAsync(contactAttribute);++ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);++ //event notification+ await _mediator.EntityDeleted(contactAttribute);+ }++ /// <summary>+ /// Gets all contact attributes+ /// </summary>+ /// <param name="storeId">Store identifier</param>+ /// <param name="ignoreAcl"></param>+ /// <returns>Contact attributes</returns>+ public virtual async Task<IList<ContactAttribute>> GetAllContactAttributes(string storeId = "",+ bool ignoreAcl = false)+ {+ var key = string.Format(CacheKey.CONTACTATTRIBUTES_ALL_KEY, storeId, ignoreAcl);+ return await _cacheBase.GetAsync(key, async () =>{- ArgumentNullException.ThrowIfNull(contactAttribute);+ var query = from p in _contactAttributeRepository.Table+ select p;- await _contactAttributeRepository.InsertAsync(contactAttribute);+ query = query.OrderBy(c => c.DisplayOrder);- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);+ if ((string.IsNullOrEmpty(storeId) || _accessControlConfig.IgnoreStoreLimitations) &&+ (ignoreAcl || _accessControlConfig.IgnoreAcl)) return await Task.FromResult(query.ToList());+ if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)+ {+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();+ query = from p in query+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;+ }++ //Store acl+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ select p;+ return await Task.FromResult(query.ToList());+ });+ }- //event notification- await _mediator.EntityInserted(contactAttribute);- }+ /// <summary>+ /// Gets a contact attribute+ /// </summary>+ /// <param name="contactAttributeId">Contact attribute identifier</param>+ /// <returns>Contact attribute</returns>+ public virtual Task<ContactAttribute> GetContactAttributeById(string contactAttributeId)+ {+ var key = string.Format(CacheKey.CONTACTATTRIBUTES_BY_ID_KEY, contactAttributeId);+ return _cacheBase.GetAsync(key, () => _contactAttributeRepository.GetByIdAsync(contactAttributeId));+ }- /// <summary>- /// Updates the contact attribute- /// </summary>- /// <param name="contactAttribute">Contact attribute</param>- public virtual async Task UpdateContactAttribute(ContactAttribute contactAttribute)- {- ArgumentNullException.ThrowIfNull(contactAttribute);+ /// <summary>+ /// Inserts a contact attribute+ /// </summary>+ /// <param name="contactAttribute">Contact attribute</param>+ public virtual async Task InsertContactAttribute(ContactAttribute contactAttribute)+ {+ ArgumentNullException.ThrowIfNull(contactAttribute);- await _contactAttributeRepository.UpdateAsync(contactAttribute);+ await _contactAttributeRepository.InsertAsync(contactAttribute);- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);- //event notification- await _mediator.EntityUpdated(contactAttribute);- }+ //event notification+ await _mediator.EntityInserted(contactAttribute);+ }- #endregion+ /// <summary>+ /// Updates the contact attribute+ /// </summary>+ /// <param name="contactAttribute">Contact attribute</param>+ public virtual async Task UpdateContactAttribute(ContactAttribute contactAttribute)+ {+ ArgumentNullException.ThrowIfNull(contactAttribute);++ await _contactAttributeRepository.UpdateAsync(contactAttribute);+ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CONTACTATTRIBUTEVALUES_PATTERN_KEY);- #endregion+ //event notification+ await _mediator.EntityUpdated(contactAttribute);}-}++ #endregion++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.csindex fba07d19b..f9bdad1b0 100644--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs@@ -1,115 +1,110 @@using Grand.Business.Core.Interfaces.Marketing.Contacts;-using Grand.Infrastructure.Extensions;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Messages;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Contacts+namespace Grand.Business.Marketing.Services.Contacts;++/// <summary>+/// ContactUs interface+/// </summary>+public class ContactUsService : IContactUsService{+ private readonly IRepository<ContactUs> _contactusRepository;+ private readonly IMediator _mediator;++ public ContactUsService(+ IRepository<ContactUs> contactusRepository,+ IMediator mediator)+ {+ _contactusRepository = contactusRepository;+ _mediator = mediator;+ }+/// <summary>- /// ContactUs interface+ /// Deletes a contactus item/// </summary>- public class ContactUsService : IContactUsService+ /// <param name="contactus">ContactUs item</param>+ public virtual async Task DeleteContactUs(ContactUs contactus){+ ArgumentNullException.ThrowIfNull(contactus);- private readonly IRepository<ContactUs> _contactusRepository;- private readonly IMediator _mediator;-- public ContactUsService(- IRepository<ContactUs> contactusRepository,- IMediator mediator)- {- _contactusRepository = contactusRepository;- _mediator = mediator;- }- /// <summary>- /// Deletes a contactus item- /// </summary>- /// <param name="contactus">ContactUs item</param>- public virtual async Task DeleteContactUs(ContactUs contactus)- {- ArgumentNullException.ThrowIfNull(contactus);-- await _contactusRepository.DeleteAsync(contactus);-- //event notification- await _mediator.EntityDeleted(contactus);-- }-- /// <summary>- /// Clears table- /// </summary>- public virtual async Task ClearTable()- {- await _contactusRepository.ClearAsync();- }-- /// <summary>- /// Gets all contactUs items- /// </summary>- /// <param name="fromUtc">ContactUs item creation from; null to load all records</param>- /// <param name="toUtc">ContactUs item creation to; null to load all records</param>- /// <param name="email">email</param>- /// <param name="vendorId">vendorId; null to load all records</param>- /// <param name="customerId">customerId; null to load all records</param>- /// <param name="storeId">Store ident</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>ContactUs items</returns>- public virtual async Task<IPagedList<ContactUs>> GetAllContactUs(DateTime? fromUtc = null, DateTime? toUtc = null,- string email = "", string vendorId = "", string customerId = "", string storeId = "",- int pageIndex = 0, int pageSize = int.MaxValue)- {-- var query = from c in _contactusRepository.Table- select c;-- if (fromUtc.HasValue)- query = query.Where(l => fromUtc.Value <= l.CreatedOnUtc);- if (toUtc.HasValue)- query = query.Where(l => toUtc.Value >= l.CreatedOnUtc);- if (!string.IsNullOrEmpty(vendorId))- query = query.Where(l => vendorId == l.VendorId);- if (!string.IsNullOrEmpty(customerId))- query = query.Where(l => customerId == l.CustomerId);- if (!string.IsNullOrEmpty(storeId))- query = query.Where(l => storeId == l.StoreId);+ await _contactusRepository.DeleteAsync(contactus);- if (!string.IsNullOrEmpty(email))- query = query.Where(l => l.Email.ToLower().Contains(email.ToLower()));-- query = query.OrderByDescending(x => x.CreatedOnUtc);- var contactus = await PagedList<ContactUs>.Create(query, pageIndex, pageSize);- return contactus;- }+ //event notification+ await _mediator.EntityDeleted(contactus);+ }- /// <summary>- /// Gets a contactus item- /// </summary>- /// <param name="contactUsId">ContactUs item identifier</param>- /// <returns>ContactUs item</returns>- public virtual Task<ContactUs> GetContactUsById(string contactUsId)- {- return _contactusRepository.GetByIdAsync(contactUsId);- }+ /// <summary>+ /// Clears table+ /// </summary>+ public virtual async Task ClearTable()+ {+ await _contactusRepository.ClearAsync();+ }- /// <summary>- /// Inserts a contactus item- /// </summary>- /// <param name="contactus">ContactUs</param>- /// <returns>A contactus item</returns>- public virtual async Task InsertContactUs(ContactUs contactus)- {- ArgumentNullException.ThrowIfNull(contactus);+ /// <summary>+ /// Gets all contactUs items+ /// </summary>+ /// <param name="fromUtc">ContactUs item creation from; null to load all records</param>+ /// <param name="toUtc">ContactUs item creation to; null to load all records</param>+ /// <param name="email">email</param>+ /// <param name="vendorId">vendorId; null to load all records</param>+ /// <param name="customerId">customerId; null to load all records</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <returns>ContactUs items</returns>+ public virtual async Task<IPagedList<ContactUs>> GetAllContactUs(DateTime? fromUtc = null, DateTime? toUtc = null,+ string email = "", string vendorId = "", string customerId = "", string storeId = "",+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from c in _contactusRepository.Table+ select c;++ if (fromUtc.HasValue)+ query = query.Where(l => fromUtc.Value <= l.CreatedOnUtc);+ if (toUtc.HasValue)+ query = query.Where(l => toUtc.Value >= l.CreatedOnUtc);+ if (!string.IsNullOrEmpty(vendorId))+ query = query.Where(l => vendorId == l.VendorId);+ if (!string.IsNullOrEmpty(customerId))+ query = query.Where(l => customerId == l.CustomerId);+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(l => storeId == l.StoreId);++ if (!string.IsNullOrEmpty(email))+ query = query.Where(l => l.Email.ToLower().Contains(email.ToLower()));++ query = query.OrderByDescending(x => x.CreatedOnUtc);+ var contactus = await PagedList<ContactUs>.Create(query, pageIndex, pageSize);+ return contactus;+ }- await _contactusRepository.InsertAsync(contactus);+ /// <summary>+ /// Gets a contactus item+ /// </summary>+ /// <param name="contactUsId">ContactUs item identifier</param>+ /// <returns>ContactUs item</returns>+ public virtual Task<ContactUs> GetContactUsById(string contactUsId)+ {+ return _contactusRepository.GetByIdAsync(contactUsId);+ }- //event notification- await _mediator.EntityInserted(contactus);+ /// <summary>+ /// Inserts a contactus item+ /// </summary>+ /// <param name="contactus">ContactUs</param>+ /// <returns>A contactus item</returns>+ public virtual async Task InsertContactUs(ContactUs contactus)+ {+ ArgumentNullException.ThrowIfNull(contactus);- }+ await _contactusRepository.InsertAsync(contactus);+ //event notification+ await _mediator.EntityInserted(contactus);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.csindex 15b4e68ee..2ca1a416b 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs@@ -1,66 +1,66 @@using Grand.Business.Core.Interfaces.Marketing.Courses;-using Grand.Infrastructure.Extensions;-using Grand.Domain.Courses;using Grand.Data;+using Grand.Domain.Courses;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Courses+namespace Grand.Business.Marketing.Services.Courses;++public class CourseActionService : ICourseActionService{- public class CourseActionService : ICourseActionService+ private readonly IRepository<CourseAction> _courseActionRepository;+ private readonly IMediator _mediator;++ public CourseActionService(IRepository<CourseAction> courseActionRepository, IMediator mediator){- private readonly IRepository<CourseAction> _courseActionRepository;- private readonly IMediator _mediator;+ _courseActionRepository = courseActionRepository;+ _mediator = mediator;+ }- public CourseActionService(IRepository<CourseAction> courseActionRepository, IMediator mediator)- {- _courseActionRepository = courseActionRepository;- _mediator = mediator;- }+ public virtual Task<CourseAction> GetById(string id)+ {+ return _courseActionRepository.GetByIdAsync(id);+ }- public virtual Task<CourseAction> GetById(string id)- {- return _courseActionRepository.GetByIdAsync(id);- }- public virtual async Task<CourseAction> GetCourseAction(string customerId, string lessonId)- {- var query = from a in _courseActionRepository.Table- where a.CustomerId == customerId && a.LessonId == lessonId- select a;+ public virtual async Task<CourseAction> GetCourseAction(string customerId, string lessonId)+ {+ var query = from a in _courseActionRepository.Table+ where a.CustomerId == customerId && a.LessonId == lessonId+ select a;- return await Task.FromResult(query.FirstOrDefault());- }+ return await Task.FromResult(query.FirstOrDefault());+ }- public virtual async Task<bool> CustomerLessonCompleted(string customerId, string lessonId)- {- var query = await Task.FromResult((from a in _courseActionRepository.Table- where a.CustomerId == customerId && a.LessonId == lessonId- select a).FirstOrDefault());+ public virtual async Task<bool> CustomerLessonCompleted(string customerId, string lessonId)+ {+ var query = await Task.FromResult((from a in _courseActionRepository.Table+ where a.CustomerId == customerId && a.LessonId == lessonId+ select a).FirstOrDefault());- return query is { Finished: true };- }+ return query is { Finished: true };+ }- public virtual async Task<CourseAction> InsertAsync(CourseAction courseAction)- {- ArgumentNullException.ThrowIfNull(courseAction);+ public virtual async Task<CourseAction> InsertAsync(CourseAction courseAction)+ {+ ArgumentNullException.ThrowIfNull(courseAction);- await _courseActionRepository.InsertAsync(courseAction);+ await _courseActionRepository.InsertAsync(courseAction);- //event notification- await _mediator.EntityInserted(courseAction);+ //event notification+ await _mediator.EntityInserted(courseAction);- return courseAction;- }+ return courseAction;+ }- public virtual async Task<CourseAction> Update(CourseAction courseAction)- {- ArgumentNullException.ThrowIfNull(courseAction);+ public virtual async Task<CourseAction> Update(CourseAction courseAction)+ {+ ArgumentNullException.ThrowIfNull(courseAction);- await _courseActionRepository.UpdateAsync(courseAction);+ await _courseActionRepository.UpdateAsync(courseAction);- //event notification- await _mediator.EntityUpdated(courseAction);+ //event notification+ await _mediator.EntityUpdated(courseAction);- return courseAction;- }+ return courseAction;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.csindex a9f6d8632..34781e28c 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs@@ -1,71 +1,70 @@using Grand.Business.Core.Interfaces.Marketing.Courses;-using Grand.Infrastructure.Extensions;-using Grand.Domain.Courses;using Grand.Data;+using Grand.Domain.Courses;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Courses+namespace Grand.Business.Marketing.Services.Courses;++public class CourseLessonService : ICourseLessonService{- public class CourseLessonService : ICourseLessonService- {- private readonly IRepository<CourseLesson> _courseLessonRepository;- private readonly IMediator _mediator;+ private readonly IRepository<CourseLesson> _courseLessonRepository;+ private readonly IMediator _mediator;- public CourseLessonService(IRepository<CourseLesson> courseLessonRepository, IMediator mediator)- {- _courseLessonRepository = courseLessonRepository;- _mediator = mediator;- }+ public CourseLessonService(IRepository<CourseLesson> courseLessonRepository, IMediator mediator)+ {+ _courseLessonRepository = courseLessonRepository;+ _mediator = mediator;+ }- public virtual async Task Delete(CourseLesson courseLesson)- {- ArgumentNullException.ThrowIfNull(courseLesson);+ public virtual async Task Delete(CourseLesson courseLesson)+ {+ ArgumentNullException.ThrowIfNull(courseLesson);- await _courseLessonRepository.DeleteAsync(courseLesson);+ await _courseLessonRepository.DeleteAsync(courseLesson);- //event notification- await _mediator.EntityDeleted(courseLesson);- }+ //event notification+ await _mediator.EntityDeleted(courseLesson);+ }- public virtual async Task<IList<CourseLesson>> GetByCourseId(string courseId)- {- if (string.IsNullOrEmpty(courseId))- throw new ArgumentNullException(nameof(courseId));+ public virtual async Task<IList<CourseLesson>> GetByCourseId(string courseId)+ {+ if (string.IsNullOrEmpty(courseId))+ throw new ArgumentNullException(nameof(courseId));- var query = from c in _courseLessonRepository.Table- where c.CourseId == courseId- select c;+ var query = from c in _courseLessonRepository.Table+ where c.CourseId == courseId+ select c;- return await Task.FromResult(query.ToList());- }+ return await Task.FromResult(query.ToList());+ }- public virtual Task<CourseLesson> GetById(string id)- {- return _courseLessonRepository.GetByIdAsync(id);- }+ public virtual Task<CourseLesson> GetById(string id)+ {+ return _courseLessonRepository.GetByIdAsync(id);+ }- public virtual async Task<CourseLesson> Insert(CourseLesson courseLesson)- {- ArgumentNullException.ThrowIfNull(courseLesson);+ public virtual async Task<CourseLesson> Insert(CourseLesson courseLesson)+ {+ ArgumentNullException.ThrowIfNull(courseLesson);- await _courseLessonRepository.InsertAsync(courseLesson);+ await _courseLessonRepository.InsertAsync(courseLesson);- //event notification- await _mediator.EntityInserted(courseLesson);+ //event notification+ await _mediator.EntityInserted(courseLesson);- return courseLesson;- }+ return courseLesson;+ }- public virtual async Task<CourseLesson> Update(CourseLesson courseLesson)- {- ArgumentNullException.ThrowIfNull(courseLesson);+ public virtual async Task<CourseLesson> Update(CourseLesson courseLesson)+ {+ ArgumentNullException.ThrowIfNull(courseLesson);- await _courseLessonRepository.UpdateAsync(courseLesson);+ await _courseLessonRepository.UpdateAsync(courseLesson);- //event notification- await _mediator.EntityUpdated(courseLesson);+ //event notification+ await _mediator.EntityUpdated(courseLesson);- return courseLesson;- }+ return courseLesson;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.csindex 5d1a7f08c..771eae14d 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs@@ -1,68 +1,67 @@using Grand.Business.Core.Interfaces.Marketing.Courses;-using Grand.Infrastructure.Extensions;-using Grand.Domain.Courses;using Grand.Data;+using Grand.Domain.Courses;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Courses+namespace Grand.Business.Marketing.Services.Courses;++public class CourseLevelService : ICourseLevelService{- public class CourseLevelService : ICourseLevelService- {- private readonly IRepository<CourseLevel> _courseLevelRepository;- private readonly IMediator _mediator;+ private readonly IRepository<CourseLevel> _courseLevelRepository;+ private readonly IMediator _mediator;- public CourseLevelService(IRepository<CourseLevel> courseLevelRepository, IMediator mediator)- {- _courseLevelRepository = courseLevelRepository;- _mediator = mediator;- }+ public CourseLevelService(IRepository<CourseLevel> courseLevelRepository, IMediator mediator)+ {+ _courseLevelRepository = courseLevelRepository;+ _mediator = mediator;+ }- public virtual async Task Delete(CourseLevel courseLevel)- {- ArgumentNullException.ThrowIfNull(courseLevel);+ public virtual async Task Delete(CourseLevel courseLevel)+ {+ ArgumentNullException.ThrowIfNull(courseLevel);- await _courseLevelRepository.DeleteAsync(courseLevel);+ await _courseLevelRepository.DeleteAsync(courseLevel);- //event notification- await _mediator.EntityDeleted(courseLevel);- }+ //event notification+ await _mediator.EntityDeleted(courseLevel);+ }- public virtual async Task<IList<CourseLevel>> GetAll()- {- var query = from l in _courseLevelRepository.Table- orderby l.DisplayOrder- select l;+ public virtual async Task<IList<CourseLevel>> GetAll()+ {+ var query = from l in _courseLevelRepository.Table+ orderby l.DisplayOrder+ select l;- return await Task.FromResult(query.ToList());- }+ return await Task.FromResult(query.ToList());+ }- public virtual Task<CourseLevel> GetById(string id)- {- return _courseLevelRepository.GetByIdAsync(id);- }+ public virtual Task<CourseLevel> GetById(string id)+ {+ return _courseLevelRepository.GetByIdAsync(id);+ }- public virtual async Task<CourseLevel> Insert(CourseLevel courseLevel)- {- ArgumentNullException.ThrowIfNull(courseLevel);+ public virtual async Task<CourseLevel> Insert(CourseLevel courseLevel)+ {+ ArgumentNullException.ThrowIfNull(courseLevel);- await _courseLevelRepository.InsertAsync(courseLevel);+ await _courseLevelRepository.InsertAsync(courseLevel);- //event notification- await _mediator.EntityInserted(courseLevel);+ //event notification+ await _mediator.EntityInserted(courseLevel);- return courseLevel;- }+ return courseLevel;+ }- public virtual async Task<CourseLevel> Update(CourseLevel courseLevel)- {- ArgumentNullException.ThrowIfNull(courseLevel);+ public virtual async Task<CourseLevel> Update(CourseLevel courseLevel)+ {+ ArgumentNullException.ThrowIfNull(courseLevel);- await _courseLevelRepository.UpdateAsync(courseLevel);+ await _courseLevelRepository.UpdateAsync(courseLevel);- //event notification- await _mediator.EntityUpdated(courseLevel);+ //event notification+ await _mediator.EntityUpdated(courseLevel);- return courseLevel;- }+ return courseLevel;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.csindex 4ddc17cda..ad0f16cf6 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs@@ -1,118 +1,121 @@using Grand.Business.Core.Interfaces.Marketing.Courses;+using Grand.Data;using Grand.Domain;using Grand.Domain.Courses;using Grand.Domain.Customers;-using Grand.Data;using Grand.Domain.Orders;+using Grand.Domain.Payments;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Courses+namespace Grand.Business.Marketing.Services.Courses;++public class CourseService : ICourseService{- public class CourseService : ICourseService+ private readonly AccessControlConfig _accessControlConfig;+ private readonly IRepository<Course> _courseRepository;+ private readonly IMediator _mediator;+ private readonly IRepository<Order> _orderRepository;++ public CourseService(IRepository<Course> courseRepository,+ IRepository<Order> orderRepository,+ IMediator mediator,+ AccessControlConfig accessControlConfig){- private readonly IRepository<Course> _courseRepository;- private readonly IRepository<Order> _orderRepository;- private readonly IMediator _mediator;- private readonly AccessControlConfig _accessControlConfig;-- public CourseService(IRepository<Course> courseRepository,- IRepository<Order> orderRepository,- IMediator mediator,- AccessControlConfig accessControlConfig)- {- _courseRepository = courseRepository;- _orderRepository = orderRepository;- _mediator = mediator;- _accessControlConfig = accessControlConfig;- }+ _courseRepository = courseRepository;+ _orderRepository = orderRepository;+ _mediator = mediator;+ _accessControlConfig = accessControlConfig;+ }- public virtual async Task Delete(Course course)- {- ArgumentNullException.ThrowIfNull(course);+ public virtual async Task Delete(Course course)+ {+ ArgumentNullException.ThrowIfNull(course);- await _courseRepository.DeleteAsync(course);+ await _courseRepository.DeleteAsync(course);- //event notification- await _mediator.EntityDeleted(course);- }+ //event notification+ await _mediator.EntityDeleted(course);+ }- public virtual async Task<IPagedList<Course>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from q in _courseRepository.Table- orderby q.DisplayOrder- select q;+ public virtual async Task<IPagedList<Course>> GetAll(int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from q in _courseRepository.Table+ orderby q.DisplayOrder+ select q;- return await PagedList<Course>.Create(query, pageIndex, pageSize);- }- public virtual async Task<IList<Course>> GetByCustomer(Customer customer, string storeId)- {- var query = from c in _courseRepository.Table- select c;+ return await PagedList<Course>.Create(query, pageIndex, pageSize);+ }++ public virtual async Task<IList<Course>> GetByCustomer(Customer customer, string storeId)+ {+ var query = from c in _courseRepository.Table+ select c;- query = query.Where(c => c.Published);+ query = query.Where(c => c.Published);- if (!_accessControlConfig.IgnoreAcl || (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))+ if (!_accessControlConfig.IgnoreAcl ||+ (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations))+ {+ if (!_accessControlConfig.IgnoreAcl){- if (!_accessControlConfig.IgnoreAcl)- {- //ACL (access control list)- var allowedCustomerGroupsIds = customer.GetCustomerGroupIds();- query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;- }- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)- {- //Store acl- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;- }+ //ACL (access control list)+ var allowedCustomerGroupsIds = customer.GetCustomerGroupIds();+ query = from p in query+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;}- //courses without assigned product- var q1 = query.Where(x => string.IsNullOrEmpty(x.ProductId)).ToList();+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)+ //Store acl+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ select p;+ }- //get products from orders - paid/not deleted/for customer/store- var pl = _orderRepository.Table.Where(x => x.CustomerId == customer.Id && !x.Deleted- && x.PaymentStatusId == Domain.Payments.PaymentStatus.Paid- && x.StoreId == storeId).SelectMany(x => x.OrderItems, (p, pr) => pr.ProductId).Distinct().ToList();+ //courses without assigned product+ var q1 = query.Where(x => string.IsNullOrEmpty(x.ProductId)).ToList();- //courses assigned to products- var q2 = query.Where(x => pl.Contains(x.ProductId)).ToList();+ //get products from orders - paid/not deleted/for customer/store+ var pl = _orderRepository.Table.Where(x => x.CustomerId == customer.Id && !x.Deleted+ && x.PaymentStatusId ==+ PaymentStatus.Paid+ && x.StoreId == storeId)+ .SelectMany(x => x.OrderItems, (p, pr) => pr.ProductId).Distinct().ToList();- return await Task.FromResult(q1.Concat(q2).ToList());- }+ //courses assigned to products+ var q2 = query.Where(x => pl.Contains(x.ProductId)).ToList();- public virtual Task<Course> GetById(string id)- {- return _courseRepository.GetByIdAsync(id);- }+ return await Task.FromResult(q1.Concat(q2).ToList());+ }- public virtual async Task<Course> Insert(Course course)- {- ArgumentNullException.ThrowIfNull(course);+ public virtual Task<Course> GetById(string id)+ {+ return _courseRepository.GetByIdAsync(id);+ }- await _courseRepository.InsertAsync(course);+ public virtual async Task<Course> Insert(Course course)+ {+ ArgumentNullException.ThrowIfNull(course);- //event notification- await _mediator.EntityInserted(course);+ await _courseRepository.InsertAsync(course);- return course;- }+ //event notification+ await _mediator.EntityInserted(course);- public virtual async Task<Course> Update(Course course)- {- ArgumentNullException.ThrowIfNull(course);+ return course;+ }++ public virtual async Task<Course> Update(Course course)+ {+ ArgumentNullException.ThrowIfNull(course);- await _courseRepository.UpdateAsync(course);+ await _courseRepository.UpdateAsync(course);- //event notification- await _mediator.EntityUpdated(course);+ //event notification+ await _mediator.EntityUpdated(course);- return course;- }+ return course;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.csindex 752891a49..07f351a50 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs@@ -1,72 +1,71 @@using Grand.Business.Core.Interfaces.Marketing.Courses;-using Grand.Infrastructure.Extensions;-using Grand.Domain.Courses;using Grand.Data;+using Grand.Domain.Courses;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Courses+namespace Grand.Business.Marketing.Services.Courses;++public class CourseSubjectService : ICourseSubjectService{- public class CourseSubjectService : ICourseSubjectService- {- private readonly IRepository<CourseSubject> _courseSubjectRepository;- private readonly IMediator _mediator;+ private readonly IRepository<CourseSubject> _courseSubjectRepository;+ private readonly IMediator _mediator;- public CourseSubjectService(IRepository<CourseSubject> courseSubjectRepository, IMediator mediator)- {- _courseSubjectRepository = courseSubjectRepository;- _mediator = mediator;- }+ public CourseSubjectService(IRepository<CourseSubject> courseSubjectRepository, IMediator mediator)+ {+ _courseSubjectRepository = courseSubjectRepository;+ _mediator = mediator;+ }- public virtual async Task Delete(CourseSubject courseSubject)- {- ArgumentNullException.ThrowIfNull(courseSubject);+ public virtual async Task Delete(CourseSubject courseSubject)+ {+ ArgumentNullException.ThrowIfNull(courseSubject);- await _courseSubjectRepository.DeleteAsync(courseSubject);+ await _courseSubjectRepository.DeleteAsync(courseSubject);- //event notification- await _mediator.EntityDeleted(courseSubject);- }+ //event notification+ await _mediator.EntityDeleted(courseSubject);+ }- public virtual async Task<IList<CourseSubject>> GetByCourseId(string courseId)- {- if (string.IsNullOrEmpty(courseId))- throw new ArgumentNullException(nameof(courseId));+ public virtual async Task<IList<CourseSubject>> GetByCourseId(string courseId)+ {+ if (string.IsNullOrEmpty(courseId))+ throw new ArgumentNullException(nameof(courseId));- var query = from c in _courseSubjectRepository.Table- where c.CourseId == courseId- orderby c.DisplayOrder- select c;+ var query = from c in _courseSubjectRepository.Table+ where c.CourseId == courseId+ orderby c.DisplayOrder+ select c;- return await Task.FromResult(query.ToList());- }+ return await Task.FromResult(query.ToList());+ }- public virtual Task<CourseSubject> GetById(string id)- {- return _courseSubjectRepository.GetByIdAsync(id);- }+ public virtual Task<CourseSubject> GetById(string id)+ {+ return _courseSubjectRepository.GetByIdAsync(id);+ }- public virtual async Task<CourseSubject> Insert(CourseSubject courseSubject)- {- ArgumentNullException.ThrowIfNull(courseSubject);+ public virtual async Task<CourseSubject> Insert(CourseSubject courseSubject)+ {+ ArgumentNullException.ThrowIfNull(courseSubject);- await _courseSubjectRepository.InsertAsync(courseSubject);+ await _courseSubjectRepository.InsertAsync(courseSubject);- //event notification- await _mediator.EntityInserted(courseSubject);+ //event notification+ await _mediator.EntityInserted(courseSubject);- return courseSubject;- }+ return courseSubject;+ }- public virtual async Task<CourseSubject> Update(CourseSubject courseSubject)- {- ArgumentNullException.ThrowIfNull(courseSubject);+ public virtual async Task<CourseSubject> Update(CourseSubject courseSubject)+ {+ ArgumentNullException.ThrowIfNull(courseSubject);- await _courseSubjectRepository.UpdateAsync(courseSubject);+ await _courseSubjectRepository.UpdateAsync(courseSubject);- //event notification- await _mediator.EntityUpdated(courseSubject);+ //event notification+ await _mediator.EntityUpdated(courseSubject);- return courseSubject;- }+ return courseSubject;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.csindex 4195c7d34..b4095bcc0 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs@@ -1,57 +1,57 @@-using Grand.Business.Core.Interfaces.Marketing.Customers;-using Grand.Business.Core.Events.Marketing;-using Grand.Infrastructure;-using Grand.Domain.Customers;+using Grand.Business.Core.Events.Marketing;+using Grand.Business.Core.Interfaces.Marketing.Customers;using Grand.Data;+using Grand.Domain.Common;+using Grand.Domain.Customers;+using Grand.Infrastructure;using MediatR;-namespace Grand.Business.Marketing.Services.Customers+namespace Grand.Business.Marketing.Services.Customers;++public class CustomerCoordinatesService : ICustomerCoordinatesService{- public class CustomerCoordinatesService : ICustomerCoordinatesService+ private readonly IRepository<Customer> _customerRepository;+ private readonly IMediator _mediator;+ private readonly IWorkContext _workContext;++ public CustomerCoordinatesService(+ IRepository<Customer> customerRepository,+ IWorkContext workContext,+ IMediator mediator)+ {+ _customerRepository = customerRepository;+ _workContext = workContext;+ _mediator = mediator;+ }++ public Task<(double longitude, double latitude)> GetGeoCoordinate()+ {+ return GetGeoCoordinate(_workContext.CurrentCustomer);+ }++ public async Task<(double longitude, double latitude)> GetGeoCoordinate(Customer customer){- private readonly IRepository<Customer> _customerRepository;- private readonly IWorkContext _workContext;- private readonly IMediator _mediator;-- public CustomerCoordinatesService(- IRepository<Customer> customerRepository,- IWorkContext workContext,- IMediator mediator)- {- _customerRepository = customerRepository;- _workContext = workContext;- _mediator = mediator;- }-- public Task<(double longitude, double latitude)> GetGeoCoordinate()- {- return GetGeoCoordinate(_workContext.CurrentCustomer);- }-- public async Task<(double longitude, double latitude)> GetGeoCoordinate(Customer customer)- {- ArgumentNullException.ThrowIfNull(customer);-- if (customer.Coordinates == null)- await Task.FromResult((0, 0));-- return await Task.FromResult((customer.Coordinates!.X, customer.Coordinates!.Y));- }-- public async Task SaveGeoCoordinate(double longitude, double latitude)- {- await SaveGeoCoordinate(_workContext.CurrentCustomer, longitude, latitude);- }-- public async Task SaveGeoCoordinate(Customer customer, double longitude, double latitude)- {- customer.Coordinates = new Domain.Common.GeoCoordinates(longitude, latitude);-- //update customer- await _customerRepository.UpdateField(customer.Id, x => x.Coordinates, customer.Coordinates);-- //raise event- await _mediator.Publish(new CustomerCoordinatesEvent(customer));- }+ ArgumentNullException.ThrowIfNull(customer);++ if (customer.Coordinates == null)+ await Task.FromResult((0, 0));++ return await Task.FromResult((customer.Coordinates!.X, customer.Coordinates!.Y));+ }++ public async Task SaveGeoCoordinate(double longitude, double latitude)+ {+ await SaveGeoCoordinate(_workContext.CurrentCustomer, longitude, latitude);+ }++ public async Task SaveGeoCoordinate(Customer customer, double longitude, double latitude)+ {+ customer.Coordinates = new GeoCoordinates(longitude, latitude);++ //update customer+ await _customerRepository.UpdateField(customer.Id, x => x.Coordinates, customer.Coordinates);++ //raise event+ await _mediator.Publish(new CustomerCoordinatesEvent(customer));}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.csindex 9c0e596b1..d719be646 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs@@ -1,218 +1,226 @@using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Data;+using Grand.Domain;+using Grand.Domain.Customers;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Domain;-using Grand.Domain.Customers;-using Grand.Data;using MediatR;-namespace Grand.Business.Marketing.Services.Customers+namespace Grand.Business.Marketing.Services.Customers;++/// <summary>+/// Customer product service interface+/// </summary>+public class CustomerProductService : ICustomerProductService{+ private readonly ICacheBase _cacheBase;++ private readonly IRepository<CustomerProductPrice> _customerProductPriceRepository;+ private readonly IRepository<CustomerProduct> _customerProductRepository;+ private readonly IMediator _mediator;++ public CustomerProductService(+ IRepository<CustomerProductPrice> customerProductPriceRepository,+ IRepository<CustomerProduct> customerProductRepository,+ ICacheBase cacheBase,+ IMediator mediator)+ {+ _cacheBase = cacheBase;+ _customerProductPriceRepository = customerProductPriceRepository;+ _customerProductRepository = customerProductRepository;+ _mediator = mediator;+ }++ #region Customer Product Price+/// <summary>- /// Customer product service interface+ /// Gets a customer product price/// </summary>- public class CustomerProductService : ICustomerProductService+ /// <param name="id">Identifier</param>+ /// <returns>Customer product price</returns>+ public virtual Task<CustomerProductPrice> GetCustomerProductPriceById(string id){+ return _customerProductPriceRepository.GetByIdAsync(id);+ }- private readonly IRepository<CustomerProductPrice> _customerProductPriceRepository;- private readonly IRepository<CustomerProduct> _customerProductRepository;- private readonly ICacheBase _cacheBase;- private readonly IMediator _mediator;-- public CustomerProductService(- IRepository<CustomerProductPrice> customerProductPriceRepository,- IRepository<CustomerProduct> customerProductRepository,- ICacheBase cacheBase,- IMediator mediator)- {- _cacheBase = cacheBase;- _customerProductPriceRepository = customerProductPriceRepository;- _customerProductRepository = customerProductRepository;- _mediator = mediator;- }-- #region Customer Product Price-- /// <summary>- /// Gets a customer product price- /// </summary>- /// <param name="id">Identifier</param>- /// <returns>Customer product price</returns>- public virtual Task<CustomerProductPrice> GetCustomerProductPriceById(string id)- {- return _customerProductPriceRepository.GetByIdAsync(id);- }-- /// <summary>- /// Gets a price- /// </summary>- /// <param name="customerId">Customer Identifier</param>- /// <param name="productId">Product Identifier</param>- /// <returns>Customer product price</returns>- public virtual async Task<double?> GetPriceByCustomerProduct(string customerId, string productId)- {- var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerId, productId);- var productPrice = await _cacheBase.GetAsync(key, async () =>- {- var pp = await Task.FromResult(_customerProductPriceRepository.Table.FirstOrDefault(x => x.CustomerId == customerId && x.ProductId == productId));- return pp == null ? (null, false) : (pp, true);- });-- if (!productPrice.Item2)- return null;- return productPrice.pp.Price;- }-- /// <summary>- /// Inserts a customer product price- /// </summary>- /// <param name="customerProductPrice">Customer product price</param>- public virtual async Task InsertCustomerProductPrice(CustomerProductPrice customerProductPrice)+ /// <summary>+ /// Gets a price+ /// </summary>+ /// <param name="customerId">Customer Identifier</param>+ /// <param name="productId">Product Identifier</param>+ /// <returns>Customer product price</returns>+ public virtual async Task<double?> GetPriceByCustomerProduct(string customerId, string productId)+ {+ var key = string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerId, productId);+ var productPrice = await _cacheBase.GetAsync(key, async () =>{- ArgumentNullException.ThrowIfNull(customerProductPrice);+ var pp = await Task.FromResult(+ _customerProductPriceRepository.Table.FirstOrDefault(x =>+ x.CustomerId == customerId && x.ProductId == productId));+ return pp == null ? (null, false) : (pp, true);+ });++ if (!productPrice.Item2)+ return null;+ return productPrice.pp.Price;+ }- await _customerProductPriceRepository.InsertAsync(customerProductPrice);+ /// <summary>+ /// Inserts a customer product price+ /// </summary>+ /// <param name="customerProductPrice">Customer product price</param>+ public virtual async Task InsertCustomerProductPrice(CustomerProductPrice customerProductPrice)+ {+ ArgumentNullException.ThrowIfNull(customerProductPrice);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerProductPrice.CustomerId, customerProductPrice.ProductId));+ await _customerProductPriceRepository.InsertAsync(customerProductPrice);- //event notification- await _mediator.EntityInserted(customerProductPrice);- }+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID,+ customerProductPrice.CustomerId, customerProductPrice.ProductId));- /// <summary>- /// Updates the customer product price- /// </summary>- /// <param name="customerProductPrice">Customer product price</param>- public virtual async Task UpdateCustomerProductPrice(CustomerProductPrice customerProductPrice)- {- ArgumentNullException.ThrowIfNull(customerProductPrice);+ //event notification+ await _mediator.EntityInserted(customerProductPrice);+ }- await _customerProductPriceRepository.UpdateAsync(customerProductPrice);+ /// <summary>+ /// Updates the customer product price+ /// </summary>+ /// <param name="customerProductPrice">Customer product price</param>+ public virtual async Task UpdateCustomerProductPrice(CustomerProductPrice customerProductPrice)+ {+ ArgumentNullException.ThrowIfNull(customerProductPrice);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerProductPrice.CustomerId, customerProductPrice.ProductId));+ await _customerProductPriceRepository.UpdateAsync(customerProductPrice);- //event notification- await _mediator.EntityUpdated(customerProductPrice);- }+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID,+ customerProductPrice.CustomerId, customerProductPrice.ProductId));- /// <summary>- /// Delete a customer product price- /// </summary>- /// <param name="customerProductPrice">Customer product price</param>- public virtual async Task DeleteCustomerProductPrice(CustomerProductPrice customerProductPrice)- {- ArgumentNullException.ThrowIfNull(customerProductPrice);+ //event notification+ await _mediator.EntityUpdated(customerProductPrice);+ }- await _customerProductPriceRepository.DeleteAsync(customerProductPrice);+ /// <summary>+ /// Delete a customer product price+ /// </summary>+ /// <param name="customerProductPrice">Customer product price</param>+ public virtual async Task DeleteCustomerProductPrice(CustomerProductPrice customerProductPrice)+ {+ ArgumentNullException.ThrowIfNull(customerProductPrice);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID, customerProductPrice.CustomerId, customerProductPrice.ProductId));+ await _customerProductPriceRepository.DeleteAsync(customerProductPrice);- //event notification- await _mediator.EntityDeleted(customerProductPrice);- }+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMER_PRODUCT_PRICE_KEY_ID,+ customerProductPrice.CustomerId, customerProductPrice.ProductId));- public virtual async Task<IPagedList<CustomerProductPrice>> GetProductsPriceByCustomer(string customerId, int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from pp in _customerProductPriceRepository.Table- where pp.CustomerId == customerId- select pp;- return await PagedList<CustomerProductPrice>.Create(query, pageIndex, pageSize);- }-- #endregion-- #region Personalize products-- /// <summary>- /// Gets a customer product- /// </summary>- /// <param name="id">Identifier</param>- /// <returns>Customer product</returns>- public virtual async Task<CustomerProduct> GetCustomerProduct(string id)- {- return await _customerProductRepository.GetByIdAsync(id);- }-- /// <summary>- /// Gets a customer product- /// </summary>- /// <param name="customerId">Customer Identifier</param>- /// <param name="productId">Product Identifier</param>- /// <returns>Customer product</returns>- public virtual async Task<CustomerProduct> GetCustomerProduct(string customerId, string productId)- {- var query = from pp in _customerProductRepository.Table- where pp.CustomerId == customerId && pp.ProductId == productId- select pp;-- return await Task.FromResult(query.FirstOrDefault());- }-- /// <summary>- /// Insert a customer product- /// </summary>- /// <param name="customerProduct">Customer product</param>- public virtual async Task InsertCustomerProduct(CustomerProduct customerProduct)- {- ArgumentNullException.ThrowIfNull(customerProduct);+ //event notification+ await _mediator.EntityDeleted(customerProductPrice);+ }- await _customerProductRepository.InsertAsync(customerProduct);+ public virtual async Task<IPagedList<CustomerProductPrice>> GetProductsPriceByCustomer(string customerId,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from pp in _customerProductPriceRepository.Table+ where pp.CustomerId == customerId+ select pp;+ return await PagedList<CustomerProductPrice>.Create(query, pageIndex, pageSize);+ }- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY, customerProduct.CustomerId));+ #endregion- //event notification- await _mediator.EntityInserted(customerProduct);- }+ #region Personalize products- /// <summary>- /// Updates the customer product- /// </summary>- /// <param name="customerProduct">Customer product </param>- public virtual async Task UpdateCustomerProduct(CustomerProduct customerProduct)- {- ArgumentNullException.ThrowIfNull(customerProduct);+ /// <summary>+ /// Gets a customer product+ /// </summary>+ /// <param name="id">Identifier</param>+ /// <returns>Customer product</returns>+ public virtual async Task<CustomerProduct> GetCustomerProduct(string id)+ {+ return await _customerProductRepository.GetByIdAsync(id);+ }++ /// <summary>+ /// Gets a customer product+ /// </summary>+ /// <param name="customerId">Customer Identifier</param>+ /// <param name="productId">Product Identifier</param>+ /// <returns>Customer product</returns>+ public virtual async Task<CustomerProduct> GetCustomerProduct(string customerId, string productId)+ {+ var query = from pp in _customerProductRepository.Table+ where pp.CustomerId == customerId && pp.ProductId == productId+ select pp;++ return await Task.FromResult(query.FirstOrDefault());+ }++ /// <summary>+ /// Insert a customer product+ /// </summary>+ /// <param name="customerProduct">Customer product</param>+ public virtual async Task InsertCustomerProduct(CustomerProduct customerProduct)+ {+ ArgumentNullException.ThrowIfNull(customerProduct);- await _customerProductRepository.UpdateAsync(customerProduct);+ await _customerProductRepository.InsertAsync(customerProduct);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY, customerProduct.CustomerId));+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY,+ customerProduct.CustomerId));- //event notification- await _mediator.EntityUpdated(customerProduct);- }+ //event notification+ await _mediator.EntityInserted(customerProduct);+ }- /// <summary>- /// Delete a customer product- /// </summary>- /// <param name="customerProduct">Customer product</param>- public virtual async Task DeleteCustomerProduct(CustomerProduct customerProduct)- {- ArgumentNullException.ThrowIfNull(customerProduct);+ /// <summary>+ /// Updates the customer product+ /// </summary>+ /// <param name="customerProduct">Customer product </param>+ public virtual async Task UpdateCustomerProduct(CustomerProduct customerProduct)+ {+ ArgumentNullException.ThrowIfNull(customerProduct);++ await _customerProductRepository.UpdateAsync(customerProduct);- await _customerProductRepository.DeleteAsync(customerProduct);+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY,+ customerProduct.CustomerId));- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY, customerProduct.CustomerId));+ //event notification+ await _mediator.EntityUpdated(customerProduct);+ }- //event notification- await _mediator.EntityDeleted(customerProduct);- }+ /// <summary>+ /// Delete a customer product+ /// </summary>+ /// <param name="customerProduct">Customer product</param>+ public virtual async Task DeleteCustomerProduct(CustomerProduct customerProduct)+ {+ ArgumentNullException.ThrowIfNull(customerProduct);- public virtual async Task<IPagedList<CustomerProduct>> GetProductsByCustomer(string customerId, int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from pp in _customerProductRepository.Table- where pp.CustomerId == customerId- orderby pp.DisplayOrder- select pp;- return await PagedList<CustomerProduct>.Create(query, pageIndex, pageSize);- }+ await _customerProductRepository.DeleteAsync(customerProduct);- #endregion+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.PRODUCTS_CUSTOMER_PERSONAL_KEY,+ customerProduct.CustomerId));+ //event notification+ await _mediator.EntityDeleted(customerProduct);}-}++ public virtual async Task<IPagedList<CustomerProduct>> GetProductsByCustomer(string customerId, int pageIndex = 0,+ int pageSize = int.MaxValue)+ {+ var query = from pp in _customerProductRepository.Table+ where pp.CustomerId == customerId+ orderby pp.DisplayOrder+ select pp;+ return await PagedList<CustomerProduct>.Create(query, pageIndex, pageSize);+ }++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.csindex 859a1e7c3..fd3f872fe 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs@@ -1,284 +1,284 @@using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Data;+using Grand.Domain;+using Grand.Domain.Customers;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Domain;-using Grand.Domain.Customers;-using Grand.Data;using MediatR;-namespace Grand.Business.Marketing.Services.Customers+namespace Grand.Business.Marketing.Services.Customers;++/// <summary>+/// Customer tag service+/// </summary>+public class CustomerTagService : ICustomerTagService{+ #region Ctor+/// <summary>- /// Customer tag service+ /// Ctor/// </summary>- public class CustomerTagService : ICustomerTagService+ public CustomerTagService(IRepository<CustomerTag> customerTagRepository,+ IRepository<CustomerTagProduct> customerTagProductRepository,+ IRepository<Customer> customerRepository,+ IMediator mediator,+ ICacheBase cacheBase+ ){- #region Fields-- private readonly IRepository<CustomerTag> _customerTagRepository;- private readonly IRepository<CustomerTagProduct> _customerTagProductRepository;- private readonly IRepository<Customer> _customerRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- public CustomerTagService(IRepository<CustomerTag> customerTagRepository,- IRepository<CustomerTagProduct> customerTagProductRepository,- IRepository<Customer> customerRepository,- IMediator mediator,- ICacheBase cacheBase- )- {- _customerTagRepository = customerTagRepository;- _customerTagProductRepository = customerTagProductRepository;- _mediator = mediator;- _customerRepository = customerRepository;- _cacheBase = cacheBase;- }-- #endregion-- /// <summary>- /// Gets all customer for tag id- /// </summary>- /// <returns>Customers</returns>- public virtual async Task<IPagedList<Customer>> GetCustomersByTag(string customerTagId = "", int pageIndex = 0, int pageSize = 2147483647)- {- var query = from c in _customerRepository.Table- where c.CustomerTags.Contains(customerTagId)- select c;- return await PagedList<Customer>.Create(query, pageIndex, pageSize);- }-- /// <summary>- /// Delete a customer tag- /// </summary>- /// <param name="customerTag">Customer tag</param>- public virtual async Task DeleteCustomerTag(CustomerTag customerTag)- {- ArgumentNullException.ThrowIfNull(customerTag);+ _customerTagRepository = customerTagRepository;+ _customerTagProductRepository = customerTagProductRepository;+ _mediator = mediator;+ _customerRepository = customerRepository;+ _cacheBase = cacheBase;+ }- //update customer- await _customerRepository.Pull(string.Empty, x => x.CustomerTags, customerTag.Id);+ #endregion- //delete- await _customerTagRepository.DeleteAsync(customerTag);+ /// <summary>+ /// Gets all customer for tag id+ /// </summary>+ /// <returns>Customers</returns>+ public virtual async Task<IPagedList<Customer>> GetCustomersByTag(string customerTagId = "", int pageIndex = 0,+ int pageSize = 2147483647)+ {+ var query = from c in _customerRepository.Table+ where c.CustomerTags.Contains(customerTagId)+ select c;+ return await PagedList<Customer>.Create(query, pageIndex, pageSize);+ }- //event notification- await _mediator.EntityDeleted(customerTag);- }+ /// <summary>+ /// Delete a customer tag+ /// </summary>+ /// <param name="customerTag">Customer tag</param>+ public virtual async Task DeleteCustomerTag(CustomerTag customerTag)+ {+ ArgumentNullException.ThrowIfNull(customerTag);- /// <summary>- /// Gets all customer tags- /// </summary>- /// <returns>Customer tags</returns>- public virtual async Task<IList<CustomerTag>> GetAllCustomerTags()- {- return await Task.FromResult(_customerTagRepository.Table.ToList());- }-- /// <summary>- /// Gets customer tag- /// </summary>- /// <param name="customerTagId">Customer tag identifier</param>- /// <returns>Customer tag</returns>- public virtual Task<CustomerTag> GetCustomerTagById(string customerTagId)- {- return _customerTagRepository.GetByIdAsync(customerTagId);- }-- /// <summary>- /// Gets customer tag by name- /// </summary>- /// <param name="name">Customer tag name</param>- /// <returns>Customer tag</returns>- public virtual async Task<CustomerTag> GetCustomerTagByName(string name)- {- var query = from pt in _customerTagRepository.Table- where pt.Name == name- select pt;-- return await Task.FromResult(query.FirstOrDefault());- }-- /// <summary>- /// Gets customer tags search by name- /// </summary>- /// <param name="name">Customer tags name</param>- /// <returns>Customer tags</returns>- public virtual async Task<IList<CustomerTag>> GetCustomerTagsByName(string name)- {- var query = from pt in _customerTagRepository.Table- where pt.Name.ToLower().Contains(name.ToLower())- select pt;- return await Task.FromResult(query.ToList());- }+ //update customer+ await _customerRepository.Pull(string.Empty, x => x.CustomerTags, customerTag.Id);- /// <summary>- /// Inserts a customer tag- /// </summary>- /// <param name="customerTag">Customer tag</param>- public virtual async Task InsertCustomerTag(CustomerTag customerTag)- {- ArgumentNullException.ThrowIfNull(customerTag);+ //delete+ await _customerTagRepository.DeleteAsync(customerTag);- await _customerTagRepository.InsertAsync(customerTag);+ //event notification+ await _mediator.EntityDeleted(customerTag);+ }- //event notification- await _mediator.EntityInserted(customerTag);- }+ /// <summary>+ /// Gets all customer tags+ /// </summary>+ /// <returns>Customer tags</returns>+ public virtual async Task<IList<CustomerTag>> GetAllCustomerTags()+ {+ return await Task.FromResult(_customerTagRepository.Table.ToList());+ }- /// <summary>- /// Insert tag to a customer- /// </summary>- public virtual async Task InsertTagToCustomer(string customerTagId, string customerId)- {- await _customerRepository.AddToSet(customerId, x => x.CustomerTags, customerTagId);- }+ /// <summary>+ /// Gets customer tag+ /// </summary>+ /// <param name="customerTagId">Customer tag identifier</param>+ /// <returns>Customer tag</returns>+ public virtual Task<CustomerTag> GetCustomerTagById(string customerTagId)+ {+ return _customerTagRepository.GetByIdAsync(customerTagId);+ }- /// <summary>- /// Delete tag from a customer- /// </summary>- public virtual async Task DeleteTagFromCustomer(string customerTagId, string customerId)- {- await _customerRepository.Pull(customerId, x => x.CustomerTags, customerTagId);- }-- /// <summary>- /// Updates the customer tag- /// </summary>- /// <param name="customerTag">Customer tag</param>- public virtual async Task UpdateCustomerTag(CustomerTag customerTag)- {- ArgumentNullException.ThrowIfNull(customerTag);+ /// <summary>+ /// Gets customer tag by name+ /// </summary>+ /// <param name="name">Customer tag name</param>+ /// <returns>Customer tag</returns>+ public virtual async Task<CustomerTag> GetCustomerTagByName(string name)+ {+ var query = from pt in _customerTagRepository.Table+ where pt.Name == name+ select pt;- await _customerTagRepository.UpdateAsync(customerTag);+ return await Task.FromResult(query.FirstOrDefault());+ }- //event notification- await _mediator.EntityUpdated(customerTag);- }+ /// <summary>+ /// Gets customer tags search by name+ /// </summary>+ /// <param name="name">Customer tags name</param>+ /// <returns>Customer tags</returns>+ public virtual async Task<IList<CustomerTag>> GetCustomerTagsByName(string name)+ {+ var query = from pt in _customerTagRepository.Table+ where pt.Name.ToLower().Contains(name.ToLower())+ select pt;+ return await Task.FromResult(query.ToList());+ }- /// <summary>- /// Get number of customers- /// </summary>- /// <param name="customerTagId">Customer tag identifier</param>- /// <returns>Number of customers</returns>- public virtual async Task<int> GetCustomerCount(string customerTagId)- {- var count = _customerRepository.Table.- Count(x => x.CustomerTags.Contains(customerTagId));- if (count > 0)- return count;- return await Task.FromResult(0);- }-- #region Customer tag product--- /// <summary>- /// Gets customer tag products for customer tag- /// </summary>- /// <param name="customerTagId">Customer tag id</param>- /// <returns>Customer tag products</returns>- public virtual async Task<IList<CustomerTagProduct>> GetCustomerTagProducts(string customerTagId)- {- var key = string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagId);- return await _cacheBase.GetAsync(key, async () =>- {- var query = from cr in _customerTagProductRepository.Table- where cr.CustomerTagId == customerTagId- orderby cr.DisplayOrder- select cr;- return await Task.FromResult(query.ToList());- });- }-- /// <summary>- /// Gets customer tag products for customer tag- /// </summary>- /// <param name="customerTagId">Customer tag id</param>- /// <param name="productId">Product id</param>- /// <returns>Customer tag product</returns>- public virtual async Task<CustomerTagProduct> GetCustomerTagProduct(string customerTagId, string productId)+ /// <summary>+ /// Inserts a customer tag+ /// </summary>+ /// <param name="customerTag">Customer tag</param>+ public virtual async Task InsertCustomerTag(CustomerTag customerTag)+ {+ ArgumentNullException.ThrowIfNull(customerTag);++ await _customerTagRepository.InsertAsync(customerTag);++ //event notification+ await _mediator.EntityInserted(customerTag);+ }++ /// <summary>+ /// Insert tag to a customer+ /// </summary>+ public virtual async Task InsertTagToCustomer(string customerTagId, string customerId)+ {+ await _customerRepository.AddToSet(customerId, x => x.CustomerTags, customerTagId);+ }++ /// <summary>+ /// Delete tag from a customer+ /// </summary>+ public virtual async Task DeleteTagFromCustomer(string customerTagId, string customerId)+ {+ await _customerRepository.Pull(customerId, x => x.CustomerTags, customerTagId);+ }++ /// <summary>+ /// Updates the customer tag+ /// </summary>+ /// <param name="customerTag">Customer tag</param>+ public virtual async Task UpdateCustomerTag(CustomerTag customerTag)+ {+ ArgumentNullException.ThrowIfNull(customerTag);++ await _customerTagRepository.UpdateAsync(customerTag);++ //event notification+ await _mediator.EntityUpdated(customerTag);+ }++ /// <summary>+ /// Get number of customers+ /// </summary>+ /// <param name="customerTagId">Customer tag identifier</param>+ /// <returns>Number of customers</returns>+ public virtual async Task<int> GetCustomerCount(string customerTagId)+ {+ var count = _customerRepository.Table.Count(x => x.CustomerTags.Contains(customerTagId));+ if (count > 0)+ return count;+ return await Task.FromResult(0);+ }++ #region Fields++ private readonly IRepository<CustomerTag> _customerTagRepository;+ private readonly IRepository<CustomerTagProduct> _customerTagProductRepository;+ private readonly IRepository<Customer> _customerRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;++ #endregion++ #region Customer tag product++ /// <summary>+ /// Gets customer tag products for customer tag+ /// </summary>+ /// <param name="customerTagId">Customer tag id</param>+ /// <returns>Customer tag products</returns>+ public virtual async Task<IList<CustomerTagProduct>> GetCustomerTagProducts(string customerTagId)+ {+ var key = string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagId);+ return await _cacheBase.GetAsync(key, async () =>{var query = from cr in _customerTagProductRepository.Table- where cr.CustomerTagId == customerTagId && cr.ProductId == productId- orderby cr.DisplayOrder- select cr;- return await Task.FromResult(query.FirstOrDefault());- }-- /// <summary>- /// Gets customer tag product- /// </summary>- /// <param name="id">id</param>- /// <returns>Customer tag product</returns>- public virtual Task<CustomerTagProduct> GetCustomerTagProductById(string id)- {- return _customerTagProductRepository.GetByIdAsync(id);- }-- /// <summary>- /// Inserts a customer tag product- /// </summary>- /// <param name="customerTagProduct">Customer tag product</param>- public virtual async Task InsertCustomerTagProduct(CustomerTagProduct customerTagProduct)- {- ArgumentNullException.ThrowIfNull(customerTagProduct);+ where cr.CustomerTagId == customerTagId+ orderby cr.DisplayOrder+ select cr;+ return await Task.FromResult(query.ToList());+ });+ }- await _customerTagProductRepository.InsertAsync(customerTagProduct);+ /// <summary>+ /// Gets customer tag products for customer tag+ /// </summary>+ /// <param name="customerTagId">Customer tag id</param>+ /// <param name="productId">Product id</param>+ /// <returns>Customer tag product</returns>+ public virtual async Task<CustomerTagProduct> GetCustomerTagProduct(string customerTagId, string productId)+ {+ var query = from cr in _customerTagProductRepository.Table+ where cr.CustomerTagId == customerTagId && cr.ProductId == productId+ orderby cr.DisplayOrder+ select cr;+ return await Task.FromResult(query.FirstOrDefault());+ }- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagProduct.CustomerTagId));- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);+ /// <summary>+ /// Gets customer tag product+ /// </summary>+ /// <param name="id">id</param>+ /// <returns>Customer tag product</returns>+ public virtual Task<CustomerTagProduct> GetCustomerTagProductById(string id)+ {+ return _customerTagProductRepository.GetByIdAsync(id);+ }- //event notification- await _mediator.EntityInserted(customerTagProduct);- }+ /// <summary>+ /// Inserts a customer tag product+ /// </summary>+ /// <param name="customerTagProduct">Customer tag product</param>+ public virtual async Task InsertCustomerTagProduct(CustomerTagProduct customerTagProduct)+ {+ ArgumentNullException.ThrowIfNull(customerTagProduct);- /// <summary>- /// Updates the customer tag product- /// </summary>- /// <param name="customerTagProduct">Customer tag product</param>- public virtual async Task UpdateCustomerTagProduct(CustomerTagProduct customerTagProduct)- {- ArgumentNullException.ThrowIfNull(customerTagProduct);+ await _customerTagProductRepository.InsertAsync(customerTagProduct);- await _customerTagProductRepository.UpdateAsync(customerTagProduct);+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY,+ customerTagProduct.CustomerTagId));+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagProduct.CustomerTagId));- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);+ //event notification+ await _mediator.EntityInserted(customerTagProduct);+ }- //event notification- await _mediator.EntityUpdated(customerTagProduct);- }+ /// <summary>+ /// Updates the customer tag product+ /// </summary>+ /// <param name="customerTagProduct">Customer tag product</param>+ public virtual async Task UpdateCustomerTagProduct(CustomerTagProduct customerTagProduct)+ {+ ArgumentNullException.ThrowIfNull(customerTagProduct);- /// <summary>- /// Delete a customer tag product- /// </summary>- /// <param name="customerTagProduct">Customer tag product</param>- public virtual async Task DeleteCustomerTagProduct(CustomerTagProduct customerTagProduct)- {- ArgumentNullException.ThrowIfNull(customerTagProduct);+ await _customerTagProductRepository.UpdateAsync(customerTagProduct);- await _customerTagProductRepository.DeleteAsync(customerTagProduct);+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY,+ customerTagProduct.CustomerTagId));+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);- //clear cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY, customerTagProduct.CustomerTagId));- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);- //event notification- await _mediator.EntityDeleted(customerTagProduct);- }+ //event notification+ await _mediator.EntityUpdated(customerTagProduct);+ }++ /// <summary>+ /// Delete a customer tag product+ /// </summary>+ /// <param name="customerTagProduct">Customer tag product</param>+ public virtual async Task DeleteCustomerTagProduct(CustomerTagProduct customerTagProduct)+ {+ ArgumentNullException.ThrowIfNull(customerTagProduct);- #endregion+ await _customerTagProductRepository.DeleteAsync(customerTagProduct);+ //clear cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.CUSTOMERTAGPRODUCTS_ROLE_KEY,+ customerTagProduct.CustomerTagId));+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_CUSTOMER_TAG_PATTERN);+ //event notification+ await _mediator.EntityDeleted(customerTagProduct);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.csindex 269a0eaa5..4584ff9a4 100644--- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs@@ -1,93 +1,92 @@using Grand.Business.Core.Interfaces.Marketing.Documents;-using Grand.Infrastructure.Extensions;-using Grand.Domain;using Grand.Data;+using Grand.Domain;+using Grand.Domain.Common;using Grand.Domain.Documents;+using Grand.Infrastructure.Extensions;using MediatR;-using Grand.Domain.Common;-namespace Grand.Business.Marketing.Services.Documents-{- public class DocumentService : IDocumentService- {- private readonly IRepository<Document> _documentRepository;- private readonly IMediator _mediator;-- public DocumentService(IRepository<Document> documentRepository, IMediator mediator)- {- _documentRepository = documentRepository;- _mediator = mediator;- }+namespace Grand.Business.Marketing.Services.Documents;- public virtual async Task Delete(Document document)- {- ArgumentNullException.ThrowIfNull(document);+public class DocumentService : IDocumentService+{+ private readonly IRepository<Document> _documentRepository;+ private readonly IMediator _mediator;- await _documentRepository.DeleteAsync(document);+ public DocumentService(IRepository<Document> documentRepository, IMediator mediator)+ {+ _documentRepository = documentRepository;+ _mediator = mediator;+ }- //event notification- await _mediator.EntityDeleted(document);- }+ public virtual async Task Delete(Document document)+ {+ ArgumentNullException.ThrowIfNull(document);- public virtual async Task<IPagedList<Document>> GetAll(string name = "", string number = "", string email = "", string username = "",- Reference reference = Reference.None, string objectId = "", string seId = "", int status = -1, int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from d in _documentRepository.Table- select d;+ await _documentRepository.DeleteAsync(document);- if (!string.IsNullOrWhiteSpace(name))- query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(name.ToLower()));+ //event notification+ await _mediator.EntityDeleted(document);+ }- if (!string.IsNullOrWhiteSpace(number))- query = query.Where(m => m.Number != null && m.Number.ToLower().Contains(number.ToLower()));+ public virtual async Task<IPagedList<Document>> GetAll(string name = "", string number = "", string email = "",+ string username = "",+ Reference reference = Reference.None, string objectId = "", string seId = "", int status = -1,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from d in _documentRepository.Table+ select d;- if (!string.IsNullOrWhiteSpace(email))- query = query.Where(m => m.CustomerEmail == email.ToLower());+ if (!string.IsNullOrWhiteSpace(name))+ query = query.Where(m => m.Name != null && m.Name.ToLower().Contains(name.ToLower()));- if (!string.IsNullOrWhiteSpace(username))- query = query.Where(m => m.Username == username);+ if (!string.IsNullOrWhiteSpace(number))+ query = query.Where(m => m.Number != null && m.Number.ToLower().Contains(number.ToLower()));- if (!string.IsNullOrWhiteSpace(objectId))- query = query.Where(m => m.ObjectId == objectId);+ if (!string.IsNullOrWhiteSpace(email))+ query = query.Where(m => m.CustomerEmail == email.ToLower());- if (!string.IsNullOrWhiteSpace(seId))- query = query.Where(m => m.SeId == seId);+ if (!string.IsNullOrWhiteSpace(username))+ query = query.Where(m => m.Username == username);- if (reference > 0)- query = query.Where(m => m.ReferenceId == reference);+ if (!string.IsNullOrWhiteSpace(objectId))+ query = query.Where(m => m.ObjectId == objectId);- if (status >= 0)- query = query.Where(d => d.StatusId == (DocumentStatus)status);+ if (!string.IsNullOrWhiteSpace(seId))+ query = query.Where(m => m.SeId == seId);- return await PagedList<Document>.Create(query, pageIndex, pageSize);- }+ if (reference > 0)+ query = query.Where(m => m.ReferenceId == reference);+ if (status >= 0)+ query = query.Where(d => d.StatusId == (DocumentStatus)status);- public virtual Task<Document> GetById(string id)- {- return _documentRepository.GetByIdAsync(id);- }+ return await PagedList<Document>.Create(query, pageIndex, pageSize);+ }- public virtual async Task Insert(Document document)- {- ArgumentNullException.ThrowIfNull(document);- await _documentRepository.InsertAsync(document);+ public virtual Task<Document> GetById(string id)+ {+ return _documentRepository.GetByIdAsync(id);+ }- //event notification- await _mediator.EntityInserted(document);+ public virtual async Task Insert(Document document)+ {+ ArgumentNullException.ThrowIfNull(document);- }+ await _documentRepository.InsertAsync(document);- public virtual async Task Update(Document document)- {- ArgumentNullException.ThrowIfNull(document);+ //event notification+ await _mediator.EntityInserted(document);+ }- await _documentRepository.UpdateAsync(document);+ public virtual async Task Update(Document document)+ {+ ArgumentNullException.ThrowIfNull(document);- //event notification- await _mediator.EntityUpdated(document);+ await _documentRepository.UpdateAsync(document);- }+ //event notification+ await _mediator.EntityUpdated(document);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.csindex e71a17660..976a98c2c 100644--- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs@@ -1,64 +1,62 @@using Grand.Business.Core.Interfaces.Marketing.Documents;-using Grand.Infrastructure.Extensions;using Grand.Data;using Grand.Domain.Documents;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Documents-{- public class DocumentTypeService : IDocumentTypeService- {- private readonly IRepository<DocumentType> _documentTypeRepository;- private readonly IMediator _mediator;+namespace Grand.Business.Marketing.Services.Documents;- public DocumentTypeService(IRepository<DocumentType> documentTypeRepository, IMediator mediator)- {- _documentTypeRepository = documentTypeRepository;- _mediator = mediator;- }+public class DocumentTypeService : IDocumentTypeService+{+ private readonly IRepository<DocumentType> _documentTypeRepository;+ private readonly IMediator _mediator;- public virtual async Task Delete(DocumentType documentType)- {- ArgumentNullException.ThrowIfNull(documentType);+ public DocumentTypeService(IRepository<DocumentType> documentTypeRepository, IMediator mediator)+ {+ _documentTypeRepository = documentTypeRepository;+ _mediator = mediator;+ }- await _documentTypeRepository.DeleteAsync(documentType);+ public virtual async Task Delete(DocumentType documentType)+ {+ ArgumentNullException.ThrowIfNull(documentType);- //event notification- await _mediator.EntityDeleted(documentType);- }+ await _documentTypeRepository.DeleteAsync(documentType);- public virtual async Task<IList<DocumentType>> GetAll()- {- var query = from t in _documentTypeRepository.Table- orderby t.DisplayOrder- select t;- return await Task.FromResult(query.ToList());- }+ //event notification+ await _mediator.EntityDeleted(documentType);+ }- public virtual Task<DocumentType> GetById(string id)- {- return _documentTypeRepository.GetByIdAsync(id);- }+ public virtual async Task<IList<DocumentType>> GetAll()+ {+ var query = from t in _documentTypeRepository.Table+ orderby t.DisplayOrder+ select t;+ return await Task.FromResult(query.ToList());+ }- public virtual async Task Insert(DocumentType documentType)- {- ArgumentNullException.ThrowIfNull(documentType);+ public virtual Task<DocumentType> GetById(string id)+ {+ return _documentTypeRepository.GetByIdAsync(id);+ }- await _documentTypeRepository.InsertAsync(documentType);+ public virtual async Task Insert(DocumentType documentType)+ {+ ArgumentNullException.ThrowIfNull(documentType);- //event notification- await _mediator.EntityInserted(documentType);- }+ await _documentTypeRepository.InsertAsync(documentType);- public virtual async Task Update(DocumentType documentType)- {- ArgumentNullException.ThrowIfNull(documentType);+ //event notification+ await _mediator.EntityInserted(documentType);+ }- await _documentTypeRepository.UpdateAsync(documentType);+ public virtual async Task Update(DocumentType documentType)+ {+ ArgumentNullException.ThrowIfNull(documentType);- //event notification- await _mediator.EntityUpdated(documentType);+ await _documentTypeRepository.UpdateAsync(documentType);- }+ //event notification+ await _mediator.EntityUpdated(documentType);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.csindex ceb63d43f..6a356189e 100644--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs@@ -2,376 +2,371 @@ using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Marketing.Newsletters;using Grand.Business.Marketing.Extensions;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Messages;using Grand.Infrastructure.Extensions;using Grand.SharedKernel;using Grand.SharedKernel.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Newsletters+namespace Grand.Business.Marketing.Services.Newsletters;++/// <summary>+/// Newsletter subscription service+/// </summary>+public class NewsLetterSubscriptionService : INewsLetterSubscriptionService{- /// <summary>- /// Newsletter subscription service- /// </summary>- public class NewsLetterSubscriptionService : INewsLetterSubscriptionService- {- #region Fields+ #region Ctor- private readonly IMediator _mediator;- private readonly IRepository<NewsLetterSubscription> _subscriptionRepository;- private readonly IHistoryService _historyService;+ public NewsLetterSubscriptionService(+ IRepository<NewsLetterSubscription> subscriptionRepository,+ IMediator mediator,+ IHistoryService historyService)+ {+ _subscriptionRepository = subscriptionRepository;+ _mediator = mediator;+ _historyService = historyService;+ }- #endregion+ #endregion- #region Ctor+ #region Utilities- public NewsLetterSubscriptionService(- IRepository<NewsLetterSubscription> subscriptionRepository,- IMediator mediator,- IHistoryService historyService)+ /// <summary>+ /// Publishes the subscription event.+ /// </summary>+ /// <param name="email">The email.</param>+ /// <param name="isSubscribe">if set to <c>true</c> [is subscribe].</param>+ /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>+ private async Task PublishSubscriptionEvent(string email, bool isSubscribe, bool publishSubscriptionEvents)+ {+ if (publishSubscriptionEvents){- _subscriptionRepository = subscriptionRepository;- _mediator = mediator;- _historyService = historyService;+ if (isSubscribe)+ await _mediator.PublishNewsletterSubscribe(email);+ else+ await _mediator.PublishNewsletterUnsubscribe(email);}+ }- #endregion+ #endregion- #region Utilities+ #region Fields- /// <summary>- /// Publishes the subscription event.- /// </summary>- /// <param name="email">The email.</param>- /// <param name="isSubscribe">if set to <c>true</c> [is subscribe].</param>- /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>- private async Task PublishSubscriptionEvent(string email, bool isSubscribe, bool publishSubscriptionEvents)- {- if (publishSubscriptionEvents)- {- if (isSubscribe)- {- await _mediator.PublishNewsletterSubscribe(email);- }- else- {- await _mediator.PublishNewsletterUnsubscribe(email);- }- }- }- #endregion+ private readonly IMediator _mediator;+ private readonly IRepository<NewsLetterSubscription> _subscriptionRepository;+ private readonly IHistoryService _historyService;- #region Methods+ #endregion- /// <summary>- /// Inserts a newsletter subscription- /// </summary>- /// <param name="newsLetterSubscription">NewsLetter subscription</param>- /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>- public virtual async Task InsertNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true)- {- ArgumentNullException.ThrowIfNull(newsLetterSubscription);+ #region Methods- //Handle e-mail- newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email);+ /// <summary>+ /// Inserts a newsletter subscription+ /// </summary>+ /// <param name="newsLetterSubscription">NewsLetter subscription</param>+ /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>+ public virtual async Task InsertNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription,+ bool publishSubscriptionEvents = true)+ {+ ArgumentNullException.ThrowIfNull(newsLetterSubscription);- //Persist- await _subscriptionRepository.InsertAsync(newsLetterSubscription);+ //Handle e-mail+ newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email);- //Publish the subscription event- if (newsLetterSubscription.Active)- {- await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);- }+ //Persist+ await _subscriptionRepository.InsertAsync(newsLetterSubscription);- //save history- await newsLetterSubscription.SaveHistory<NewsLetterSubscription>(_historyService);+ //Publish the subscription event+ if (newsLetterSubscription.Active)+ await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);- //Publish event- await _mediator.EntityInserted(newsLetterSubscription);- }+ //save history+ await newsLetterSubscription.SaveHistory<NewsLetterSubscription>(_historyService);- /// <summary>- /// Updates a newsletter subscription- /// </summary>- /// <param name="newsLetterSubscription">NewsLetter subscription</param>- /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>- public virtual async Task UpdateNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true)- {- ArgumentNullException.ThrowIfNull(newsLetterSubscription);+ //Publish event+ await _mediator.EntityInserted(newsLetterSubscription);+ }++ /// <summary>+ /// Updates a newsletter subscription+ /// </summary>+ /// <param name="newsLetterSubscription">NewsLetter subscription</param>+ /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>+ public virtual async Task UpdateNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription,+ bool publishSubscriptionEvents = true)+ {+ ArgumentNullException.ThrowIfNull(newsLetterSubscription);- //Handle e-mail- newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email);+ //Handle e-mail+ newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email);- //get previous newsLetterSubscription record- var prevNewsLetterSubscription = await _subscriptionRepository.GetByIdAsync(newsLetterSubscription.Id);+ //get previous newsLetterSubscription record+ var prevNewsLetterSubscription = await _subscriptionRepository.GetByIdAsync(newsLetterSubscription.Id);- //Persist- await _subscriptionRepository.UpdateAsync(newsLetterSubscription);+ //Persist+ await _subscriptionRepository.UpdateAsync(newsLetterSubscription);- //save history- await newsLetterSubscription.SaveHistory<NewsLetterSubscription>(_historyService);+ //save history+ await newsLetterSubscription.SaveHistory<NewsLetterSubscription>(_historyService);- //Publish the un/subscribe event- if (prevNewsLetterSubscription != null)+ //Publish the un/subscribe event+ if (prevNewsLetterSubscription != null)+ switch (newsLetterSubscription.Active){- switch (newsLetterSubscription.Active)- {- case true when !prevNewsLetterSubscription.Active:- await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);- break;- case false when prevNewsLetterSubscription.Active:- await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);- break;- }+ case true when !prevNewsLetterSubscription.Active:+ await PublishSubscriptionEvent(newsLetterSubscription.Email, true, publishSubscriptionEvents);+ break;+ case false when prevNewsLetterSubscription.Active:+ await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);+ break;}- //Publish event- await _mediator.EntityUpdated(newsLetterSubscription);- }- /// <summary>- /// Deletes a newsletter subscription- /// </summary>- /// <param name="newsLetterSubscription">NewsLetter subscription</param>- /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>- public virtual async Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true)- {- ArgumentNullException.ThrowIfNull(newsLetterSubscription);+ //Publish event+ await _mediator.EntityUpdated(newsLetterSubscription);+ }- await _subscriptionRepository.DeleteAsync(newsLetterSubscription);+ /// <summary>+ /// Deletes a newsletter subscription+ /// </summary>+ /// <param name="newsLetterSubscription">NewsLetter subscription</param>+ /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param>+ public virtual async Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription,+ bool publishSubscriptionEvents = true)+ {+ ArgumentNullException.ThrowIfNull(newsLetterSubscription);- //Publish the unsubscribe event- await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);+ await _subscriptionRepository.DeleteAsync(newsLetterSubscription);- //event notification- await _mediator.EntityDeleted(newsLetterSubscription);- }+ //Publish the unsubscribe event+ await PublishSubscriptionEvent(newsLetterSubscription.Email, false, publishSubscriptionEvents);- /// <summary>- /// Gets a newsletter subscription by newsletter subscription identifier- /// </summary>- /// <param name="newsLetterSubscriptionId">The newsletter subscription identifier</param>- /// <returns>NewsLetter subscription</returns>- public virtual Task<NewsLetterSubscription> GetNewsLetterSubscriptionById(string newsLetterSubscriptionId)- {- return _subscriptionRepository.GetByIdAsync(newsLetterSubscriptionId);- }+ //event notification+ await _mediator.EntityDeleted(newsLetterSubscription);+ }- /// <summary>- /// Gets a newsletter subscription by newsletter subscription GUID- /// </summary>- /// <param name="newsLetterSubscriptionGuid">The newsletter subscription GUID</param>- /// <returns>NewsLetter subscription</returns>- public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid)- {- if (newsLetterSubscriptionGuid == Guid.Empty) return null;+ /// <summary>+ /// Gets a newsletter subscription by newsletter subscription identifier+ /// </summary>+ /// <param name="newsLetterSubscriptionId">The newsletter subscription identifier</param>+ /// <returns>NewsLetter subscription</returns>+ public virtual Task<NewsLetterSubscription> GetNewsLetterSubscriptionById(string newsLetterSubscriptionId)+ {+ return _subscriptionRepository.GetByIdAsync(newsLetterSubscriptionId);+ }- var newsLetterSubscriptions = from nls in _subscriptionRepository.Table- where nls.NewsLetterSubscriptionGuid == newsLetterSubscriptionGuid- select nls;+ /// <summary>+ /// Gets a newsletter subscription by newsletter subscription GUID+ /// </summary>+ /// <param name="newsLetterSubscriptionGuid">The newsletter subscription GUID</param>+ /// <returns>NewsLetter subscription</returns>+ public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid)+ {+ if (newsLetterSubscriptionGuid == Guid.Empty) return null;- return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());- }+ var newsLetterSubscriptions = from nls in _subscriptionRepository.Table+ where nls.NewsLetterSubscriptionGuid == newsLetterSubscriptionGuid+ select nls;- /// <summary>- /// Gets a newsletter subscription by email and store ID- /// </summary>- /// <param name="email">The newsletter subscription email</param>- /// <param name="storeId">Store identifier</param>- /// <returns>NewsLetter subscription</returns>- public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByEmailAndStoreId(string email, string storeId)- {- if (!CommonHelper.IsValidEmail(email))- return null;+ return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());+ }- email = email.Trim();+ /// <summary>+ /// Gets a newsletter subscription by email and store ID+ /// </summary>+ /// <param name="email">The newsletter subscription email</param>+ /// <param name="storeId">Store identifier</param>+ /// <returns>NewsLetter subscription</returns>+ public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByEmailAndStoreId(string email,+ string storeId)+ {+ if (!CommonHelper.IsValidEmail(email))+ return null;- var newsLetterSubscriptions = from nls in _subscriptionRepository.Table- where nls.Email.ToLower() == email.ToLower() && nls.StoreId == storeId- select nls;+ email = email.Trim();- return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());- }+ var newsLetterSubscriptions = from nls in _subscriptionRepository.Table+ where nls.Email.ToLower() == email.ToLower() && nls.StoreId == storeId+ select nls;- /// <summary>- /// Gets a newsletter subscription by customer ID- /// </summary>- /// <param name="customerId">Customer identifier</param>- /// <returns>NewsLetter subscription</returns>- public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByCustomerId(string customerId)- {- if (string.IsNullOrEmpty(customerId))- return null;+ return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());+ }- var newsLetterSubscriptions = from nls in _subscriptionRepository.Table- where nls.CustomerId == customerId- select nls;+ /// <summary>+ /// Gets a newsletter subscription by customer ID+ /// </summary>+ /// <param name="customerId">Customer identifier</param>+ /// <returns>NewsLetter subscription</returns>+ public virtual async Task<NewsLetterSubscription> GetNewsLetterSubscriptionByCustomerId(string customerId)+ {+ if (string.IsNullOrEmpty(customerId))+ return null;- return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());- }+ var newsLetterSubscriptions = from nls in _subscriptionRepository.Table+ where nls.CustomerId == customerId+ select nls;- /// <summary>- /// Gets the newsletter subscription list- /// </summary>- /// <param name="email">Email to search or string. Empty to load all records.</param>- /// <param name="storeId">Store identifier. "" to load all records.</param>- /// <param name="isActive">Value indicating whether subscriber record should be active or not; null to load all records</param>- /// <param name="categoryIds"></param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>NewsLetterSubscription entities</returns>- public virtual async Task<IPagedList<NewsLetterSubscription>> GetAllNewsLetterSubscriptions(string email = null,- string storeId = "", bool? isActive = null, string[] categoryIds = null,- int pageIndex = 0, int pageSize = int.MaxValue)+ return await Task.FromResult(newsLetterSubscriptions.FirstOrDefault());+ }++ /// <summary>+ /// Gets the newsletter subscription list+ /// </summary>+ /// <param name="email">Email to search or string. Empty to load all records.</param>+ /// <param name="storeId">Store identifier. "" to load all records.</param>+ /// <param name="isActive">Value indicating whether subscriber record should be active or not; null to load all records</param>+ /// <param name="categoryIds"></param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <returns>NewsLetterSubscription entities</returns>+ public virtual async Task<IPagedList<NewsLetterSubscription>> GetAllNewsLetterSubscriptions(string email = null,+ string storeId = "", bool? isActive = null, string[] categoryIds = null,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ //do not filter by customer group+ var query = from p in _subscriptionRepository.Table+ select p;++ if (!string.IsNullOrEmpty(email))+ query = query.Where(nls => nls.Email.ToLower().Contains(email.ToLower()));+ if (!string.IsNullOrEmpty(storeId))+ query = query.Where(nls => nls.StoreId == storeId);+ if (isActive.HasValue)+ query = query.Where(nls => nls.Active == isActive.Value);+ if (categoryIds is { Length: > 0 })+ query = query.Where(c => c.Categories.Any(x => categoryIds.Contains(x)));++ query = query.OrderBy(nls => nls.Email);+ return await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);+ }++ /// <summary>+ /// Export newsletter subscribers to TXT+ /// </summary>+ /// <param name="subscriptions">Subscriptions</param>+ /// <returns>Result in TXT (string) format</returns>+ public virtual string ExportNewsletterSubscribersToTxt(IList<NewsLetterSubscription> subscriptions)+ {+ ArgumentNullException.ThrowIfNull(subscriptions);++ const char separator = ',';+ var sb = new StringBuilder();+ foreach (var subscription in subscriptions){- //do not filter by customer group- var query = from p in _subscriptionRepository.Table- select p;-- if (!string.IsNullOrEmpty(email))- query = query.Where(nls => nls.Email.ToLower().Contains(email.ToLower()));- if (!string.IsNullOrEmpty(storeId))- query = query.Where(nls => nls.StoreId == storeId);- if (isActive.HasValue)- query = query.Where(nls => nls.Active == isActive.Value);- if (categoryIds is { Length: > 0 })- query = query.Where(c => c.Categories.Any(x => categoryIds.Contains(x)));-- query = query.OrderBy(nls => nls.Email);- return await PagedList<NewsLetterSubscription>.Create(query, pageIndex, pageSize);+ sb.Append(subscription.Email);+ sb.Append(separator);+ sb.Append(subscription.Active);+ sb.Append(separator);+ sb.Append(subscription.CreatedOnUtc.ToString("dd.MM.yyyy HH:mm:ss"));+ sb.Append(separator);+ sb.Append(subscription.StoreId);+ sb.Append(separator);+ sb.Append(string.Join(';', subscription.Categories));+ sb.Append(Environment.NewLine); //new line}- /// <summary>- /// Export newsletter subscribers to TXT- /// </summary>- /// <param name="subscriptions">Subscriptions</param>- /// <returns>Result in TXT (string) format</returns>- public virtual string ExportNewsletterSubscribersToTxt(IList<NewsLetterSubscription> subscriptions)- {- ArgumentNullException.ThrowIfNull(subscriptions);+ return sb.ToString();+ }- const char separator = ',';- var sb = new StringBuilder();- foreach (var subscription in subscriptions)+ /// <summary>+ /// Import newsletter subscribers from TXT file+ /// </summary>+ /// <param name="stream">Stream</param>+ /// <param name="currentStoreId">Current store ident</param>+ /// <returns>Number of imported subscribers</returns>+ public virtual async Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId)+ {+ var count = 0;+ using var reader = new StreamReader(stream);+ while (!reader.EndOfStream)+ {+ var line = await reader.ReadLineAsync();+ if (string.IsNullOrWhiteSpace(line))+ continue;+ var tmp = line.Split(',');++ string email;+ var isActive = true;+ var categories = new List<string>();+ var isCategories = false;+ var storeId = currentStoreId;+ switch (tmp.Length){- sb.Append(subscription.Email);- sb.Append(separator);- sb.Append(subscription.Active);- sb.Append(separator);- sb.Append(subscription.CreatedOnUtc.ToString("dd.MM.yyyy HH:mm:ss"));- sb.Append(separator);- sb.Append(subscription.StoreId);- sb.Append(separator);- sb.Append(string.Join(';', subscription.Categories));- sb.Append(Environment.NewLine); //new line+ //parse+ case 1:+ //"email" only+ email = tmp[0].Trim();+ break;+ case 2:+ //"email" and "active" fields specified+ email = tmp[0].Trim();+ isActive = bool.Parse(tmp[1].Trim());+ break;+ case 3:+ //"email" and "active" and "storeId" fields specified+ email = tmp[0].Trim();+ isActive = bool.Parse(tmp[1].Trim());+ storeId = tmp[2].Trim();+ break;+ case 4:+ //"email" and "active" and "storeId" and categories fields specified+ email = tmp[0].Trim();+ isActive = bool.Parse(tmp[1].Trim());+ storeId = tmp[2].Trim();+ try+ {+ var items = tmp[3].Trim().Split(';').ToList();+ categories.AddRange(items.Where(item => !string.IsNullOrEmpty(item)));+ isCategories = true;+ }+ catch+ {+ // ignored+ }++ break;+ default:+ throw new GrandException("Wrong file format");}- return sb.ToString();++ //import+ await ImportSubscription(email, storeId, isActive, isCategories, categories);++ count++;}- /// <summary>- /// Import newsletter subscribers from TXT file- /// </summary>- /// <param name="stream">Stream</param>- /// <param name="currentStoreId">Current store ident</param>- /// <returns>Number of imported subscribers</returns>- public virtual async Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId)+ return count;+ }++ protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool isCategories,+ List<string> categories)+ {+ var subscription = await GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);+ if (subscription != null){- var count = 0;- using var reader = new StreamReader(stream);- while (!reader.EndOfStream)+ subscription.Email = email;+ subscription.Active = isActive;+ if (isCategories){- var line = await reader.ReadLineAsync();- if (string.IsNullOrWhiteSpace(line))- continue;- var tmp = line.Split(',');-- string email;- var isActive = true;- var categories = new List<string>();- var isCategories = false;- var storeId = currentStoreId;- switch (tmp.Length)- {- //parse- case 1:- //"email" only- email = tmp[0].Trim();- break;- case 2:- //"email" and "active" fields specified- email = tmp[0].Trim();- isActive = bool.Parse(tmp[1].Trim());- break;- case 3:- //"email" and "active" and "storeId" fields specified- email = tmp[0].Trim();- isActive = bool.Parse(tmp[1].Trim());- storeId = tmp[2].Trim();- break;- case 4:- //"email" and "active" and "storeId" and categories fields specified- email = tmp[0].Trim();- isActive = bool.Parse(tmp[1].Trim());- storeId = tmp[2].Trim();- try- {- var items = tmp[3].Trim().Split(';').ToList();- categories.AddRange(items.Where(item => !string.IsNullOrEmpty(item)));- isCategories = true;- }- catch- {- // ignored- }- break;- default:- throw new GrandException("Wrong file format");- }-- //import- await ImportSubscription(email, storeId, isActive, isCategories, categories);-- count++;+ subscription.Categories.Clear();+ foreach (var item in categories) subscription.Categories.Add(item);}- return count;+ await UpdateNewsLetterSubscription(subscription);}-- protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool isCategories, List<string> categories)+ else{- var subscription = await GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);- if (subscription != null)- {- subscription.Email = email;- subscription.Active = isActive;- if (isCategories)- {- subscription.Categories.Clear();- foreach (var item in categories)- {- subscription.Categories.Add(item);- }- }- await UpdateNewsLetterSubscription(subscription);- }- else- {- subscription = new NewsLetterSubscription {- Active = isActive,- Email = email,- StoreId = storeId,- NewsLetterSubscriptionGuid = Guid.NewGuid()- };- foreach (var item in categories)- {- subscription.Categories.Add(item);- }- await InsertNewsLetterSubscription(subscription);- }+ subscription = new NewsLetterSubscription {+ Active = isActive,+ Email = email,+ StoreId = storeId,+ NewsLetterSubscriptionGuid = Guid.NewGuid()+ };+ foreach (var item in categories) subscription.Categories.Add(item);+ await InsertNewsLetterSubscription(subscription);}-- #endregion}++ #endregion}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.csindex 73b5e7dfb..a6d24002b 100644--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs@@ -4,102 +4,102 @@ using Grand.Domain.Messages;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Marketing.Services.Newsletters+namespace Grand.Business.Marketing.Services.Newsletters;++public class NewsletterCategoryService : INewsletterCategoryService{- public class NewsletterCategoryService : INewsletterCategoryService+ #region Ctor++ public NewsletterCategoryService(IRepository<NewsletterCategory> newsletterCategoryRepository, IMediator mediator)+ {+ _newsletterCategoryRepository = newsletterCategoryRepository;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<NewsletterCategory> _newsletterCategoryRepository;+ private readonly IMediator _mediator;++ #endregion++ #region Methods++ /// <summary>+ /// Inserts a newsletter category+ /// </summary>+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task InsertNewsletterCategory(NewsletterCategory newsletterCategory)+ {+ ArgumentNullException.ThrowIfNull(newsletterCategory);++ await _newsletterCategoryRepository.InsertAsync(newsletterCategory);++ //event notification+ await _mediator.EntityInserted(newsletterCategory);+ }++ /// <summary>+ /// Updates a newsletter category+ /// </summary>+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task UpdateNewsletterCategory(NewsletterCategory newsletterCategory)+ {+ ArgumentNullException.ThrowIfNull(newsletterCategory);++ await _newsletterCategoryRepository.UpdateAsync(newsletterCategory);++ //event notification+ await _mediator.EntityUpdated(newsletterCategory);+ }++ /// <summary>+ /// Deleted a newsletter category+ /// </summary>+ /// <param name="newsletterCategory">NewsletterCategory</param>+ public virtual async Task DeleteNewsletterCategory(NewsletterCategory newsletterCategory)+ {+ ArgumentNullException.ThrowIfNull(newsletterCategory);++ await _newsletterCategoryRepository.DeleteAsync(newsletterCategory);++ //event notification+ await _mediator.EntityDeleted(newsletterCategory);+ }++ /// <summary>+ /// Gets a newsletter by category+ /// </summary>+ /// <param name="id">newsletter category</param>+ /// <returns>NewsletterCategory</returns>+ public virtual Task<NewsletterCategory> GetNewsletterCategoryById(string id)+ {+ return _newsletterCategoryRepository.GetByIdAsync(id);+ }++ /// <summary>+ /// Gets all newsletter categories+ /// </summary>+ /// <returns>NewsletterCategories</returns>+ public virtual async Task<IList<NewsletterCategory>> GetAllNewsletterCategory(){- #region Fields-- private readonly IRepository<NewsletterCategory> _newsletterCategoryRepository;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- public NewsletterCategoryService(IRepository<NewsletterCategory> newsletterCategoryRepository, IMediator mediator)- {- _newsletterCategoryRepository = newsletterCategoryRepository;- _mediator = mediator;- }- #endregion-- #region Methods- /// <summary>- /// Inserts a newsletter category- /// </summary>- /// <param name="newsletterCategory">NewsletterCategory</param>- public virtual async Task InsertNewsletterCategory(NewsletterCategory newsletterCategory)- {- ArgumentNullException.ThrowIfNull(newsletterCategory);-- await _newsletterCategoryRepository.InsertAsync(newsletterCategory);-- //event notification- await _mediator.EntityInserted(newsletterCategory);- }-- /// <summary>- /// Updates a newsletter category- /// </summary>- /// <param name="newsletterCategory">NewsletterCategory</param>- public virtual async Task UpdateNewsletterCategory(NewsletterCategory newsletterCategory)- {- ArgumentNullException.ThrowIfNull(newsletterCategory);-- await _newsletterCategoryRepository.UpdateAsync(newsletterCategory);-- //event notification- await _mediator.EntityUpdated(newsletterCategory);-- }-- /// <summary>- /// Deleted a newsletter category- /// </summary>- /// <param name="newsletterCategory">NewsletterCategory</param>- public virtual async Task DeleteNewsletterCategory(NewsletterCategory newsletterCategory)- {- ArgumentNullException.ThrowIfNull(newsletterCategory);-- await _newsletterCategoryRepository.DeleteAsync(newsletterCategory);-- //event notification- await _mediator.EntityDeleted(newsletterCategory);-- }-- /// <summary>- /// Gets a newsletter by category- /// </summary>- /// <param name="id">newsletter category</param>- /// <returns>NewsletterCategory</returns>- public virtual Task<NewsletterCategory> GetNewsletterCategoryById(string id)- {- return _newsletterCategoryRepository.GetByIdAsync(id);- }-- /// <summary>- /// Gets all newsletter categories- /// </summary>- /// <returns>NewsletterCategories</returns>- public virtual async Task<IList<NewsletterCategory>> GetAllNewsletterCategory()- {- return await Task.FromResult(_newsletterCategoryRepository.Table.ToList());- }-- /// <summary>- /// Gets all newsletter categories by store- /// </summary>- /// <returns>NewsletterCategories</returns>- public virtual async Task<IList<NewsletterCategory>> GetNewsletterCategoriesByStore(string storeId)- {- var query = from p in _newsletterCategoryRepository.Table- where !p.LimitedToStores || p.Stores.Contains(storeId)- orderby p.DisplayOrder- select p;- return await Task.FromResult(query.ToList());- }- #endregion+ return await Task.FromResult(_newsletterCategoryRepository.Table.ToList());}-}++ /// <summary>+ /// Gets all newsletter categories by store+ /// </summary>+ /// <returns>NewsletterCategories</returns>+ public virtual async Task<IList<NewsletterCategory>> GetNewsletterCategoriesByStore(string storeId)+ {+ var query = from p in _newsletterCategoryRepository.Table+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ orderby p.DisplayOrder+ select p;+ return await Task.FromResult(query.ToList());+ }++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.csindex 5dda9f085..4321aa64a 100644--- a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs+++ b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs@@ -1,7 +1,7 @@using Grand.Business.Core.Interfaces.Marketing.PushNotifications;using Grand.Business.Marketing.Utilities;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.PushNotifications;using Grand.Infrastructure.Extensions;using MediatR;@@ -9,232 +9,228 @@ using Microsoft.Extensions.Logging;using System.Net.Http;using System.Text.Json;-namespace Grand.Business.Marketing.Services.PushNotifications+namespace Grand.Business.Marketing.Services.PushNotifications;++public class PushNotificationsService : IPushNotificationsService{- public class PushNotificationsService : IPushNotificationsService+ private const string FcmUrl = "https://fcm.googleapis.com/fcm/send";+ private readonly HttpClient _httpClient;+ private readonly ILogger<PushNotificationsService> _logger;+ private readonly IMediator _mediator;+ private readonly IRepository<PushMessage> _pushMessagesRepository;+ private readonly PushNotificationsSettings _pushNotificationsSettings;+ private readonly IRepository<PushRegistration> _pushRegistrationRepository;++ public PushNotificationsService(+ IRepository<PushRegistration> pushRegistrationRepository,+ IRepository<PushMessage> pushMessagesRepository,+ IMediator mediator,+ PushNotificationsSettings pushNotificationsSettings,+ ILogger<PushNotificationsService> logger,+ HttpClient httpClient){- private readonly IRepository<PushRegistration> _pushRegistrationRepository;- private readonly IRepository<PushMessage> _pushMessagesRepository;- private readonly IMediator _mediator;- private readonly PushNotificationsSettings _pushNotificationsSettings;- private readonly ILogger<PushNotificationsService> _logger;- private readonly HttpClient _httpClient;-- private const string FcmUrl = "https://fcm.googleapis.com/fcm/send";-- public PushNotificationsService(- IRepository<PushRegistration> pushRegistrationRepository,- IRepository<PushMessage> pushMessagesRepository,- IMediator mediator,- PushNotificationsSettings pushNotificationsSettings,- ILogger<PushNotificationsService> logger,- HttpClient httpClient)- {- _pushRegistrationRepository = pushRegistrationRepository;- _pushMessagesRepository = pushMessagesRepository;- _mediator = mediator;- _pushNotificationsSettings = pushNotificationsSettings;- _logger = logger;- _httpClient = httpClient;- }+ _pushRegistrationRepository = pushRegistrationRepository;+ _pushMessagesRepository = pushMessagesRepository;+ _mediator = mediator;+ _pushNotificationsSettings = pushNotificationsSettings;+ _logger = logger;+ _httpClient = httpClient;+ }- /// <summary>- /// Inserts push receiver- /// </summary>- /// <param name="registration"></param>- public virtual async Task InsertPushReceiver(PushRegistration registration)- {- await _pushRegistrationRepository.InsertAsync(registration);+ /// <summary>+ /// Inserts push receiver+ /// </summary>+ /// <param name="registration"></param>+ public virtual async Task InsertPushReceiver(PushRegistration registration)+ {+ await _pushRegistrationRepository.InsertAsync(registration);- await _mediator.EntityInserted(registration);- }+ await _mediator.EntityInserted(registration);+ }- /// <summary>- /// Deletes push receiver- /// </summary>- /// <param name="registration"></param>- public virtual async Task DeletePushReceiver(PushRegistration registration)- {- await _pushRegistrationRepository.DeleteAsync(registration);- await _mediator.EntityDeleted(registration);- }+ /// <summary>+ /// Deletes push receiver+ /// </summary>+ /// <param name="registration"></param>+ public virtual async Task DeletePushReceiver(PushRegistration registration)+ {+ await _pushRegistrationRepository.DeleteAsync(registration);+ await _mediator.EntityDeleted(registration);+ }- /// <summary>- /// Gets push receiver- /// </summary>- /// <param name="customerId"></param>- public virtual async Task<PushRegistration> GetPushReceiverByCustomerId(string customerId)- {- return await Task.FromResult(_pushRegistrationRepository.Table.FirstOrDefault(x => x.CustomerId == customerId));- }+ /// <summary>+ /// Gets push receiver+ /// </summary>+ /// <param name="customerId"></param>+ public virtual async Task<PushRegistration> GetPushReceiverByCustomerId(string customerId)+ {+ return await Task.FromResult(_pushRegistrationRepository.Table.FirstOrDefault(x => x.CustomerId == customerId));+ }- /// <summary>- /// Updates push receiver- /// </summary>- /// <param name="registration"></param>- public virtual async Task UpdatePushReceiver(PushRegistration registration)- {- await _pushRegistrationRepository.UpdateAsync(registration);- await _mediator.EntityUpdated(registration);- }+ /// <summary>+ /// Updates push receiver+ /// </summary>+ /// <param name="registration"></param>+ public virtual async Task UpdatePushReceiver(PushRegistration registration)+ {+ await _pushRegistrationRepository.UpdateAsync(registration);+ await _mediator.EntityUpdated(registration);+ }- /// <summary>- /// Gets all push receivers- /// </summary>- public virtual async Task<List<PushRegistration>> GetPushReceivers()- {- return await Task.FromResult(_pushRegistrationRepository.Table.Where(x => x.Allowed).ToList());- }+ /// <summary>+ /// Gets all push receivers+ /// </summary>+ public virtual async Task<List<PushRegistration>> GetPushReceivers()+ {+ return await Task.FromResult(_pushRegistrationRepository.Table.Where(x => x.Allowed).ToList());+ }- /// <summary>- /// Gets number of customers that accepted push notifications permission popup- /// </summary>- public virtual async Task<int> GetAllowedReceivers()- {- return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => x.Allowed));- }+ /// <summary>+ /// Gets number of customers that accepted push notifications permission popup+ /// </summary>+ public virtual async Task<int> GetAllowedReceivers()+ {+ return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => x.Allowed));+ }- /// <summary>- /// Gets number of customers that denied push notifications permission popup- /// </summary>- public virtual async Task<int> GetDeniedReceivers()- {- return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => !x.Allowed));- }+ /// <summary>+ /// Gets number of customers that denied push notifications permission popup+ /// </summary>+ public virtual async Task<int> GetDeniedReceivers()+ {+ return await Task.FromResult(_pushRegistrationRepository.Table.Count(x => !x.Allowed));+ }- /// <summary>- /// Inserts push message- /// </summary>- /// <param name="message"></param>- public virtual async Task InsertPushMessage(PushMessage message)- {- await _pushMessagesRepository.InsertAsync(message);- await _mediator.EntityInserted(message);- }+ /// <summary>+ /// Inserts push message+ /// </summary>+ /// <param name="message"></param>+ public virtual async Task InsertPushMessage(PushMessage message)+ {+ await _pushMessagesRepository.InsertAsync(message);+ await _mediator.EntityInserted(message);+ }- /// <summary>- /// Gets all push messages- /// </summary>- public virtual async Task<IPagedList<PushMessage>> GetPushMessages(int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = _pushMessagesRepository.Table.OrderByDescending(x => x.SentOn);- return await Task.FromResult(new PagedList<PushMessage>(query, pageIndex, pageSize));- }+ /// <summary>+ /// Gets all push messages+ /// </summary>+ public virtual async Task<IPagedList<PushMessage>> GetPushMessages(int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = _pushMessagesRepository.Table.OrderByDescending(x => x.SentOn);+ return await Task.FromResult(new PagedList<PushMessage>(query, pageIndex, pageSize));+ }- /// <summary>- /// Gets all push receivers- /// </summary>- public virtual async Task<IPagedList<PushRegistration>> GetPushReceivers(int pageIndex = 0, int pageSize = int.MaxValue)+ /// <summary>+ /// Gets all push receivers+ /// </summary>+ public virtual async Task<IPagedList<PushRegistration>> GetPushReceivers(int pageIndex = 0,+ int pageSize = int.MaxValue)+ {+ var query = _pushRegistrationRepository.Table.OrderByDescending(x => x.RegisteredOn);+ return await Task.FromResult(new PagedList<PushRegistration>(query, pageIndex, pageSize));+ }++ /// <summary>+ /// Sends push notification to all receivers+ /// </summary>+ /// <param name="title"></param>+ /// <param name="text"></param>+ /// <param name="pictureUrl"></param>+ /// <param name="registrationIds"></param>+ /// <param name="clickUrl"></param>+ /// <returns>Bool indicating whether message was sent successfully and string result to display</returns>+ public virtual async Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl,+ string clickUrl, List<string> registrationIds = null)+ {+ var ids = new List<string>();++ if (registrationIds != null && registrationIds.Any()){- var query = _pushRegistrationRepository.Table.OrderByDescending(x => x.RegisteredOn);- return await Task.FromResult(new PagedList<PushRegistration>(query, pageIndex, pageSize));+ ids = registrationIds;}-- /// <summary>- /// Sends push notification to all receivers- /// </summary>- /// <param name="title"></param>- /// <param name="text"></param>- /// <param name="pictureUrl"></param>- /// <param name="registrationIds"></param>- /// <param name="clickUrl"></param>- /// <returns>Bool indicating whether message was sent successfully and string result to display</returns>- public virtual async Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl, string clickUrl, List<string> registrationIds = null)+ else{- var ids = new List<string>();+ var receivers = await GetPushReceivers();+ if (!receivers.Any()) return (false, "Admin.PushNotifications.Error.NoReceivers");- if (registrationIds != null && registrationIds.Any())- {- ids = registrationIds;- }- else+ const int batchSize = 1000;+ for (var batch = 0;+ batch <= Math.Round((double)(receivers.Count / batchSize), 0, MidpointRounding.ToEven);+ batch++){- var receivers = await GetPushReceivers();- if (!receivers.Any())- {- return (false, "Admin.PushNotifications.Error.NoReceivers");- }-- const int batchSize = 1000;- for (var batch = 0; batch <= Math.Round((double)(receivers.Count / batchSize), 0, MidpointRounding.ToEven); batch++)- {- var t = receivers.Skip(batch * batchSize).Take(batchSize);- foreach (var receiver in receivers.Where(receiver => !ids.Contains(receiver.Token)))- {- ids.Add(receiver.Token);- }- }+ var t = receivers.Skip(batch * batchSize).Take(batchSize);+ foreach (var receiver in receivers.Where(receiver => !ids.Contains(receiver.Token)))+ ids.Add(receiver.Token);}+ }- var data = new- {- registration_ids = ids,- notification = new- {- body = text,- title,- icon = pictureUrl,- click_action = clickUrl- }- };-- var json = JsonSerializer.Serialize(data);- try- {- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, FcmUrl);- httpRequest.Headers.Add("Authorization", $"key = {_pushNotificationsSettings.PrivateApiKey}");- httpRequest.Headers.Add("Sender", $"id = {_pushNotificationsSettings.SenderId}");-- httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");-- using var response = await _httpClient.SendAsync(httpRequest);- var responseString = await response.Content.ReadAsStringAsync();- if (!response.IsSuccessStatusCode)- {- _logger.LogError("Error occured while sending push notification {ResponseString}", responseString);- return (false, responseString);- }-- var responseMessage = JsonSerializer.Deserialize<JsonResponse>(responseString);- if (responseMessage == null) return (false, "PushNotifications.ResponseMessage.Empty");-- await InsertPushMessage(new PushMessage {- NumberOfReceivers = responseMessage.success,- SentOn = DateTime.UtcNow,- Text = text,- Title = title- });-- return (true, "Admin.PushNotifications.MessageSent");+ var data = new {+ registration_ids = ids,+ notification = new {+ body = text,+ title,+ icon = pictureUrl,+ click_action = clickUrl}- catch (Exception ex)+ };++ var json = JsonSerializer.Serialize(data);+ try+ {+ using var httpRequest = new HttpRequestMessage(HttpMethod.Post, FcmUrl);+ httpRequest.Headers.Add("Authorization", $"key = {_pushNotificationsSettings.PrivateApiKey}");+ httpRequest.Headers.Add("Sender", $"id = {_pushNotificationsSettings.SenderId}");++ httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");++ using var response = await _httpClient.SendAsync(httpRequest);+ var responseString = await response.Content.ReadAsStringAsync();+ if (!response.IsSuccessStatusCode){- return (false, ex.Message);+ _logger.LogError("Error occured while sending push notification {ResponseString}", responseString);+ return (false, responseString);}- }- /// <summary>- /// Sends push notification to specified customer- /// </summary>- /// <param name="title"></param>- /// <param name="text"></param>- /// <param name="pictureUrl"></param>- /// <param name="customerId"></param>- /// <param name="clickUrl"></param>- /// <returns>Bool indicating whether message was sent successfully and string result to display</returns>- public virtual async Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl, string customerId, string clickUrl)- {- return await SendPushNotification(title, text, pictureUrl, clickUrl,- [GetPushReceiverByCustomerId(customerId).Id.ToString()]);- }+ var responseMessage = JsonSerializer.Deserialize<JsonResponse>(responseString);+ if (responseMessage == null) return (false, "PushNotifications.ResponseMessage.Empty");- /// <summary>- /// Gets all push receivers- /// </summary>- /// <param name="id">Ident</param>- public virtual Task<PushRegistration> GetPushReceiver(string id)+ await InsertPushMessage(new PushMessage {+ NumberOfReceivers = responseMessage.success,+ SentOn = DateTime.UtcNow,+ Text = text,+ Title = title+ });++ return (true, "Admin.PushNotifications.MessageSent");+ }+ catch (Exception ex){- return _pushRegistrationRepository.GetByIdAsync(id);+ return (false, ex.Message);}}-}++ /// <summary>+ /// Sends push notification to specified customer+ /// </summary>+ /// <param name="title"></param>+ /// <param name="text"></param>+ /// <param name="pictureUrl"></param>+ /// <param name="customerId"></param>+ /// <param name="clickUrl"></param>+ /// <returns>Bool indicating whether message was sent successfully and string result to display</returns>+ public virtual async Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl,+ string customerId, string clickUrl)+ {+ return await SendPushNotification(title, text, pictureUrl, clickUrl,+ [GetPushReceiverByCustomerId(customerId).Id.ToString()]);+ }++ /// <summary>+ /// Gets all push receivers+ /// </summary>+ /// <param name="id">Ident</param>+ public virtual Task<PushRegistration> GetPushReceiver(string id)+ {+ return _pushRegistrationRepository.GetByIdAsync(id);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs b/src/Business/Grand.Business.Marketing/Startup/StartupApplication.csindex cad2805e3..70a329a3a 100644--- a/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Marketing/Startup/StartupApplication.cs@@ -18,55 +18,56 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Business.Marketing.Startup+namespace Grand.Business.Marketing.Startup;++public class StartupApplication : IStartupApplication{- public class StartupApplication : IStartupApplication+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- RegisterCoursesService(services);- RegisterDocumentsService(services);- RegisterCommon(services);- RegisterCustomer(services);- }- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {+ RegisterCoursesService(services);+ RegisterDocumentsService(services);+ RegisterCommon(services);+ RegisterCustomer(services);+ }- }- public int Priority => 100;- public bool BeforeConfigure => false;+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ }- private void RegisterCustomer(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<ICustomerTagService, CustomerTagService>();- serviceCollection.AddScoped<ICustomerProductService, CustomerProductService>();- serviceCollection.AddScoped<ICustomerCoordinatesService, CustomerCoordinatesService>();- }- private void RegisterCommon(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<IContactAttributeParser, ContactAttributeParser>();- serviceCollection.AddScoped<IContactAttributeService, ContactAttributeService>();- serviceCollection.AddScoped<IContactUsService, ContactUsService>();- serviceCollection.AddScoped<INewsLetterSubscriptionService, NewsLetterSubscriptionService>();- serviceCollection.AddScoped<INewsletterCategoryService, NewsletterCategoryService>();- serviceCollection.AddScoped<ICampaignService, CampaignService>();+ public int Priority => 100;+ public bool BeforeConfigure => false;- serviceCollection.AddHttpClient<IPushNotificationsService, PushNotificationsService>();+ private void RegisterCustomer(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<ICustomerTagService, CustomerTagService>();+ serviceCollection.AddScoped<ICustomerProductService, CustomerProductService>();+ serviceCollection.AddScoped<ICustomerCoordinatesService, CustomerCoordinatesService>();+ }- }- private void RegisterCoursesService(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<ICourseActionService, CourseActionService>();- serviceCollection.AddScoped<ICourseLessonService, CourseLessonService>();- serviceCollection.AddScoped<ICourseLevelService, CourseLevelService>();- serviceCollection.AddScoped<ICourseService, CourseService>();- serviceCollection.AddScoped<ICourseSubjectService, CourseSubjectService>();- }- private void RegisterDocumentsService(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<IDocumentTypeService, DocumentTypeService>();- serviceCollection.AddScoped<IDocumentService, DocumentService>();+ private void RegisterCommon(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<IContactAttributeParser, ContactAttributeParser>();+ serviceCollection.AddScoped<IContactAttributeService, ContactAttributeService>();+ serviceCollection.AddScoped<IContactUsService, ContactUsService>();+ serviceCollection.AddScoped<INewsLetterSubscriptionService, NewsLetterSubscriptionService>();+ serviceCollection.AddScoped<INewsletterCategoryService, NewsletterCategoryService>();+ serviceCollection.AddScoped<ICampaignService, CampaignService>();- }+ serviceCollection.AddHttpClient<IPushNotificationsService, PushNotificationsService>();+ }++ private void RegisterCoursesService(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<ICourseActionService, CourseActionService>();+ serviceCollection.AddScoped<ICourseLessonService, CourseLessonService>();+ serviceCollection.AddScoped<ICourseLevelService, CourseLevelService>();+ serviceCollection.AddScoped<ICourseService, CourseService>();+ serviceCollection.AddScoped<ICourseSubjectService, CourseSubjectService>();+ }++ private void RegisterDocumentsService(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<IDocumentTypeService, DocumentTypeService>();+ serviceCollection.AddScoped<IDocumentService, DocumentService>();}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs b/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.csindex f0158dcd7..f035c96db 100644--- a/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs+++ b/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs@@ -1,16 +1,15 @@-namespace Grand.Business.Marketing.Utilities-{- public class JsonResponse- {- public long multicast_id { get; set; }- public int success { get; set; }- public int failure { get; set; }- public int canonical_ids { get; set; }- public Message[] results { get; set; }- }+namespace Grand.Business.Marketing.Utilities;- public class Message- {- public string message_id { get; set; }- }+public class JsonResponse+{+ public long multicast_id { get; set; }+ public int success { get; set; }+ public int failure { get; set; }+ public int canonical_ids { get; set; }+ public Message[] results { get; set; }}++public class Message+{+ public string message_id { get; set; }+}\ No newline at end of file