Skip to content

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.

Grand.Business.Customer - Code cleanup (ReSharper)

support229f44ae6db6
diff --git a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs
index e61cb391b..734beabf5 100644
--- a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs
+++ b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs
@@ -1,62 +1,61 @@
using Grand.Business.Core.Commands.Customers;
-using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Events.Customers;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
using MediatR;
-using Grand.Business.Core.Interfaces.Common.Directory;
-namespace Grand.Business.Customers.Commands.Handlers
+namespace Grand.Business.Customers.Commands.Handlers;
+
+public class ActiveVendorCommandHandler : IRequestHandler<ActiveVendorCommand, bool>
{
- public class ActiveVendorCommandHandler : IRequestHandler<ActiveVendorCommand, bool>
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IMediator _mediator;
+ private readonly IVendorService _vendorService;
+
+ public ActiveVendorCommandHandler(
+ IVendorService vendorService,
+ ICustomerService customerService,
+ IGroupService groupService,
+ IMediator mediator)
{
- private readonly IVendorService _vendorService;
- private readonly ICustomerService _customerService;
- private readonly IGroupService _groupService;
- private readonly IMediator _mediator;
-
- public ActiveVendorCommandHandler(
- IVendorService vendorService,
- ICustomerService customerService,
- IGroupService groupService,
- IMediator mediator)
- {
- _vendorService = vendorService;
- _customerService = customerService;
- _groupService = groupService;
- _mediator = mediator;
- }
+ _vendorService = vendorService;
+ _customerService = customerService;
+ _groupService = groupService;
+ _mediator = mediator;
+ }
- public async Task<bool> Handle(ActiveVendorCommand request, CancellationToken cancellationToken)
- {
- //update vendor - set active
- request.Vendor.Active = request.Active;
- await _vendorService.UpdateVendor(request.Vendor);
+ public async Task<bool> Handle(ActiveVendorCommand request, CancellationToken cancellationToken)
+ {
+ //update vendor - set active
+ request.Vendor.Active = request.Active;
+ await _vendorService.UpdateVendor(request.Vendor);
- //assign vendor group for customers
- var vendorGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Vendors);
+ //assign vendor group for customers
+ var vendorGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Vendors);
- foreach (var item in request.CustomerIds)
+ foreach (var item in request.CustomerIds)
+ {
+ var customer = await _customerService.GetCustomerById(item);
+ if (customer is not { Deleted: false, Active: true } || customer.IsSystemAccount() ||
+ await _groupService.IsAdmin(customer)) continue;
+ if (vendorGroup == null) continue;
+ if (request.Active)
{
- var customer = await _customerService.GetCustomerById(item);
- if (customer is not { Deleted: false, Active: true } || customer.IsSystemAccount() ||
- await _groupService.IsAdmin(customer)) continue;
- if (vendorGroup == null) continue;
- if (request.Active)
- {
- if (!await _groupService.IsVendor(customer))
- await _customerService.InsertCustomerGroupInCustomer(vendorGroup, item);
- }
- else
- {
- if (await _groupService.IsVendor(customer))
- await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, item);
- }
+ if (!await _groupService.IsVendor(customer))
+ await _customerService.InsertCustomerGroupInCustomer(vendorGroup, item);
}
+ else
+ {
+ if (await _groupService.IsVendor(customer))
+ await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, item);
+ }
+ }
- //raise event
- await _mediator.Publish(new VendorActivationEvent(request.Vendor), cancellationToken);
+ //raise event
+ await _mediator.Publish(new VendorActivationEvent(request.Vendor), cancellationToken);
- return true;
- }
+ return true;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoggedInEventHandler.cs b/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoggedInEventHandler.cs
index e390476df..821c32cc6 100644
--- a/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoggedInEventHandler.cs
+++ b/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoggedInEventHandler.cs
@@ -4,7 +4,7 @@ using MediatR;
namespace Grand.Business.Customers.Events.Handlers;
-public class CustomerLoggedInEventHandler: INotificationHandler<CustomerLoggedInEvent>
+public class CustomerLoggedInEventHandler : INotificationHandler<CustomerLoggedInEvent>
{
private readonly ICustomerService _customerService;
diff --git a/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoginFailedEventHandler.cs b/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoginFailedEventHandler.cs
index a0a4dc158..eedfe3949 100644
--- a/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoginFailedEventHandler.cs
+++ b/src/Business/Grand.Business.Customers/Events/Handlers/CustomerLoginFailedEventHandler.cs
@@ -5,11 +5,11 @@ using MediatR;
namespace Grand.Business.Customers.Events.Handlers;
-public class CustomerLoginFailedEventHandler: INotificationHandler<CustomerLoginFailedEvent>
+public class CustomerLoginFailedEventHandler : INotificationHandler<CustomerLoginFailedEvent>
{
private readonly ICustomerService _customerService;
private readonly CustomerSettings _customerSettings;
-
+
public CustomerLoginFailedEventHandler(ICustomerService customerService, CustomerSettings customerSettings)
{
_customerService = customerService;
@@ -26,10 +26,12 @@ public class CustomerLoginFailedEventHandler: INotificationHandler<CustomerLogin
notification.Customer.FailedLoginAttempts >= _customerSettings.FailedPasswordAllowedAttempts)
{
//lock out
- notification.Customer.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(_customerSettings.FailedPasswordLockoutMinutes);
+ notification.Customer.CannotLoginUntilDateUtc =
+ DateTime.UtcNow.AddMinutes(_customerSettings.FailedPasswordLockoutMinutes);
//reset the counter
notification.Customer.FailedLoginAttempts = 0;
}
+
await _customerService.UpdateCustomerLastLoginDate(notification.Customer);
}
}
diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs
index 31e746a7c..26fc6000a 100644
--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs
+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs
@@ -1,121 +1,116 @@
using Grand.Business.Core.Queries.Customers;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using MediatR;
using System.Linq.Expressions;
-namespace Grand.Business.Customers.Queries.Handlers
+namespace Grand.Business.Customers.Queries.Handlers;
+
+public class GetCustomerQueryHandler : IRequestHandler<GetCustomerQuery, IQueryable<Customer>>
{
- public class GetCustomerQueryHandler : IRequestHandler<GetCustomerQuery, IQueryable<Customer>>
+ private readonly IRepository<Customer> _customerRepository;
+
+ public GetCustomerQueryHandler(IRepository<Customer> customerRepository)
+ {
+ _customerRepository = customerRepository;
+ }
+
+ public Task<IQueryable<Customer>> Handle(GetCustomerQuery request, CancellationToken cancellationToken)
{
- private readonly IRepository<Customer> _customerRepository;
+ var query = from p in _customerRepository.Table
+ select p;
+
+ if (request.CreatedFromUtc.HasValue)
+ query = query.Where(c => request.CreatedFromUtc.Value <= c.CreatedOnUtc);
+ if (request.CreatedToUtc.HasValue)
+ query = query.Where(c => request.CreatedToUtc.Value >= c.CreatedOnUtc);
+ if (!string.IsNullOrEmpty(request.AffiliateId))
+ query = query.Where(c => request.AffiliateId == c.AffiliateId);
+ if (!string.IsNullOrEmpty(request.VendorId))
+ query = query.Where(c => request.VendorId == c.VendorId);
+ if (!string.IsNullOrEmpty(request.StoreId))
+ query = query.Where(c => c.StoreId == request.StoreId);
+ if (!string.IsNullOrEmpty(request.OwnerId))
+ query = query.Where(c => c.OwnerId == request.OwnerId);
+ if (!string.IsNullOrEmpty(request.SalesEmployeeId))
+ query = query.Where(c => c.SeId == request.SalesEmployeeId);
+
+ query = query.Where(c => !c.Deleted);
+ if (request.CustomerGroupIds is { Length: > 0 })
+ query = query.Where(c => c.Groups.Any(x => request.CustomerGroupIds.Contains(x)));
+ if (request.CustomerTagIds is { Length: > 0 })
+ foreach (var item in request.CustomerTagIds)
+ query = query.Where(c => c.CustomerTags.Contains(item));
+ if (!string.IsNullOrWhiteSpace(request.Email))
+ query = query.Where(c => c.Email != null && c.Email.Contains(request.Email.ToLower()));
+ if (!string.IsNullOrWhiteSpace(request.Username))
+ query = query.Where(c => c.Username != null && c.Username.ToLower().Contains(request.Username.ToLower()));
+
+ if (!string.IsNullOrWhiteSpace(request.FirstName))
+ query = query.Where(x => x.UserFields.Any(y =>
+ y.Key == SystemCustomerFieldNames.FirstName && y.Value != null &&
+ y.Value.ToLower().Contains(request.FirstName.ToLower())));
+
+ if (!string.IsNullOrWhiteSpace(request.LastName))
+ query = query.Where(x => x.UserFields.Any(y =>
+ y.Key == SystemCustomerFieldNames.LastName && y.Value != null &&
+ y.Value.ToLower().Contains(request.LastName.ToLower())));
+
+ //search by company
+ if (!string.IsNullOrWhiteSpace(request.Company))
+ query = query.Where(x => x.UserFields.Any(y =>
+ y.Key == SystemCustomerFieldNames.Company && y.Value != null &&
+ y.Value.ToLower().Contains(request.Company.ToLower())));
+ //search by phone
+ if (!string.IsNullOrWhiteSpace(request.Phone))
+ query = query.Where(x => x.UserFields.Any(y =>
+ y.Key == SystemCustomerFieldNames.Phone && y.Value != null &&
+ y.Value.ToLower().Contains(request.Phone.ToLower())));
+ //search by zip
+ if (!string.IsNullOrWhiteSpace(request.ZipPostalCode))
+ query = query.Where(x => x.UserFields.Any(y =>
+ y.Key == SystemCustomerFieldNames.ZipPostalCode && y.Value != null &&
+ y.Value.ToLower().Contains(request.ZipPostalCode.ToLower())));
- public GetCustomerQueryHandler(IRepository<Customer> customerRepository)
+ if (request.LoadOnlyWithShoppingCart)
+ query = request.Sct.HasValue
+ ? query.Where(c => c.ShoppingCartItems.Any(x => x.ShoppingCartTypeId == request.Sct.Value))
+ : query.Where(c => c.ShoppingCartItems.Any());
+
+ if (request.OrderBySelector == null)
{
- _customerRepository = customerRepository;
+ query = query.OrderByDescending(c => c.CreatedOnUtc);
}
- public Task<IQueryable<Customer>> Handle(GetCustomerQuery request, CancellationToken cancellationToken)
+ else
{
- var query = from p in _customerRepository.Table
- select p;
-
- if (request.CreatedFromUtc.HasValue)
- query = query.Where(c => request.CreatedFromUtc.Value <= c.CreatedOnUtc);
- if (request.CreatedToUtc.HasValue)
- query = query.Where(c => request.CreatedToUtc.Value >= c.CreatedOnUtc);
- if (!string.IsNullOrEmpty(request.AffiliateId))
- query = query.Where(c => request.AffiliateId == c.AffiliateId);
- if (!string.IsNullOrEmpty(request.VendorId))
- query = query.Where(c => request.VendorId == c.VendorId);
- if (!string.IsNullOrEmpty(request.StoreId))
- query = query.Where(c => c.StoreId == request.StoreId);
- if (!string.IsNullOrEmpty(request.OwnerId))
- query = query.Where(c => c.OwnerId == request.OwnerId);
- if (!string.IsNullOrEmpty(request.SalesEmployeeId))
- query = query.Where(c => c.SeId == request.SalesEmployeeId);
-
- query = query.Where(c => !c.Deleted);
- if (request.CustomerGroupIds is { Length: > 0 })
- query = query.Where(c => c.Groups.Any(x => request.CustomerGroupIds.Contains(x)));
- if (request.CustomerTagIds is { Length: > 0 })
- {
- foreach (var item in request.CustomerTagIds)
- {
- query = query.Where(c => c.CustomerTags.Contains(item));
- }
- }
- if (!string.IsNullOrWhiteSpace(request.Email))
- query = query.Where(c => c.Email != null && c.Email.Contains(request.Email.ToLower()));
- if (!string.IsNullOrWhiteSpace(request.Username))
- query = query.Where(c => c.Username != null && c.Username.ToLower().Contains(request.Username.ToLower()));
-
- if (!string.IsNullOrWhiteSpace(request.FirstName))
- {
- query = query.Where(x => x.UserFields.Any(y => y.Key == SystemCustomerFieldNames.FirstName && y.Value != null && y.Value.ToLower().Contains(request.FirstName.ToLower())));
- }
-
- if (!string.IsNullOrWhiteSpace(request.LastName))
- {
- query = query.Where(x => x.UserFields.Any(y => y.Key == SystemCustomerFieldNames.LastName && y.Value != null && y.Value.ToLower().Contains(request.LastName.ToLower())));
- }
-
- //search by company
- if (!string.IsNullOrWhiteSpace(request.Company))
- {
- query = query.Where(x => x.UserFields.Any(y => y.Key == SystemCustomerFieldNames.Company && y.Value != null && y.Value.ToLower().Contains(request.Company.ToLower())));
- }
- //search by phone
- if (!string.IsNullOrWhiteSpace(request.Phone))
- {
- query = query.Where(x => x.UserFields.Any(y => y.Key == SystemCustomerFieldNames.Phone && y.Value != null && y.Value.ToLower().Contains(request.Phone.ToLower())));
- }
- //search by zip
- if (!string.IsNullOrWhiteSpace(request.ZipPostalCode))
- {
- query = query.Where(x => x.UserFields.Any(y => y.Key == SystemCustomerFieldNames.ZipPostalCode && y.Value != null && y.Value.ToLower().Contains(request.ZipPostalCode.ToLower())));
- }
-
- if (request.LoadOnlyWithShoppingCart)
- {
- query = request.Sct.HasValue ?
- query.Where(c => c.ShoppingCartItems.Any(x => x.ShoppingCartTypeId == request.Sct.Value)) :
- query.Where(c => c.ShoppingCartItems.Any());
- }
-
- if (request.OrderBySelector == null)
- query = query.OrderByDescending(c => c.CreatedOnUtc);
- else
- {
- var propName = GetName(request.OrderBySelector);
- query = OrderingHelper(query, propName);
- }
-
- return Task.FromResult(query);
+ var propName = GetName(request.OrderBySelector);
+ query = OrderingHelper(query, propName);
}
- private string GetName(Expression<Func<Customer, object>> exp)
- {
- if (exp.Body is MemberExpression body) return body.Member.Name;
- var expBody = (UnaryExpression)exp.Body;
- body = expBody.Operand as MemberExpression;
- return body?.Member.Name;
- }
+ return Task.FromResult(query);
+ }
- private IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName)
- {
- ParameterExpression param = Expression.Parameter(typeof(T), propertyName);
- MemberExpression property = Expression.PropertyOrField(param, propertyName);
- LambdaExpression sort = Expression.Lambda(property, param);
-
- MethodCallExpression call = Expression.Call(
- typeof(Queryable),
- "OrderByDescending",
- [typeof(T), property.Type],
- source.Expression,
- Expression.Quote(sort));
-
- return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
- }
+ private string GetName(Expression<Func<Customer, object>> exp)
+ {
+ if (exp.Body is MemberExpression body) return body.Member.Name;
+ var expBody = (UnaryExpression)exp.Body;
+ body = expBody.Operand as MemberExpression;
+ return body?.Member.Name;
+ }
+
+ private IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName)
+ {
+ var param = Expression.Parameter(typeof(T), propertyName);
+ var property = Expression.PropertyOrField(param, propertyName);
+ var sort = Expression.Lambda(property, param);
+
+ var call = Expression.Call(
+ typeof(Queryable),
+ "OrderByDescending",
+ [typeof(T), property.Type],
+ source.Expression,
+ Expression.Quote(sort));
+ return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs
index 9b4ed1b8a..acf87a9cd 100644
--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs
+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs
@@ -3,23 +3,22 @@ using Grand.Business.Core.Queries.Customers;
using Grand.Domain.Customers;
using MediatR;
-namespace Grand.Business.Customers.Queries.Handlers
+namespace Grand.Business.Customers.Queries.Handlers;
+
+public class GetGroupBySystemNameQueryHandler : IRequestHandler<GetGroupBySystemNameQuery, CustomerGroup>
{
- public class GetGroupBySystemNameQueryHandler : IRequestHandler<GetGroupBySystemNameQuery, CustomerGroup>
- {
- private readonly IGroupService _groupService;
+ private readonly IGroupService _groupService;
- public GetGroupBySystemNameQueryHandler(IGroupService groupService)
- {
- _groupService = groupService;
- }
+ public GetGroupBySystemNameQueryHandler(IGroupService groupService)
+ {
+ _groupService = groupService;
+ }
- public async Task<CustomerGroup> Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(request.SystemName))
- throw new ArgumentNullException(nameof(request.SystemName));
+ public async Task<CustomerGroup> Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrEmpty(request.SystemName))
+ throw new ArgumentNullException(nameof(request.SystemName));
- return await _groupService.GetCustomerGroupBySystemName(request.SystemName);
- }
+ return await _groupService.GetCustomerGroupBySystemName(request.SystemName);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs
index 688cbe153..444f5083a 100644
--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs
+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetPasswordIsExpiredQueryHandler.cs
@@ -3,41 +3,42 @@ using Grand.Business.Core.Queries.Customers;
using Grand.Domain.Customers;
using MediatR;
-namespace Grand.Business.Customers.Queries.Handlers
+namespace Grand.Business.Customers.Queries.Handlers;
+
+public class GetPasswordIsExpiredQueryHandler : IRequestHandler<GetPasswordIsExpiredQuery, bool>
{
- public class GetPasswordIsExpiredQueryHandler : IRequestHandler<GetPasswordIsExpiredQuery, bool>
+ private readonly CustomerSettings _customerSettings;
+ private readonly IGroupService _groupService;
+
+ public GetPasswordIsExpiredQueryHandler(IGroupService groupService, CustomerSettings customerSettings)
+ {
+ _groupService = groupService;
+ _customerSettings = customerSettings;
+ }
+
+ public async Task<bool> Handle(GetPasswordIsExpiredQuery request, CancellationToken cancellationToken)
{
- private readonly IGroupService _groupService;
- private readonly CustomerSettings _customerSettings;
-
- public GetPasswordIsExpiredQueryHandler(IGroupService groupService, CustomerSettings customerSettings)
- {
- _groupService = groupService;
- _customerSettings = customerSettings;
- }
-
- public async Task<bool> Handle(GetPasswordIsExpiredQuery request, CancellationToken cancellationToken)
- {
- if (request.Customer == null)
- throw new ArgumentNullException(nameof(request.Customer));
-
- //user without email don't have a password
- if (string.IsNullOrEmpty(request.Customer.Email))
- return false;
-
- //password lifetime is disabled for user
- var customerGroups = await _groupService.GetAllByIds(request.Customer.Groups.ToArray());
-
- if (!customerGroups.Any(role => role.Active && role.EnablePasswordLifetime))
- return false;
-
- //setting disabled for all
- if (_customerSettings.PasswordLifetime == 0)
- return false;
-
- var currentLifetime = !request.Customer.PasswordChangeDateUtc.HasValue ? int.MaxValue : (DateTime.UtcNow - request.Customer.PasswordChangeDateUtc.Value).Days;
-
- return currentLifetime >= _customerSettings.PasswordLifetime;
- }
+ if (request.Customer == null)
+ throw new ArgumentNullException(nameof(request.Customer));
+
+ //user without email don't have a password
+ if (string.IsNullOrEmpty(request.Customer.Email))
+ return false;
+
+ //password lifetime is disabled for user
+ var customerGroups = await _groupService.GetAllByIds(request.Customer.Groups.ToArray());
+
+ if (!customerGroups.Any(role => role.Active && role.EnablePasswordLifetime))
+ return false;
+
+ //setting disabled for all
+ if (_customerSettings.PasswordLifetime == 0)
+ return false;
+
+ var currentLifetime = !request.Customer.PasswordChangeDateUtc.HasValue
+ ? int.MaxValue
+ : (DateTime.UtcNow - request.Customer.PasswordChangeDateUtc.Value).Days;
+
+ return currentLifetime >= _customerSettings.PasswordLifetime;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs
index f38bf0061..c759339a0 100644
--- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs
+++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs
@@ -1,155 +1,157 @@
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Affiliates;
-using Grand.Data;
using Grand.Domain.Orders;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Affiliate service
+/// </summary>
+public class AffiliateService : IAffiliateService
{
+ #region Ctor
+
/// <summary>
- /// Affiliate service
+ /// Ctor
/// </summary>
- public class AffiliateService : IAffiliateService
+ /// <param name="affiliateRepository">Affiliate repository</param>
+ /// <param name="orderRepository">Order repository</param>
+ /// <param name="mediator">Mediator</param>
+ public AffiliateService(IRepository<Affiliate> affiliateRepository,
+ IRepository<Order> orderRepository,
+ IMediator mediator)
{
- #region Fields
+ _affiliateRepository = affiliateRepository;
+ _orderRepository = orderRepository;
+ _mediator = mediator;
+ }
- private readonly IRepository<Affiliate> _affiliateRepository;
- private readonly IRepository<Order> _orderRepository;
- private readonly IMediator _mediator;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<Affiliate> _affiliateRepository;
+ private readonly IRepository<Order> _orderRepository;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="affiliateRepository">Affiliate repository</param>
- /// <param name="orderRepository">Order repository</param>
- /// <param name="mediator">Mediator</param>
- public AffiliateService(IRepository<Affiliate> affiliateRepository,
- IRepository<Order> orderRepository,
- IMediator mediator)
- {
- _affiliateRepository = affiliateRepository;
- _orderRepository = orderRepository;
- _mediator = mediator;
- }
+ #endregion
- #endregion
+ #region Methods
- #region Methods
+ /// <summary>
+ /// Gets an affiliate by identifier
+ /// </summary>
+ /// <param name="affiliateId">Affiliate identifier</param>
+ /// <returns>Affiliate</returns>
+ public virtual Task<Affiliate> GetAffiliateById(string affiliateId)
+ {
+ return _affiliateRepository.GetByIdAsync(affiliateId);
+ }
- /// <summary>
- /// Gets an affiliate by identifier
- /// </summary>
- /// <param name="affiliateId">Affiliate identifier</param>
- /// <returns>Affiliate</returns>
- public virtual Task<Affiliate> GetAffiliateById(string affiliateId)
- {
- return _affiliateRepository.GetByIdAsync(affiliateId);
- }
+ /// <summary>
+ /// Gets an affiliate by friendly url name
+ /// </summary>
+ /// <param name="friendlyUrlName">Friendly url name</param>
+ /// <returns>Affiliate</returns>
+ public virtual async Task<Affiliate> GetAffiliateByFriendlyUrlName(string friendlyUrlName)
+ {
+ var query = from a in _affiliateRepository.Table
+ where a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant())
+ select a;
+ var affiliate = await Task.FromResult(query.FirstOrDefault());
+ return affiliate;
+ }
- /// <summary>
- /// Gets an affiliate by friendly url name
- /// </summary>
- /// <param name="friendlyUrlName">Friendly url name</param>
- /// <returns>Affiliate</returns>
- public virtual async Task<Affiliate> GetAffiliateByFriendlyUrlName(string friendlyUrlName)
+ /// <summary>
+ /// Gets all affiliates
+ /// </summary>
+ /// <returns>Affiliates</returns>
+ public virtual async Task<IPagedList<Affiliate>> GetAllAffiliates(string friendlyUrlName = null,
+ string firstName = null, string lastName = null,
+ bool loadOnlyWithOrders = false,
+ DateTime? ordersCreatedFromUtc = null, DateTime? ordersCreatedToUtc = null,
+ int pageIndex = 0, int pageSize = int.MaxValue,
+ bool showHidden = false)
+ {
+ var query = from p in _affiliateRepository.Table
+ select p;
+
+ if (!string.IsNullOrWhiteSpace(friendlyUrlName))
+ query = query.Where(a =>
+ a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant()));
+ if (!string.IsNullOrWhiteSpace(firstName))
+ query = query.Where(a =>
+ a.Address.FirstName != null && a.Address.FirstName.ToLower().Contains(firstName.ToLower()));
+ if (!string.IsNullOrWhiteSpace(lastName))
+ query = query.Where(a =>
+ a.Address.LastName != null && a.Address.LastName.ToLower().Contains(lastName.ToLower()));
+ if (!showHidden)
+ query = query.Where(a => a.Active);
+
+ if (loadOnlyWithOrders)
{
- var query = from a in _affiliateRepository.Table
- where a.FriendlyUrlName!=null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant())
- select a;
- var affiliate = await Task.FromResult(query.FirstOrDefault());
- return affiliate;
+ var ordersQuery = from p in _orderRepository.Table
+ select p;
+
+ if (ordersCreatedFromUtc.HasValue)
+ ordersQuery = ordersQuery.Where(o => ordersCreatedFromUtc.Value <= o.CreatedOnUtc);
+ if (ordersCreatedToUtc.HasValue)
+ ordersQuery = ordersQuery.Where(o => ordersCreatedToUtc.Value >= o.CreatedOnUtc);
+ ordersQuery = ordersQuery.Where(o => !o.Deleted);
+ var affOrder = ordersQuery.Select(x => x.AffiliateId).ToList();
+ query = query.Where(x => affOrder.Contains(x.Id));
}
- /// <summary>
- /// Gets all affiliates
- /// </summary>
- /// <returns>Affiliates</returns>
- public virtual async Task<IPagedList<Affiliate>> GetAllAffiliates(string friendlyUrlName = null,
- string firstName = null, string lastName = null,
- bool loadOnlyWithOrders = false,
- DateTime? ordersCreatedFromUtc = null, DateTime? ordersCreatedToUtc = null,
- int pageIndex = 0, int pageSize = int.MaxValue,
- bool showHidden = false)
- {
- var query = from p in _affiliateRepository.Table
- select p;
-
- if (!string.IsNullOrWhiteSpace(friendlyUrlName))
- query = query.Where(a => a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant()));
- if (!string.IsNullOrWhiteSpace(firstName))
- query = query.Where(a => a.Address.FirstName != null && a.Address.FirstName.ToLower().Contains(firstName.ToLower()));
- if (!string.IsNullOrWhiteSpace(lastName))
- query = query.Where(a => a.Address.LastName != null && a.Address.LastName.ToLower().Contains(lastName.ToLower()));
- if (!showHidden)
- query = query.Where(a => a.Active);
-
- if (loadOnlyWithOrders)
- {
- var ordersQuery = from p in _orderRepository.Table
- select p;
-
- if (ordersCreatedFromUtc.HasValue)
- ordersQuery = ordersQuery.Where(o => ordersCreatedFromUtc.Value <= o.CreatedOnUtc);
- if (ordersCreatedToUtc.HasValue)
- ordersQuery = ordersQuery.Where(o => ordersCreatedToUtc.Value >= o.CreatedOnUtc);
- ordersQuery = ordersQuery.Where(o => !o.Deleted);
- var affOrder = ordersQuery.Select(x => x.AffiliateId).ToList();
- query = query.Where(x => affOrder.Contains(x.Id));
- }
-
- query = query.OrderByDescending(a => a.Id);
-
- return await PagedList<Affiliate>.Create(query, pageIndex, pageSize);
- }
+ query = query.OrderByDescending(a => a.Id);
- /// <summary>
- /// Inserts an affiliate
- /// </summary>
- /// <param name="affiliate">Affiliate</param>
- public virtual async Task InsertAffiliate(Affiliate affiliate)
- {
- ArgumentNullException.ThrowIfNull(affiliate);
+ return await PagedList<Affiliate>.Create(query, pageIndex, pageSize);
+ }
- await _affiliateRepository.InsertAsync(affiliate);
+ /// <summary>
+ /// Inserts an affiliate
+ /// </summary>
+ /// <param name="affiliate">Affiliate</param>
+ public virtual async Task InsertAffiliate(Affiliate affiliate)
+ {
+ ArgumentNullException.ThrowIfNull(affiliate);
- //event notification
- await _mediator.EntityInserted(affiliate);
- }
+ await _affiliateRepository.InsertAsync(affiliate);
- /// <summary>
- /// Updates the affiliate
- /// </summary>
- /// <param name="affiliate">Affiliate</param>
- public virtual async Task UpdateAffiliate(Affiliate affiliate)
- {
- ArgumentNullException.ThrowIfNull(affiliate);
+ //event notification
+ await _mediator.EntityInserted(affiliate);
+ }
- await _affiliateRepository.UpdateAsync(affiliate);
+ /// <summary>
+ /// Updates the affiliate
+ /// </summary>
+ /// <param name="affiliate">Affiliate</param>
+ public virtual async Task UpdateAffiliate(Affiliate affiliate)
+ {
+ ArgumentNullException.ThrowIfNull(affiliate);
- //event notification
- await _mediator.EntityUpdated(affiliate);
- }
+ await _affiliateRepository.UpdateAsync(affiliate);
- /// <summary>
- /// Marks affiliate as deleted
- /// </summary>
- /// <param name="affiliate">Affiliate</param>
- public virtual async Task DeleteAffiliate(Affiliate affiliate)
- {
- ArgumentNullException.ThrowIfNull(affiliate);
+ //event notification
+ await _mediator.EntityUpdated(affiliate);
+ }
- await _affiliateRepository.DeleteAsync(affiliate);
+ /// <summary>
+ /// Marks affiliate as deleted
+ /// </summary>
+ /// <param name="affiliate">Affiliate</param>
+ public virtual async Task DeleteAffiliate(Affiliate affiliate)
+ {
+ ArgumentNullException.ThrowIfNull(affiliate);
- //event notification
- await _mediator.EntityDeleted(affiliate);
- }
+ await _affiliateRepository.DeleteAsync(affiliate);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(affiliate);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
index 9317293f1..7b4f7ef67 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs
@@ -7,197 +7,196 @@ using Grand.Domain.Localization;
using Grand.SharedKernel.Extensions;
using System.Net;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Customer attribute parser
+/// </summary>
+public class CustomerAttributeParser : ICustomerAttributeParser
{
+ private readonly ICustomerAttributeService _customerAttributeService;
+
+ public CustomerAttributeParser(ICustomerAttributeService customerAttributeService)
+ {
+ _customerAttributeService = customerAttributeService;
+ }
+
/// <summary>
- /// Customer attribute parser
+ /// Gets selected customer attributes
/// </summary>
- public class CustomerAttributeParser : ICustomerAttributeParser
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Selected customer attributes</returns>
+ public virtual async Task<IList<CustomerAttribute>> ParseCustomerAttributes(IList<CustomAttribute> customAttributes)
{
- private readonly ICustomerAttributeService _customerAttributeService;
-
- public CustomerAttributeParser(ICustomerAttributeService customerAttributeService)
- {
- _customerAttributeService = customerAttributeService;
- }
-
- /// <summary>
- /// Gets selected customer attributes
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Selected customer attributes</returns>
- public virtual async Task<IList<CustomerAttribute>> ParseCustomerAttributes(IList<CustomAttribute> customAttributes)
- {
- var result = new List<CustomerAttribute>();
- if (customAttributes == null || !customAttributes.Any())
- return result;
-
- foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))
- {
- var attribute = await _customerAttributeService.GetCustomerAttributeById(customAttribute.Key);
- if (attribute != null)
- {
- result.Add(attribute);
- }
- }
+ var result = new List<CustomerAttribute>();
+ if (customAttributes == null || !customAttributes.Any())
return result;
- }
- /// <summary>
- /// Get customer attribute values
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Customer attribute values</returns>
- public virtual async Task<IList<CustomerAttributeValue>> ParseCustomerAttributeValues(IList<CustomAttribute> customAttributes)
+ foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))
{
- var values = new List<CustomerAttributeValue>();
- if (customAttributes == null || !customAttributes.Any())
- return values;
+ var attribute = await _customerAttributeService.GetCustomerAttributeById(customAttribute.Key);
+ if (attribute != null) result.Add(attribute);
+ }
- var attributes = await ParseCustomerAttributes(customAttributes);
- foreach (var attribute in attributes)
- {
- if (!attribute.ShouldHaveValues())
- continue;
+ return result;
+ }
- 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.CustomerAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);
- }
+ /// <summary>
+ /// Get customer attribute values
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Customer attribute values</returns>
+ public virtual async Task<IList<CustomerAttributeValue>> ParseCustomerAttributeValues(
+ IList<CustomAttribute> customAttributes)
+ {
+ var values = new List<CustomerAttributeValue>();
+ if (customAttributes == null || !customAttributes.Any())
return values;
- }
-
- /// <summary>
- /// Adds an attribute
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <param name="ca">Customer attribute</param>
- /// <param name="value">Value</param>
- /// <returns>Attributes</returns>
- public virtual IList<CustomAttribute> AddCustomerAttribute(IList<CustomAttribute> customAttributes, CustomerAttribute ca, string value)
+ var attributes = await ParseCustomerAttributes(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.CustomerAttributeValues.FirstOrDefault(x => x.Id == valueStr)
+ into value
+ where value != null
+ select value);
}
- /// <summary>
- /// Validates customer attributes
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Warnings</returns>
- public virtual async Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes)
- {
- var warnings = new List<string>();
+ return values;
+ }
- if (customAttributes == null || !customAttributes.Any())
- return warnings;
- //ensure it's our attributes
- var attributes1 = await ParseCustomerAttributes(customAttributes);
+ /// <summary>
+ /// Adds an attribute
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <param name="ca">Customer attribute</param>
+ /// <param name="value">Value</param>
+ /// <returns>Attributes</returns>
+ public virtual IList<CustomAttribute> AddCustomerAttribute(IList<CustomAttribute> customAttributes,
+ CustomerAttribute ca, string value)
+ {
+ customAttributes ??= new List<CustomAttribute>();
+ customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });
+ return customAttributes;
+ }
+
+ /// <summary>
+ /// Validates customer attributes
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Warnings</returns>
+ public virtual async Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes)
+ {
+ var warnings = new List<string>();
- //validate required customer attributes (whether they're chosen/selected/entered)
- var attributes2 = await _customerAttributeService.GetAllCustomerAttributes();
- foreach (var a2 in attributes2)
- {
- if (!a2.IsRequired) continue;
- var found = false;
- //selected customer attributes
- foreach (var a1 in attributes1)
- {
- if (a1.Id != a2.Id) continue;
- var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);
- if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())))
- {
- found = true;
- }
- }
+ if (customAttributes == null || !customAttributes.Any())
+ return warnings;
- //if not found
- if (found) continue;
+ //ensure it's our attributes
+ var attributes1 = await ParseCustomerAttributes(customAttributes);
- warnings.Add("Selected attribute not found");
+ //validate required customer attributes (whether they're chosen/selected/entered)
+ var attributes2 = await _customerAttributeService.GetAllCustomerAttributes();
+ foreach (var a2 in attributes2)
+ {
+ if (!a2.IsRequired) continue;
+ var found = false;
+ //selected customer attributes
+ foreach (var a1 in attributes1)
+ {
+ if (a1.Id != a2.Id) continue;
+ var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);
+ if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))) found = true;
}
- return warnings;
+ //if not found
+ if (found) continue;
+
+ warnings.Add("Selected attribute not found");
}
- /// <summary>
- /// Formats attributes
- /// </summary>
- /// <param name="language">Language</param>
- /// <param name="customAttributes">Attributes</param>
- /// <param name="separator">Separator</param>
- /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
- /// <returns>Attributes</returns>
- public virtual async Task<string> FormatAttributes(Language language,
- IList<CustomAttribute> customAttributes, string separator = "<br />", bool htmlEncode = true)
- {
- var result = new StringBuilder();
+ return warnings;
+ }
+
+ /// <summary>
+ /// Formats attributes
+ /// </summary>
+ /// <param name="language">Language</param>
+ /// <param name="customAttributes">Attributes</param>
+ /// <param name="separator">Separator</param>
+ /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
+ /// <returns>Attributes</returns>
+ public virtual async Task<string> FormatAttributes(Language language,
+ IList<CustomAttribute> customAttributes, string separator = "<br />", bool htmlEncode = true)
+ {
+ var result = new StringBuilder();
- var attributes = await ParseCustomerAttributes(customAttributes);
- for (var i = 0; i < attributes.Count; i++)
+ var attributes = await ParseCustomerAttributes(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.AttributeControlTypeId)
{
- switch (attribute.AttributeControlTypeId)
+ //no values
+ case AttributeControlType.MultilineTextbox:
{
- //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)}";
- break;
- }
- case AttributeControlType.FileUpload:
- //file upload
- //not supported for customer attributes
- 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;
- }
+ //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)}";
+ break;
}
- }
- else
- {
-
- var attributeValueId = valueStr;
- var attributeValue = attribute.CustomerAttributeValues.FirstOrDefault(x => x.Id == attributeValueId);
- if (attributeValue != null)
+ case AttributeControlType.FileUpload:
+ //file upload
+ //not supported for customer attributes
+ break;
+ 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);
-
}
- if (string.IsNullOrEmpty(formattedAttribute)) continue;
- if (i != 0 || j != 0)
- result.Append(separator);
- result.Append(formattedAttribute);
}
- }
+ else
+ {
+ var attributeValueId = valueStr;
+ var attributeValue =
+ attribute.CustomerAttributeValues.FirstOrDefault(x => x.Id == attributeValueId);
+ if (attributeValue != null)
+ formattedAttribute =
+ $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";
+ //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);
+ }
}
+ return result.ToString();
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs
index da17517de..74b57b653 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs
@@ -1,186 +1,187 @@
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain.Customers;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Customer attribute service
+/// </summary>
+public class CustomerAttributeService : ICustomerAttributeService
{
+ #region Ctor
+
/// <summary>
- /// Customer attribute service
+ /// Ctor
/// </summary>
- public class CustomerAttributeService : ICustomerAttributeService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="customerAttributeRepository">Customer attribute repository</param>
+ /// <param name="mediator">Mediator</param>
+ public CustomerAttributeService(ICacheBase cacheBase,
+ IRepository<CustomerAttribute> customerAttributeRepository,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<CustomerAttribute> _customerAttributeRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ _cacheBase = cacheBase;
+ _customerAttributeRepository = customerAttributeRepository;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="customerAttributeRepository">Customer attribute repository</param>
- /// <param name="mediator">Mediator</param>
- public CustomerAttributeService(ICacheBase cacheBase,
- IRepository<CustomerAttribute> customerAttributeRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _customerAttributeRepository = customerAttributeRepository;
- _mediator = mediator;
- }
+ private readonly IRepository<CustomerAttribute> _customerAttributeRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets all customer attributes
- /// </summary>
- /// <returns>Customer attributes</returns>
- public virtual async Task<IList<CustomerAttribute>> GetAllCustomerAttributes()
- {
- var key = CacheKey.CUSTOMERATTRIBUTES_ALL_KEY;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from ca in _customerAttributeRepository.Table
- orderby ca.DisplayOrder
- select ca;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets a customer attribute
- /// </summary>
- /// <param name="customerAttributeId">Customer attribute identifier</param>
- /// <returns>Customer attribute</returns>
- public virtual Task<CustomerAttribute> GetCustomerAttributeById(string customerAttributeId)
- {
- var key = string.Format(CacheKey.CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId);
- return _cacheBase.GetAsync(key, () => _customerAttributeRepository.GetByIdAsync(customerAttributeId));
- }
-
- /// <summary>
- /// Inserts a customer attribute
- /// </summary>
- /// <param name="customerAttribute">Customer attribute</param>
- public virtual async Task InsertCustomerAttribute(CustomerAttribute customerAttribute)
+ /// <summary>
+ /// Gets all customer attributes
+ /// </summary>
+ /// <returns>Customer attributes</returns>
+ public virtual async Task<IList<CustomerAttribute>> GetAllCustomerAttributes()
+ {
+ var key = CacheKey.CUSTOMERATTRIBUTES_ALL_KEY;
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(customerAttribute);
+ var query = from ca in _customerAttributeRepository.Table
+ orderby ca.DisplayOrder
+ select ca;
+ return await Task.FromResult(query.ToList());
+ });
+ }
+
+ /// <summary>
+ /// Gets a customer attribute
+ /// </summary>
+ /// <param name="customerAttributeId">Customer attribute identifier</param>
+ /// <returns>Customer attribute</returns>
+ public virtual Task<CustomerAttribute> GetCustomerAttributeById(string customerAttributeId)
+ {
+ var key = string.Format(CacheKey.CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId);
+ return _cacheBase.GetAsync(key, () => _customerAttributeRepository.GetByIdAsync(customerAttributeId));
+ }
- await _customerAttributeRepository.InsertAsync(customerAttribute);
+ /// <summary>
+ /// Inserts a customer attribute
+ /// </summary>
+ /// <param name="customerAttribute">Customer attribute</param>
+ public virtual async Task InsertCustomerAttribute(CustomerAttribute customerAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ await _customerAttributeRepository.InsertAsync(customerAttribute);
- //event notification
- await _mediator.EntityInserted(customerAttribute);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
- /// <summary>
- /// Updates the customer attribute
- /// </summary>
- /// <param name="customerAttribute">Customer attribute</param>
- public virtual async Task UpdateCustomerAttribute(CustomerAttribute customerAttribute)
- {
- ArgumentNullException.ThrowIfNull(customerAttribute);
+ //event notification
+ await _mediator.EntityInserted(customerAttribute);
+ }
- await _customerAttributeRepository.UpdateAsync(customerAttribute);
+ /// <summary>
+ /// Updates the customer attribute
+ /// </summary>
+ /// <param name="customerAttribute">Customer attribute</param>
+ public virtual async Task UpdateCustomerAttribute(CustomerAttribute customerAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ await _customerAttributeRepository.UpdateAsync(customerAttribute);
- //event notification
- await _mediator.EntityUpdated(customerAttribute);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
- /// <summary>
- /// Deletes a customer attribute
- /// </summary>
- /// <param name="customerAttribute">Customer attribute</param>
- public virtual async Task DeleteCustomerAttribute(CustomerAttribute customerAttribute)
- {
- ArgumentNullException.ThrowIfNull(customerAttribute);
+ //event notification
+ await _mediator.EntityUpdated(customerAttribute);
+ }
- await _customerAttributeRepository.DeleteAsync(customerAttribute);
+ /// <summary>
+ /// Deletes a customer attribute
+ /// </summary>
+ /// <param name="customerAttribute">Customer attribute</param>
+ public virtual async Task DeleteCustomerAttribute(CustomerAttribute customerAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ await _customerAttributeRepository.DeleteAsync(customerAttribute);
- //event notification
- await _mediator.EntityDeleted(customerAttribute);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
-
- /// <summary>
- /// Inserts a customer attribute value
- /// </summary>
- /// <param name="customerAttributeValue">Customer attribute value</param>
- public virtual async Task InsertCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(customerAttributeValue);
+ //event notification
+ await _mediator.EntityDeleted(customerAttribute);
+ }
- var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
- ca.CustomerAttributeValues.Add(customerAttributeValue);
- await _customerAttributeRepository.UpdateAsync(ca);
+ /// <summary>
+ /// Inserts a customer attribute value
+ /// </summary>
+ /// <param name="customerAttributeValue">Customer attribute value</param>
+ public virtual async Task InsertCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
+ ca.CustomerAttributeValues.Add(customerAttributeValue);
- //event notification
- await _mediator.EntityInserted(customerAttributeValue);
- }
+ await _customerAttributeRepository.UpdateAsync(ca);
- /// <summary>
- /// Updates the customer attribute value
- /// </summary>
- /// <param name="customerAttributeValue">Customer attribute value</param>
- public virtual async Task UpdateCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(customerAttributeValue);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
- var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
- ca.CustomerAttributeValues.Remove(ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id));
- ca.CustomerAttributeValues.Add(customerAttributeValue);
+ //event notification
+ await _mediator.EntityInserted(customerAttributeValue);
+ }
- await _customerAttributeRepository.UpdateAsync(ca);
+ /// <summary>
+ /// Updates the customer attribute value
+ /// </summary>
+ /// <param name="customerAttributeValue">Customer attribute value</param>
+ public virtual async Task UpdateCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
+ ca.CustomerAttributeValues.Remove(
+ ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id));
+ ca.CustomerAttributeValues.Add(customerAttributeValue);
- //event notification
- await _mediator.EntityUpdated(customerAttributeValue);
- }
+ await _customerAttributeRepository.UpdateAsync(ca);
- /// <summary>
- /// Deletes a customer attribute value
- /// </summary>
- /// <param name="customerAttributeValue">Customer attribute value</param>
- public virtual async Task DeleteCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(customerAttributeValue);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
- var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
- ca.CustomerAttributeValues.Remove(ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id));
- await _customerAttributeRepository.UpdateAsync(ca);
+ //event notification
+ await _mediator.EntityUpdated(customerAttributeValue);
+ }
+
+ /// <summary>
+ /// Deletes a customer attribute value
+ /// </summary>
+ /// <param name="customerAttributeValue">Customer attribute value</param>
+ public virtual async Task DeleteCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(customerAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
+ var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId);
+ ca.CustomerAttributeValues.Remove(
+ ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id));
+ await _customerAttributeRepository.UpdateAsync(ca);
- //event notification
- await _mediator.EntityDeleted(customerAttributeValue);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(customerAttributeValue);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs b/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs
index 2678eddd9..eb0421a99 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs
@@ -1,60 +1,57 @@
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+public class CustomerHistoryPasswordService : ICustomerHistoryPasswordService
{
- public class CustomerHistoryPasswordService : ICustomerHistoryPasswordService
+ private readonly IRepository<CustomerHistoryPassword> _customerHistoryPasswordProductRepository;
+ private readonly IMediator _mediator;
+
+ public CustomerHistoryPasswordService(IRepository<CustomerHistoryPassword> customerHistoryPasswordProductRepository,
+ IMediator mediator)
+ {
+ _customerHistoryPasswordProductRepository = customerHistoryPasswordProductRepository;
+ _mediator = mediator;
+ }
+
+ /// <summary>
+ /// Insert a customer history password
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ public virtual async Task InsertCustomerPassword(Customer customer)
{
- private readonly IRepository<CustomerHistoryPassword> _customerHistoryPasswordProductRepository;
- private readonly IMediator _mediator;
-
- public CustomerHistoryPasswordService(IRepository<CustomerHistoryPassword> customerHistoryPasswordProductRepository,
- IMediator mediator)
- {
- _customerHistoryPasswordProductRepository = customerHistoryPasswordProductRepository;
- _mediator = mediator;
- }
-
- /// <summary>
- /// Insert a customer history password
- /// </summary>
- /// <param name="customer">Customer</param>
- public virtual async Task InsertCustomerPassword(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- var chp = new CustomerHistoryPassword
- {
- Password = customer.Password,
- PasswordFormatId = customer.PasswordFormatId,
- PasswordSalt = customer.PasswordSalt,
- CustomerId = customer.Id
- };
-
- await _customerHistoryPasswordProductRepository.InsertAsync(chp);
-
- //event notification
- await _mediator.EntityInserted(chp);
- }
-
- /// <summary>
- /// Gets customer passwords
- /// </summary>
- /// <param name="customerId">Customer identifier; pass null to load all records</param>
- /// <param name="passwordsToReturn">Number of returning passwords; pass null to load all records</param>
- /// <returns>List of customer passwords</returns>
- public virtual async Task<IList<CustomerHistoryPassword>> GetPasswords(string customerId, int passwordsToReturn)
- {
- return await Task.FromResult(_customerHistoryPasswordProductRepository
- .Table
- .Where(x=>x.CustomerId == customerId)
- .OrderByDescending(password => password.CreatedOnUtc)
- .Take(passwordsToReturn)
- .ToList());
- }
+ ArgumentNullException.ThrowIfNull(customer);
+
+ var chp = new CustomerHistoryPassword {
+ Password = customer.Password,
+ PasswordFormatId = customer.PasswordFormatId,
+ PasswordSalt = customer.PasswordSalt,
+ CustomerId = customer.Id
+ };
+
+ await _customerHistoryPasswordProductRepository.InsertAsync(chp);
+ //event notification
+ await _mediator.EntityInserted(chp);
+ }
+
+ /// <summary>
+ /// Gets customer passwords
+ /// </summary>
+ /// <param name="customerId">Customer identifier; pass null to load all records</param>
+ /// <param name="passwordsToReturn">Number of returning passwords; pass null to load all records</param>
+ /// <returns>List of customer passwords</returns>
+ public virtual async Task<IList<CustomerHistoryPassword>> GetPasswords(string customerId, int passwordsToReturn)
+ {
+ return await Task.FromResult(_customerHistoryPasswordProductRepository
+ .Table
+ .Where(x => x.CustomerId == customerId)
+ .OrderByDescending(password => password.CreatedOnUtc)
+ .Take(passwordsToReturn)
+ .ToList());
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
index d2c9ed5fe..352aa40bb 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs
@@ -9,198 +9,209 @@ using Grand.SharedKernel;
using Grand.SharedKernel.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Customer manager service
+/// </summary>
+public class CustomerManagerService : ICustomerManagerService
{
+ #region Ctor
+
/// <summary>
- /// Customer manager service
+ /// Ctor
/// </summary>
- public class CustomerManagerService : ICustomerManagerService
+ /// <param name="customerService">Customer service</param>
+ /// <param name="groupService">Group service</param>
+ /// <param name="encryptionService">Encryption service</param>
+ /// <param name="mediator">Mediator</param>
+ /// <param name="userFieldService">UserFields service</param>
+ /// <param name="customerHistoryPasswordService">History password</param>
+ /// <param name="customerSettings">Customer settings</param>
+ public CustomerManagerService(
+ ICustomerService customerService,
+ IGroupService groupService,
+ IEncryptionService encryptionService,
+ IMediator mediator,
+ IUserFieldService userFieldService,
+ ICustomerHistoryPasswordService customerHistoryPasswordService,
+ CustomerSettings customerSettings)
{
- #region Fields
-
- private readonly ICustomerService _customerService;
- private readonly IGroupService _groupService;
- private readonly IEncryptionService _encryptionService;
- private readonly IMediator _mediator;
- private readonly IUserFieldService _userFieldService;
- private readonly ICustomerHistoryPasswordService _customerHistoryPasswordService;
- private readonly CustomerSettings _customerSettings;
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="customerService">Customer service</param>
- /// <param name="groupService">Group service</param>
- /// <param name="encryptionService">Encryption service</param>
- /// <param name="mediator">Mediator</param>
- /// <param name="userFieldService">UserFields service</param>
- /// <param name="customerHistoryPasswordService">History password</param>
- /// <param name="customerSettings">Customer settings</param>
- public CustomerManagerService(
- ICustomerService customerService,
- IGroupService groupService,
- IEncryptionService encryptionService,
- IMediator mediator,
- IUserFieldService userFieldService,
- ICustomerHistoryPasswordService customerHistoryPasswordService,
- CustomerSettings customerSettings)
- {
- _customerService = customerService;
- _groupService = groupService;
- _encryptionService = encryptionService;
- _mediator = mediator;
- _userFieldService = userFieldService;
- _customerHistoryPasswordService = customerHistoryPasswordService;
- _customerSettings = customerSettings;
- }
+ _customerService = customerService;
+ _groupService = groupService;
+ _encryptionService = encryptionService;
+ _mediator = mediator;
+ _userFieldService = userFieldService;
+ _customerHistoryPasswordService = customerHistoryPasswordService;
+ _customerSettings = customerSettings;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IEncryptionService _encryptionService;
+ private readonly IMediator _mediator;
+ private readonly IUserFieldService _userFieldService;
+ private readonly ICustomerHistoryPasswordService _customerHistoryPasswordService;
+ private readonly CustomerSettings _customerSettings;
+
+ #endregion
+
+ #region Methods
+
+ public virtual bool PasswordMatch(PasswordFormat passwordFormat, string oldPassword, string newPassword,
+ string passwordSalt)
+ {
+ var newPwd = passwordFormat switch {
+ PasswordFormat.Clear => newPassword,
+ PasswordFormat.Encrypted => _encryptionService.EncryptText(newPassword, passwordSalt),
+ PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(newPassword, passwordSalt,
+ _customerSettings.HashedPasswordFormat),
+ _ => throw new Exception("PasswordFormat not supported")
+ };
+ return oldPassword.Equals(newPwd);
+ }
+
+
+ /// <summary>
+ /// Validate customer
+ /// </summary>
+ /// <param name="usernameOrEmail">Username or email</param>
+ /// <param name="password">Password</param>
+ /// <returns>Result</returns>
+ public virtual async Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password)
+ {
+ var customer = _customerSettings.UsernamesEnabled
+ ? await _customerService.GetCustomerByUsername(usernameOrEmail)
+ : await _customerService.GetCustomerByEmail(usernameOrEmail);
+
+ var pwd = customer.PasswordFormatId switch {
+ PasswordFormat.Clear => password,
+ PasswordFormat.Encrypted => _encryptionService.EncryptText(password, customer.PasswordSalt),
+ PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(password, customer.PasswordSalt,
+ _customerSettings.HashedPasswordFormat),
+ _ => throw new Exception("PasswordFormat not supported")
+ };
+ var isValid = pwd == customer.Password;
+ if (!isValid)
+ return CustomerLoginResults.WrongPassword;
+
+ //2fa required
+ if (customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled) &&
+ _customerSettings.TwoFactorAuthenticationEnabled)
+ return CustomerLoginResults.RequiresTwoFactor;
+
+ return CustomerLoginResults.Successful;
+ }
+
+ /// <summary>
+ /// Register customer
+ /// </summary>
+ /// <param name="request">Request</param>
+ /// <returns>Result</returns>
+ public virtual async Task RegisterCustomer(RegistrationRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
- #endregion
+ if (request.Customer == null)
+ throw new ArgumentException("Can't load current customer");
- #region Methods
+ //event notification
+ await _mediator.CustomerRegistrationEvent(request);
- public virtual bool PasswordMatch(PasswordFormat passwordFormat, string oldPassword, string newPassword, string passwordSalt)
+ request.Customer.Username = request.Username;
+ request.Customer.Email = request.Email;
+ request.Customer.PasswordFormatId = request.PasswordFormat;
+ request.Customer.StoreId = request.StoreId;
+
+ switch (request.PasswordFormat)
{
- var newPwd = passwordFormat switch {
- PasswordFormat.Clear => newPassword,
- PasswordFormat.Encrypted => _encryptionService.EncryptText(newPassword, passwordSalt),
- PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(newPassword, passwordSalt, _customerSettings.HashedPasswordFormat),
- _ => throw new Exception("PasswordFormat not supported")
- };
- return oldPassword.Equals(newPwd);
+ case PasswordFormat.Clear:
+ request.Customer.Password = request.Password;
+ break;
+ case PasswordFormat.Encrypted:
+ request.Customer.PasswordSalt = CommonHelper.GenerateRandomDigitCode(24);
+ request.Customer.Password =
+ _encryptionService.EncryptText(request.Password, request.Customer.PasswordSalt);
+ break;
+ case PasswordFormat.Hashed:
+ var saltKey = _encryptionService.CreateSaltKey(5);
+ request.Customer.PasswordSalt = saltKey;
+ request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey,
+ _customerSettings.HashedPasswordFormat);
+ break;
}
-
- /// <summary>
- /// Validate customer
- /// </summary>
- /// <param name="usernameOrEmail">Username or email</param>
- /// <param name="password">Password</param>
- /// <returns>Result</returns>
- public virtual async Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password)
+ await _customerHistoryPasswordService.InsertCustomerPassword(request.Customer);
+
+ request.Customer.Active = request.IsApproved;
+ await _customerService.UpdateActive(request.Customer);
+ //add to 'Registered' role
+ var registeredRole = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);
+ if (registeredRole == null)
+ throw new GrandException("'Registered' role could not be loaded");
+ request.Customer.Groups.Add(registeredRole.Id);
+ await _customerService.InsertCustomerGroupInCustomer(registeredRole, request.Customer.Id);
+ //remove from 'Guests' role
+ var guestGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests);
+ var guestExists = request.Customer.Groups.FirstOrDefault(cr => cr == guestGroup?.Id);
+ if (guestExists != null)
{
- var customer = _customerSettings.UsernamesEnabled ? await _customerService.GetCustomerByUsername(usernameOrEmail) : await _customerService.GetCustomerByEmail(usernameOrEmail);
-
- var pwd = customer.PasswordFormatId switch {
- PasswordFormat.Clear => password,
- PasswordFormat.Encrypted => _encryptionService.EncryptText(password, customer.PasswordSalt),
- PasswordFormat.Hashed => _encryptionService.CreatePasswordHash(password, customer.PasswordSalt, _customerSettings.HashedPasswordFormat),
- _ => throw new Exception("PasswordFormat not supported")
- };
- var isValid = pwd == customer.Password;
- if (!isValid)
- return CustomerLoginResults.WrongPassword;
-
- //2fa required
- if (customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled) && _customerSettings.TwoFactorAuthenticationEnabled)
- return CustomerLoginResults.RequiresTwoFactor;
-
- return CustomerLoginResults.Successful;
+ request.Customer.Groups.Remove(guestGroup.Id);
+ await _customerService.DeleteCustomerGroupInCustomer(guestGroup, request.Customer.Id);
}
- /// <summary>
- /// Register customer
- /// </summary>
- /// <param name="request">Request</param>
- /// <returns>Result</returns>
- public virtual async Task RegisterCustomer(RegistrationRequest request)
+ request.Customer.PasswordChangeDateUtc = DateTime.UtcNow;
+ await _customerService.UpdateCustomer(request.Customer);
+ }
+
+ /// <summary>
+ /// Change password
+ /// </summary>
+ /// <param name="request">Request</param>
+ public virtual async Task ChangePassword(ChangePasswordRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ var customer = await _customerService.GetCustomerByEmail(request.Email);
+ if (customer == null)
+ throw new ArgumentNullException(nameof(customer));
+
+ switch (request.PasswordFormat)
{
- ArgumentNullException.ThrowIfNull(request);
-
- if (request.Customer == null)
- throw new ArgumentException("Can't load current customer");
-
- //event notification
- await _mediator.CustomerRegistrationEvent(request);
-
- request.Customer.Username = request.Username;
- request.Customer.Email = request.Email;
- request.Customer.PasswordFormatId = request.PasswordFormat;
- request.Customer.StoreId = request.StoreId;
-
- switch (request.PasswordFormat)
+ case PasswordFormat.Clear:
{
- case PasswordFormat.Clear:
- request.Customer.Password = request.Password;
- break;
- case PasswordFormat.Encrypted:
- request.Customer.PasswordSalt = CommonHelper.GenerateRandomDigitCode(24);
- request.Customer.Password = _encryptionService.EncryptText(request.Password, request.Customer.PasswordSalt);
- break;
- case PasswordFormat.Hashed:
- var saltKey = _encryptionService.CreateSaltKey(5);
- request.Customer.PasswordSalt = saltKey;
- request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
- break;
+ customer.Password = request.NewPassword;
}
- await _customerHistoryPasswordService.InsertCustomerPassword(request.Customer);
-
- request.Customer.Active = request.IsApproved;
- await _customerService.UpdateActive(request.Customer);
- //add to 'Registered' role
- var registeredRole = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);
- if (registeredRole == null)
- throw new GrandException("'Registered' role could not be loaded");
- request.Customer.Groups.Add(registeredRole.Id);
- await _customerService.InsertCustomerGroupInCustomer(registeredRole, request.Customer.Id);
- //remove from 'Guests' role
- var guestGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests);
- var guestExists = request.Customer.Groups.FirstOrDefault(cr => cr == guestGroup?.Id);
- if (guestExists != null)
+ break;
+ case PasswordFormat.Encrypted:
{
- request.Customer.Groups.Remove(guestGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(guestGroup, request.Customer.Id);
+ customer.PasswordSalt = CommonHelper.GenerateRandomDigitCode(24);
+ customer.Password = _encryptionService.EncryptText(request.NewPassword, customer.PasswordSalt);
}
- request.Customer.PasswordChangeDateUtc = DateTime.UtcNow;
- await _customerService.UpdateCustomer(request.Customer);
-
- }
-
- /// <summary>
- /// Change password
- /// </summary>
- /// <param name="request">Request</param>
- public virtual async Task ChangePassword(ChangePasswordRequest request)
- {
- ArgumentNullException.ThrowIfNull(request);
-
- var customer = await _customerService.GetCustomerByEmail(request.Email);
- if (customer == null)
- throw new ArgumentNullException(nameof(customer));
-
- switch (request.PasswordFormat)
+ break;
+ case PasswordFormat.Hashed:
{
- case PasswordFormat.Clear:
- {
- customer.Password = request.NewPassword;
- }
- break;
- case PasswordFormat.Encrypted:
- {
- customer.PasswordSalt = CommonHelper.GenerateRandomDigitCode(24);
- customer.Password = _encryptionService.EncryptText(request.NewPassword, customer.PasswordSalt);
- }
- break;
- case PasswordFormat.Hashed:
- {
- var saltKey = _encryptionService.CreateSaltKey(5);
- customer.PasswordSalt = saltKey;
- customer.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey, _customerSettings.HashedPasswordFormat);
- }
- break;
+ var saltKey = _encryptionService.CreateSaltKey(5);
+ customer.PasswordSalt = saltKey;
+ customer.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey,
+ _customerSettings.HashedPasswordFormat);
}
- customer.PasswordChangeDateUtc = DateTime.UtcNow;
- customer.PasswordFormatId = request.PasswordFormat;
- await _customerService.UpdateCustomer(customer);
- //insert password history
- await _customerHistoryPasswordService.InsertCustomerPassword(customer);
-
- //create new login token
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString());
+ break;
}
-
- #endregion
+
+ customer.PasswordChangeDateUtc = DateTime.UtcNow;
+ customer.PasswordFormatId = request.PasswordFormat;
+ await _customerService.UpdateCustomer(customer);
+ //insert password history
+ await _customerHistoryPasswordService.InsertCustomerPassword(customer);
+
+ //create new login token
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString());
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs
index 547b8631c..318020435 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs
@@ -1,85 +1,84 @@
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+public class CustomerNoteService : ICustomerNoteService
{
- public class CustomerNoteService : ICustomerNoteService
+ private readonly IRepository<CustomerNote> _customerNoteRepository;
+ private readonly IMediator _mediator;
+
+ public CustomerNoteService(IRepository<CustomerNote> customerNoteRepository,
+ IMediator mediator)
+ {
+ _customerNoteRepository = customerNoteRepository;
+ _mediator = mediator;
+ }
+
+ #region Customer note
+
+ /// <summary>
+ /// Get note for customer
+ /// </summary>
+ /// <param name="id">Note identifier</param>
+ /// <returns>CustomerNote</returns>
+ public virtual Task<CustomerNote> GetCustomerNote(string id)
+ {
+ return string.IsNullOrWhiteSpace(id)
+ ? Task.FromResult<CustomerNote>(null)
+ : _customerNoteRepository.GetByIdAsync(id);
+ }
+
+ /// <summary>
+ /// Insert an customer note
+ /// </summary>
+ /// <param name="customerNote">The customer note</param>
+ public virtual async Task InsertCustomerNote(CustomerNote customerNote)
{
- private readonly IRepository<CustomerNote> _customerNoteRepository;
- private readonly IMediator _mediator;
-
- public CustomerNoteService(IRepository<CustomerNote> customerNoteRepository,
- IMediator mediator)
- {
- _customerNoteRepository = customerNoteRepository;
- _mediator = mediator;
- }
-
- #region Customer note
-
- /// <summary>
- /// Get note for customer
- /// </summary>
- /// <param name="id">Note identifier</param>
- /// <returns>CustomerNote</returns>
- public virtual Task<CustomerNote> GetCustomerNote(string id)
- {
- return string.IsNullOrWhiteSpace(id) ? Task.FromResult<CustomerNote>(null) : _customerNoteRepository.GetByIdAsync(id);
- }
-
- /// <summary>
- /// Insert an customer note
- /// </summary>
- /// <param name="customerNote">The customer note</param>
- public virtual async Task InsertCustomerNote(CustomerNote customerNote)
- {
- ArgumentNullException.ThrowIfNull(customerNote);
-
- await _customerNoteRepository.InsertAsync(customerNote);
-
- //event notification
- await _mediator.EntityInserted(customerNote);
- }
-
- /// <summary>
- /// Deletes an customer note
- /// </summary>
- /// <param name="customerNote">The customer note</param>
- public virtual async Task DeleteCustomerNote(CustomerNote customerNote)
- {
- ArgumentNullException.ThrowIfNull(customerNote);
-
- await _customerNoteRepository.DeleteAsync(customerNote);
-
- //event notification
- await _mediator.EntityDeleted(customerNote);
- }
-
- /// <summary>
- /// Get notes for customer
- /// </summary>
- /// <param name="customerId">Customer identifier</param>
- /// <param name="displayToCustomer">Display to customer</param>
- /// <returns>OrderNote</returns>
- public virtual async Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displayToCustomer = null)
- {
- var query = from customerNote in _customerNoteRepository.Table
- where customerNote.CustomerId == customerId
- select customerNote;
-
- if (displayToCustomer.HasValue)
- query = query.Where(x => x.DisplayToCustomer == displayToCustomer.Value);
-
- query = query.OrderByDescending(x => x.CreatedOnUtc);
-
- return await Task.FromResult(query.ToList());
- }
-
- #endregion
+ ArgumentNullException.ThrowIfNull(customerNote);
+ await _customerNoteRepository.InsertAsync(customerNote);
+ //event notification
+ await _mediator.EntityInserted(customerNote);
}
-}
+
+ /// <summary>
+ /// Deletes an customer note
+ /// </summary>
+ /// <param name="customerNote">The customer note</param>
+ public virtual async Task DeleteCustomerNote(CustomerNote customerNote)
+ {
+ ArgumentNullException.ThrowIfNull(customerNote);
+
+ await _customerNoteRepository.DeleteAsync(customerNote);
+
+ //event notification
+ await _mediator.EntityDeleted(customerNote);
+ }
+
+ /// <summary>
+ /// Get notes for customer
+ /// </summary>
+ /// <param name="customerId">Customer identifier</param>
+ /// <param name="displayToCustomer">Display to customer</param>
+ /// <returns>OrderNote</returns>
+ public virtual async Task<IList<CustomerNote>> GetCustomerNotes(string customerId, bool? displayToCustomer = null)
+ {
+ var query = from customerNote in _customerNoteRepository.Table
+ where customerNote.CustomerId == customerId
+ select customerNote;
+
+ if (displayToCustomer.HasValue)
+ query = query.Where(x => x.DisplayToCustomer == displayToCustomer.Value);
+
+ query = query.OrderByDescending(x => x.CreatedOnUtc);
+
+ return await Task.FromResult(query.ToList());
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
index 4b2965bd7..d0a11f290 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
@@ -1,697 +1,713 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Queries.Customers;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
+using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel;
using MediatR;
using System.Linq.Expressions;
-using Grand.Infrastructure.Caching;
-using Grand.Infrastructure.Caching.Constants;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Customer service
+/// </summary>
+public class CustomerService : ICustomerService
{
- /// <summary>
- /// Customer service
- /// </summary>
- public class CustomerService : ICustomerService
+ #region Ctor
+
+ public CustomerService(
+ IRepository<Customer> customerRepository,
+ IUserFieldService userFieldService,
+ IMediator mediator,
+ ICacheBase cacheBase)
{
- #region Fields
+ _customerRepository = customerRepository;
+ _userFieldService = userFieldService;
+ _mediator = mediator;
+ _cacheBase = cacheBase;
+ }
- private readonly IRepository<Customer> _customerRepository;
- private readonly IUserFieldService _userFieldService;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<Customer> _customerRepository;
+ private readonly IUserFieldService _userFieldService;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- public CustomerService(
- IRepository<Customer> customerRepository,
- IUserFieldService userFieldService,
- IMediator mediator,
- ICacheBase cacheBase)
- {
- _customerRepository = customerRepository;
- _userFieldService = userFieldService;
- _mediator = mediator;
- _cacheBase = cacheBase;
- }
+ #endregion
- #endregion
-
- #region Customers
-
- /// <summary>
- /// Gets all customers
- /// </summary>
- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
- /// <param name="affiliateId">Affiliate identifier</param>
- /// <param name="vendorId">Vendor identifier</param>
- /// <param name="storeId">Store identifier</param>
- /// <param name="ownerId">Owner identifier</param>
- /// <param name="salesEmployeeId">Sales employee identifier</param>
- /// <param name="customerGroupIds">A list of customer group identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param>
- /// <param name="customerTagIds">customer tags ids</param>
- /// <param name="email">Email; null to load all customers</param>
- /// <param name="username">Username; null to load all customers</param>
- /// <param name="firstName">First name; null to load all customers</param>
- /// <param name="lastName">Last name; null to load all customers</param>
- /// <param name="company">Company; null to load all customers</param>
- /// <param name="phone">Phone; null to load all customers</param>
- /// <param name="zipPostalCode">Phone; null to load all customers</param>
- /// <param name="loadOnlyWithShoppingCart">Value indicating whether to load customers only with shopping cart</param>
- /// <param name="sct">Value indicating what shopping cart type to filter; used when 'loadOnlyWithShoppingCart' param is 'true'</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="orderBySelector">order by selector</param>
- /// <returns>Customers</returns>
- public virtual async Task<IPagedList<Customer>> GetAllCustomers(DateTime? createdFromUtc = null,
- DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "", string ownerId = "",
- string salesEmployeeId = "", string[] customerGroupIds = null, string[] customerTagIds = null, string email = null, string username = null,
- string firstName = null, string lastName = null,
- string company = null, string phone = null, string zipPostalCode = null,
- bool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null,
- int pageIndex = 0, int pageSize = 2147483647, Expression<Func<Customer, object>> orderBySelector = null)
- {
- var queryModel = new GetCustomerQuery {
- CreatedFromUtc = createdFromUtc,
- CreatedToUtc = createdToUtc,
- AffiliateId = affiliateId,
- VendorId = vendorId,
- StoreId = storeId,
- OwnerId = ownerId,
- SalesEmployeeId = salesEmployeeId,
- CustomerGroupIds = customerGroupIds,
- CustomerTagIds = customerTagIds,
- Email = email,
- Username = username,
- FirstName = firstName,
- LastName = lastName,
- Company = company,
- Phone = phone,
- ZipPostalCode = zipPostalCode,
- LoadOnlyWithShoppingCart = loadOnlyWithShoppingCart,
- Sct = sct,
- PageIndex = pageIndex,
- PageSize = pageSize,
- OrderBySelector = orderBySelector
- };
- var query = await _mediator.Send(queryModel);
- return await PagedList<Customer>.Create(query, pageIndex, pageSize);
- }
-
- /// <summary>
- /// Gets online customers
- /// </summary>
- /// <param name="lastActivityFromUtc">Customer last activity date (from)</param>
- /// <param name="customerGroupIds">A list of customer group identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param>
- /// <param name="storeId">Store ident</param>
- /// <param name="salesEmployeeId">Sales employee ident</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
-
- /// <returns>Customers</returns>
- public virtual async Task<IPagedList<Customer>> GetOnlineCustomers(DateTime lastActivityFromUtc,
- string[] customerGroupIds, string storeId = "", string salesEmployeeId = "", int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _customerRepository.Table
- select p;
+ #region Customers
- query = query.Where(c => lastActivityFromUtc <= c.LastActivityDateUtc);
- query = query.Where(c => !c.Deleted);
+ /// <summary>
+ /// Gets all customers
+ /// </summary>
+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
+ /// <param name="affiliateId">Affiliate identifier</param>
+ /// <param name="vendorId">Vendor identifier</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <param name="ownerId">Owner identifier</param>
+ /// <param name="salesEmployeeId">Sales employee identifier</param>
+ /// <param name="customerGroupIds">
+ /// A list of customer group identifiers to filter by (at least one match); pass null or
+ /// empty list in order to load all customers;
+ /// </param>
+ /// <param name="customerTagIds">customer tags ids</param>
+ /// <param name="email">Email; null to load all customers</param>
+ /// <param name="username">Username; null to load all customers</param>
+ /// <param name="firstName">First name; null to load all customers</param>
+ /// <param name="lastName">Last name; null to load all customers</param>
+ /// <param name="company">Company; null to load all customers</param>
+ /// <param name="phone">Phone; null to load all customers</param>
+ /// <param name="zipPostalCode">Phone; null to load all customers</param>
+ /// <param name="loadOnlyWithShoppingCart">Value indicating whether to load customers only with shopping cart</param>
+ /// <param name="sct">
+ /// Value indicating what shopping cart type to filter; used when 'loadOnlyWithShoppingCart' param is
+ /// 'true'
+ /// </param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="orderBySelector">order by selector</param>
+ /// <returns>Customers</returns>
+ public virtual async Task<IPagedList<Customer>> GetAllCustomers(DateTime? createdFromUtc = null,
+ DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "",
+ string ownerId = "",
+ string salesEmployeeId = "", string[] customerGroupIds = null, string[] customerTagIds = null,
+ string email = null, string username = null,
+ string firstName = null, string lastName = null,
+ string company = null, string phone = null, string zipPostalCode = null,
+ bool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null,
+ int pageIndex = 0, int pageSize = 2147483647, Expression<Func<Customer, object>> orderBySelector = null)
+ {
+ var queryModel = new GetCustomerQuery {
+ CreatedFromUtc = createdFromUtc,
+ CreatedToUtc = createdToUtc,
+ AffiliateId = affiliateId,
+ VendorId = vendorId,
+ StoreId = storeId,
+ OwnerId = ownerId,
+ SalesEmployeeId = salesEmployeeId,
+ CustomerGroupIds = customerGroupIds,
+ CustomerTagIds = customerTagIds,
+ Email = email,
+ Username = username,
+ FirstName = firstName,
+ LastName = lastName,
+ Company = company,
+ Phone = phone,
+ ZipPostalCode = zipPostalCode,
+ LoadOnlyWithShoppingCart = loadOnlyWithShoppingCart,
+ Sct = sct,
+ PageIndex = pageIndex,
+ PageSize = pageSize,
+ OrderBySelector = orderBySelector
+ };
+ var query = await _mediator.Send(queryModel);
+ return await PagedList<Customer>.Create(query, pageIndex, pageSize);
+ }
- if (customerGroupIds is { Length: > 0 })
- query = query.Where(c => c.Groups.Select(cr => cr).Intersect(customerGroupIds).Any());
+ /// <summary>
+ /// Gets online customers
+ /// </summary>
+ /// <param name="lastActivityFromUtc">Customer last activity date (from)</param>
+ /// <param name="customerGroupIds">
+ /// A list of customer group identifiers to filter by (at least one match); pass null or
+ /// empty list in order to load all customers;
+ /// </param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="salesEmployeeId">Sales employee ident</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>Customers</returns>
+ public virtual async Task<IPagedList<Customer>> GetOnlineCustomers(DateTime lastActivityFromUtc,
+ string[] customerGroupIds, string storeId = "", string salesEmployeeId = "", int pageIndex = 0,
+ int pageSize = int.MaxValue)
+ {
+ var query = from p in _customerRepository.Table
+ select p;
- if (!string.IsNullOrEmpty(storeId))
- query = query.Where(c => c.StoreId == storeId);
+ query = query.Where(c => lastActivityFromUtc <= c.LastActivityDateUtc);
+ query = query.Where(c => !c.Deleted);
- if (!string.IsNullOrEmpty(salesEmployeeId))
- query = query.Where(c => c.SeId == salesEmployeeId);
+ if (customerGroupIds is { Length: > 0 })
+ query = query.Where(c => c.Groups.Select(cr => cr).Intersect(customerGroupIds).Any());
- query = query.OrderByDescending(c => c.LastActivityDateUtc);
- return await PagedList<Customer>.Create(query, pageIndex, pageSize);
- }
+ if (!string.IsNullOrEmpty(storeId))
+ query = query.Where(c => c.StoreId == storeId);
- /// <summary>
- /// Gets count online customers
- /// </summary>
- /// <param name="lastActivityFromUtc">Customer last activity date (from)</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="salesEmployeeId">Sales employee ident</param>
- /// <returns>Int</returns>
- public virtual async Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeId = "", string salesEmployeeId = "")
- {
- var query = from p in _customerRepository.Table
- select p;
+ if (!string.IsNullOrEmpty(salesEmployeeId))
+ query = query.Where(c => c.SeId == salesEmployeeId);
- query = query.Where(c => c.Active);
- query = query.Where(c => lastActivityFromUtc <= c.LastUpdateCartDateUtc);
- query = query.Where(c => c.ShoppingCartItems.Any(y => y.ShoppingCartTypeId == ShoppingCartType.ShoppingCart));
+ query = query.OrderByDescending(c => c.LastActivityDateUtc);
+ return await PagedList<Customer>.Create(query, pageIndex, pageSize);
+ }
- if (!string.IsNullOrEmpty(storeId))
- query = query.Where(c => c.StoreId == storeId);
+ /// <summary>
+ /// Gets count online customers
+ /// </summary>
+ /// <param name="lastActivityFromUtc">Customer last activity date (from)</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="salesEmployeeId">Sales employee ident</param>
+ /// <returns>Int</returns>
+ public virtual async Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeId = "",
+ string salesEmployeeId = "")
+ {
+ var query = from p in _customerRepository.Table
+ select p;
- if (!string.IsNullOrEmpty(salesEmployeeId))
- query = query.Where(c => c.SeId == salesEmployeeId);
+ query = query.Where(c => c.Active);
+ query = query.Where(c => lastActivityFromUtc <= c.LastUpdateCartDateUtc);
+ query = query.Where(c => c.ShoppingCartItems.Any(y => y.ShoppingCartTypeId == ShoppingCartType.ShoppingCart));
- return await Task.FromResult(query.Count());
- }
+ if (!string.IsNullOrEmpty(storeId))
+ query = query.Where(c => c.StoreId == storeId);
- /// <summary>
- /// Gets a customer
- /// </summary>
- /// <param name="customerId">Customer identifier</param>
- /// <returns>A customer</returns>
- public virtual Task<Customer> GetCustomerById(string customerId)
- {
- return string.IsNullOrWhiteSpace(customerId) ? Task.FromResult<Customer>(null) : _customerRepository.GetByIdAsync(customerId);
- }
+ if (!string.IsNullOrEmpty(salesEmployeeId))
+ query = query.Where(c => c.SeId == salesEmployeeId);
- /// <summary>
- /// Get customers by identifiers
- /// </summary>
- /// <param name="customerIds">Customer identifiers</param>
- /// <returns>Customers</returns>
- public virtual async Task<IList<Customer>> GetCustomersByIds(string[] customerIds)
- {
- if (customerIds == null || customerIds.Length == 0)
- return new List<Customer>();
-
- var query = from c in _customerRepository.Table
- where customerIds.Contains(c.Id)
- select c;
- var customers = query.ToList();
- //sort by passed identifiers
- var sortedCustomers = customerIds.Select(id => customers.Find(x => x.Id == id)).Where(customer => customer != null).ToList();
- return await Task.FromResult(sortedCustomers);
- }
+ return await Task.FromResult(query.Count());
+ }
- /// <summary>
- /// Gets a customer by GUID
- /// </summary>
- /// <param name="customerGuid">Customer GUID</param>
- /// <returns>A customer</returns>
- public virtual async Task<Customer> GetCustomerByGuid(Guid customerGuid)
- {
- return await _customerRepository.GetOneAsync(x => x.CustomerGuid == customerGuid);
- }
+ /// <summary>
+ /// Gets a customer
+ /// </summary>
+ /// <param name="customerId">Customer identifier</param>
+ /// <returns>A customer</returns>
+ public virtual Task<Customer> GetCustomerById(string customerId)
+ {
+ return string.IsNullOrWhiteSpace(customerId)
+ ? Task.FromResult<Customer>(null)
+ : _customerRepository.GetByIdAsync(customerId);
+ }
- /// <summary>
- /// Get customer by email
- /// </summary>
- /// <param name="email">Email</param>
- /// <returns>Customer</returns>
- public virtual async Task<Customer> GetCustomerByEmail(string email)
- {
- return string.IsNullOrWhiteSpace(email) ? null : await _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant());
- }
+ /// <summary>
+ /// Get customers by identifiers
+ /// </summary>
+ /// <param name="customerIds">Customer identifiers</param>
+ /// <returns>Customers</returns>
+ public virtual async Task<IList<Customer>> GetCustomersByIds(string[] customerIds)
+ {
+ if (customerIds == null || customerIds.Length == 0)
+ return new List<Customer>();
+
+ var query = from c in _customerRepository.Table
+ where customerIds.Contains(c.Id)
+ select c;
+ var customers = query.ToList();
+ //sort by passed identifiers
+ var sortedCustomers = customerIds.Select(id => customers.Find(x => x.Id == id))
+ .Where(customer => customer != null).ToList();
+ return await Task.FromResult(sortedCustomers);
+ }
- /// <summary>
- /// Get customer by system name
- /// </summary>
- /// <param name="systemName">System name</param>
- /// <returns>Customer</returns>
- public virtual Task<Customer> GetCustomerBySystemName(string systemName)
- {
- if (string.IsNullOrWhiteSpace(systemName))
- return null;
+ /// <summary>
+ /// Gets a customer by GUID
+ /// </summary>
+ /// <param name="customerGuid">Customer GUID</param>
+ /// <returns>A customer</returns>
+ public virtual async Task<Customer> GetCustomerByGuid(Guid customerGuid)
+ {
+ return await _customerRepository.GetOneAsync(x => x.CustomerGuid == customerGuid);
+ }
- var key = string.Format(CacheKey.CUSTOMER_BY_SYSTEMNAME_BY_KEY, systemName);
+ /// <summary>
+ /// Get customer by email
+ /// </summary>
+ /// <param name="email">Email</param>
+ /// <returns>Customer</returns>
+ public virtual async Task<Customer> GetCustomerByEmail(string email)
+ {
+ return string.IsNullOrWhiteSpace(email)
+ ? null
+ : await _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant());
+ }
- return _cacheBase.GetAsync(key, () => _customerRepository.GetOneAsync(x => x.SystemName == systemName));
- }
+ /// <summary>
+ /// Get customer by system name
+ /// </summary>
+ /// <param name="systemName">System name</param>
+ /// <returns>Customer</returns>
+ public virtual Task<Customer> GetCustomerBySystemName(string systemName)
+ {
+ if (string.IsNullOrWhiteSpace(systemName))
+ return null;
- /// <summary>
- /// Get customer by username
- /// </summary>
- /// <param name="username">Username</param>
- /// <returns>Customer</returns>
- public virtual async Task<Customer> GetCustomerByUsername(string username)
- {
- if (string.IsNullOrWhiteSpace(username))
- return null;
+ var key = string.Format(CacheKey.CUSTOMER_BY_SYSTEMNAME_BY_KEY, systemName);
- return await _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant());
- }
+ return _cacheBase.GetAsync(key, () => _customerRepository.GetOneAsync(x => x.SystemName == systemName));
+ }
- /// <summary>
- /// Insert a guest customer
- /// </summary>
- /// <returns>Customer</returns>
- public virtual async Task<Customer> InsertGuestCustomer(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- //add to 'Guests' group
- var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery { SystemName = SystemCustomerGroupNames.Guests });
- if (guestGroup == null)
- throw new GrandException("'Guests' group could not be loaded");
- customer.Groups.Add(guestGroup.Id);
+ /// <summary>
+ /// Get customer by username
+ /// </summary>
+ /// <param name="username">Username</param>
+ /// <returns>Customer</returns>
+ public virtual async Task<Customer> GetCustomerByUsername(string username)
+ {
+ if (string.IsNullOrWhiteSpace(username))
+ return null;
- await _customerRepository.InsertAsync(customer);
+ return await _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant());
+ }
- //event notification
- await _mediator.EntityInserted(customer);
+ /// <summary>
+ /// Insert a guest customer
+ /// </summary>
+ /// <returns>Customer</returns>
+ public virtual async Task<Customer> InsertGuestCustomer(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- return customer;
- }
+ //add to 'Guests' group
+ var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery
+ { SystemName = SystemCustomerGroupNames.Guests });
+ if (guestGroup == null)
+ throw new GrandException("'Guests' group could not be loaded");
+ customer.Groups.Add(guestGroup.Id);
- /// <summary>
- /// Insert a customer
- /// </summary>
- /// <param name="customer">Customer</param>
- public virtual async Task InsertCustomer(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ await _customerRepository.InsertAsync(customer);
- if (!string.IsNullOrEmpty(customer.Email))
- customer.Email = customer.Email.ToLowerInvariant();
+ //event notification
+ await _mediator.EntityInserted(customer);
- if (!string.IsNullOrEmpty(customer.Username))
- customer.Username = customer.Username.ToLowerInvariant();
+ return customer;
+ }
- await _customerRepository.InsertAsync(customer);
+ /// <summary>
+ /// Insert a customer
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ public virtual async Task InsertCustomer(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- //event notification
- await _mediator.EntityInserted(customer);
- }
+ if (!string.IsNullOrEmpty(customer.Email))
+ customer.Email = customer.Email.ToLowerInvariant();
- /// <summary>
- /// Updates the customer field
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="expression">expression</param>
- /// <param name="value">value</param>
- public virtual async Task UpdateCustomerField<T>(Customer customer,
- Expression<Func<Customer, T>> expression, T value)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ if (!string.IsNullOrEmpty(customer.Username))
+ customer.Username = customer.Username.ToLowerInvariant();
- await UpdateCustomerField(customer.Id, expression, value);
+ await _customerRepository.InsertAsync(customer);
- }
+ //event notification
+ await _mediator.EntityInserted(customer);
+ }
- /// <summary>
- /// Updates the customer field
- /// </summary>
- /// <param name="customerId">Customer ident</param>
- /// <param name="expression">Expression</param>
- /// <param name="value">value</param>
- public virtual async Task UpdateCustomerField<T>(string customerId,
- Expression<Func<Customer, T>> expression, T value)
- {
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ /// <summary>
+ /// Updates the customer field
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="expression">expression</param>
+ /// <param name="value">value</param>
+ public virtual async Task UpdateCustomerField<T>(Customer customer,
+ Expression<Func<Customer, T>> expression, T value)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- await _customerRepository.UpdateField(customerId, expression, value);
+ await UpdateCustomerField(customer.Id, expression, value);
+ }
- }
- /// <summary>
- /// Updates the customer
- /// </summary>
- /// <param name="customer">Customer</param>
- public virtual async Task UpdateCustomer(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- if (customer.IsSystemAccount)
- throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated");
-
- var update = UpdateBuilder<Customer>.Create()
- .Set(x => x.Email, string.IsNullOrEmpty(customer.Email) ? "" : customer.Email.ToLowerInvariant())
- .Set(x => x.PasswordFormatId, customer.PasswordFormatId)
- .Set(x => x.PasswordSalt, customer.PasswordSalt)
- .Set(x => x.Active, customer.Active)
- .Set(x => x.StoreId, customer.StoreId)
- .Set(x => x.Password, customer.Password)
- .Set(x => x.PasswordChangeDateUtc, customer.PasswordChangeDateUtc)
- .Set(x => x.Username, string.IsNullOrEmpty(customer.Username) ? "" : customer.Username.ToLowerInvariant())
- .Set(x => x.Deleted, customer.Deleted);
-
- await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
-
- //event notification
- await _mediator.EntityUpdated(customer);
- }
+ /// <summary>
+ /// Updates the customer field
+ /// </summary>
+ /// <param name="customerId">Customer ident</param>
+ /// <param name="expression">Expression</param>
+ /// <param name="value">value</param>
+ public virtual async Task UpdateCustomerField<T>(string customerId,
+ Expression<Func<Customer, T>> expression, T value)
+ {
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
+ await _customerRepository.UpdateField(customerId, expression, value);
+ }
- /// <summary>
- /// Delete a customer
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="hard">Hard delete from database</param>
- public virtual async Task DeleteCustomer(Customer customer, bool hard = false)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- if (customer.IsSystemAccount)
- throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be deleted");
-
- customer.Deleted = true;
- customer.Email = $"DELETED_@{DateTime.UtcNow.Ticks}.COM";
- customer.Username = customer.Email;
-
- //delete address
- customer.Addresses.Clear();
- customer.BillingAddress = null;
- customer.ShippingAddress = null;
- //delete user fields
- customer.UserFields.Clear();
- //delete shopping cart
- customer.ShoppingCartItems.Clear();
- //delete customer groups
- customer.Groups.Clear();
- //clear customer tags
- customer.CustomerTags.Clear();
- //update customer
- await _customerRepository.UpdateAsync(customer);
-
- if (hard)
- await _customerRepository.DeleteAsync(customer);
-
- //event notification
- await _mediator.EntityDeleted(customer);
+ /// <summary>
+ /// Updates the customer
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ public virtual async Task UpdateCustomer(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
+
+ if (customer.IsSystemAccount)
+ throw new GrandException(
+ $"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated");
+
+ var update = UpdateBuilder<Customer>.Create()
+ .Set(x => x.Email, string.IsNullOrEmpty(customer.Email) ? "" : customer.Email.ToLowerInvariant())
+ .Set(x => x.PasswordFormatId, customer.PasswordFormatId)
+ .Set(x => x.PasswordSalt, customer.PasswordSalt)
+ .Set(x => x.Active, customer.Active)
+ .Set(x => x.StoreId, customer.StoreId)
+ .Set(x => x.Password, customer.Password)
+ .Set(x => x.PasswordChangeDateUtc, customer.PasswordChangeDateUtc)
+ .Set(x => x.Username, string.IsNullOrEmpty(customer.Username) ? "" : customer.Username.ToLowerInvariant())
+ .Set(x => x.Deleted, customer.Deleted);
+
+ await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+
+ //event notification
+ await _mediator.EntityUpdated(customer);
+ }
- }
- /// <summary>
- /// Updates the customer - last activity date
- /// </summary>
- /// <param name="customer">Customer</param>
- public virtual async Task UpdateCustomerLastLoginDate(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ /// <summary>
+ /// Delete a customer
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="hard">Hard delete from database</param>
+ public virtual async Task DeleteCustomer(Customer customer, bool hard = false)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
+
+ if (customer.IsSystemAccount)
+ throw new GrandException(
+ $"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be deleted");
+
+ customer.Deleted = true;
+ customer.Email = $"DELETED_@{DateTime.UtcNow.Ticks}.COM";
+ customer.Username = customer.Email;
+
+ //delete address
+ customer.Addresses.Clear();
+ customer.BillingAddress = null;
+ customer.ShippingAddress = null;
+ //delete user fields
+ customer.UserFields.Clear();
+ //delete shopping cart
+ customer.ShoppingCartItems.Clear();
+ //delete customer groups
+ customer.Groups.Clear();
+ //clear customer tags
+ customer.CustomerTags.Clear();
+ //update customer
+ await _customerRepository.UpdateAsync(customer);
+
+ if (hard)
+ await _customerRepository.DeleteAsync(customer);
+
+ //event notification
+ await _mediator.EntityDeleted(customer);
+ }
- var update = UpdateBuilder<Customer>.Create()
- .Set(x => x.LastLoginDateUtc, customer.LastLoginDateUtc)
- .Set(x => x.FailedLoginAttempts, customer.FailedLoginAttempts)
- .Set(x => x.CannotLoginUntilDateUtc, customer.CannotLoginUntilDateUtc);
+ /// <summary>
+ /// Updates the customer - last activity date
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ public virtual async Task UpdateCustomerLastLoginDate(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+ var update = UpdateBuilder<Customer>.Create()
+ .Set(x => x.LastLoginDateUtc, customer.LastLoginDateUtc)
+ .Set(x => x.FailedLoginAttempts, customer.FailedLoginAttempts)
+ .Set(x => x.CannotLoginUntilDateUtc, customer.CannotLoginUntilDateUtc);
- }
+ await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+ }
- public virtual async Task UpdateCustomerInAdminPanel(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- if (customer.IsSystemAccount)
- throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated");
-
- var update = UpdateBuilder<Customer>.Create()
- .Set(x => x.Active, customer.Active)
- .Set(x => x.AdminComment, customer.AdminComment)
- .Set(x => x.AffiliateId, customer.AffiliateId)
- .Set(x => x.Active, customer.Active)
- .Set(x => x.Email, string.IsNullOrEmpty(customer.Email) ? "" : customer.Email.ToLowerInvariant())
- .Set(x => x.IsTaxExempt, customer.IsTaxExempt)
- .Set(x => x.Password, customer.Password)
- .Set(x => x.Username, string.IsNullOrEmpty(customer.Username) ? "" : customer.Username.ToLowerInvariant())
- .Set(x => x.Groups, customer.Groups)
- .Set(x => x.Addresses, customer.Addresses)
- .Set(x => x.FreeShipping, customer.FreeShipping)
- .Set(x => x.VendorId, customer.VendorId)
- .Set(x => x.SeId, customer.SeId)
- .Set(x => x.OwnerId, customer.OwnerId)
- .Set(x => x.StaffStoreId, customer.StaffStoreId)
- .Set(x => x.Attributes, customer.Attributes);
-
- await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
- //event notification
- await _mediator.EntityUpdated(customer);
+ public virtual async Task UpdateCustomerInAdminPanel(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
+
+ if (customer.IsSystemAccount)
+ throw new GrandException(
+ $"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated");
+
+ var update = UpdateBuilder<Customer>.Create()
+ .Set(x => x.Active, customer.Active)
+ .Set(x => x.AdminComment, customer.AdminComment)
+ .Set(x => x.AffiliateId, customer.AffiliateId)
+ .Set(x => x.Active, customer.Active)
+ .Set(x => x.Email, string.IsNullOrEmpty(customer.Email) ? "" : customer.Email.ToLowerInvariant())
+ .Set(x => x.IsTaxExempt, customer.IsTaxExempt)
+ .Set(x => x.Password, customer.Password)
+ .Set(x => x.Username, string.IsNullOrEmpty(customer.Username) ? "" : customer.Username.ToLowerInvariant())
+ .Set(x => x.Groups, customer.Groups)
+ .Set(x => x.Addresses, customer.Addresses)
+ .Set(x => x.FreeShipping, customer.FreeShipping)
+ .Set(x => x.VendorId, customer.VendorId)
+ .Set(x => x.SeId, customer.SeId)
+ .Set(x => x.OwnerId, customer.OwnerId)
+ .Set(x => x.StaffStoreId, customer.StaffStoreId)
+ .Set(x => x.Attributes, customer.Attributes);
+
+ await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+ //event notification
+ await _mediator.EntityUpdated(customer);
+ }
- }
+ public virtual async Task UpdateActive(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- public virtual async Task UpdateActive(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ var update = UpdateBuilder<Customer>.Create()
+ .Set(x => x.Active, customer.Active)
+ .Set(x => x.StoreId, customer.StoreId);
- var update = UpdateBuilder<Customer>.Create()
- .Set(x => x.Active, customer.Active)
- .Set(x => x.StoreId, customer.StoreId);
+ await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
- await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
+ //event notification
+ await _mediator.EntityUpdated(customer);
+ }
- //event notification
- await _mediator.EntityUpdated(customer);
- }
+ public virtual async Task UpdateContributions(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- public virtual async Task UpdateContributions(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ await UpdateCustomerField(customer.Id, x => x.HasContributions, true);
- await UpdateCustomerField(customer.Id, x => x.HasContributions, true);
+ //event notification
+ await _mediator.EntityUpdated(customer);
+ }
- //event notification
- await _mediator.EntityUpdated(customer);
- }
+ /// <summary>
+ /// Reset data required for checkout
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <param name="clearCouponCodes">A value indicating whether to clear coupon code</param>
+ /// <param name="clearCheckoutAttributes">A value indicating whether to clear selected checkout attributes</param>
+ /// <param name="clearLoyaltyPoints">A value indicating whether to clear "Use loyalty points" flag</param>
+ /// <param name="clearShipping">A value indicating whether to clear selected shipping method</param>
+ /// <param name="clearPayment">A value indicating whether to clear selected payment method</param>
+ public virtual async Task ResetCheckoutData(Customer customer, string storeId,
+ bool clearCouponCodes = false, bool clearCheckoutAttributes = false,
+ bool clearLoyaltyPoints = true, bool clearShipping = true, bool clearPayment = true)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- /// <summary>
- /// Reset data required for checkout
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="storeId">Store identifier</param>
- /// <param name="clearCouponCodes">A value indicating whether to clear coupon code</param>
- /// <param name="clearCheckoutAttributes">A value indicating whether to clear selected checkout attributes</param>
- /// <param name="clearLoyaltyPoints">A value indicating whether to clear "Use loyalty points" flag</param>
- /// <param name="clearShipping">A value indicating whether to clear selected shipping method</param>
- /// <param name="clearPayment">A value indicating whether to clear selected payment method</param>
- public virtual async Task ResetCheckoutData(Customer customer, string storeId,
- bool clearCouponCodes = false, bool clearCheckoutAttributes = false,
- bool clearLoyaltyPoints = true, bool clearShipping = true, bool clearPayment = true)
+ //clear entered coupon codes
+ if (clearCouponCodes)
{
- ArgumentNullException.ThrowIfNull(customer);
-
- //clear entered coupon codes
- if (clearCouponCodes)
- {
- await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.DiscountCoupons, null);
- await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.GiftVoucherCoupons, null);
- }
-
- //clear checkout attributes
- if (clearCheckoutAttributes)
- {
- await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.CheckoutAttributes, null, storeId);
- }
-
- //clear loyalty points flag
- if (clearLoyaltyPoints)
- {
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout, false, storeId);
- }
-
- //clear selected shipping method
- if (clearShipping)
- {
- await _userFieldService.SaveField<ShippingOption>(customer, SystemCustomerFieldNames.SelectedShippingOption, null, storeId);
- await _userFieldService.SaveField<ShippingOption>(customer, SystemCustomerFieldNames.OfferedShippingOptions, null, storeId);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.SelectedPickupPoint, "", storeId);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.ShippingOptionAttributeDescription, "", storeId);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.ShippingOptionAttribute, "", storeId);
- }
-
- //clear selected payment method
- if (clearPayment)
- {
- await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.SelectedPaymentMethod, null, storeId);
- await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.PaymentTransaction, null, storeId);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PaymentOptionAttribute, "", storeId);
- }
+ await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.DiscountCoupons, null);
+ await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.GiftVoucherCoupons, null);
}
- /// <summary>
- /// Delete guest customer records
- /// </summary>
- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
- /// <param name="onlyWithoutShoppingCart">A value indicating whether to delete customers only without shopping cart</param>
- /// <returns>Number of deleted customers</returns>
- public virtual async Task<int> DeleteGuestCustomers(DateTime? createdFromUtc, DateTime? createdToUtc, bool onlyWithoutShoppingCart)
- {
- var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery { SystemName = SystemCustomerGroupNames.Guests });
- if (guestGroup == null)
- throw new GrandException("Guests group could not be loaded");
+ //clear checkout attributes
+ if (clearCheckoutAttributes)
+ await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.CheckoutAttributes, null,
+ storeId);
- var query = from p in _customerRepository.Table
- select p;
+ //clear loyalty points flag
+ if (clearLoyaltyPoints)
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout, false,
+ storeId);
- query = query.Where(x => x.Groups.Contains(guestGroup.Id));
+ //clear selected shipping method
+ if (clearShipping)
+ {
+ await _userFieldService.SaveField<ShippingOption>(customer, SystemCustomerFieldNames.SelectedShippingOption,
+ null, storeId);
+ await _userFieldService.SaveField<ShippingOption>(customer, SystemCustomerFieldNames.OfferedShippingOptions,
+ null, storeId);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.SelectedPickupPoint, "", storeId);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.ShippingOptionAttributeDescription, "",
+ storeId);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.ShippingOptionAttribute, "", storeId);
+ }
- if (createdFromUtc.HasValue)
- query = query.Where(x => x.LastActivityDateUtc > createdFromUtc.Value);
- if (createdToUtc.HasValue)
- query = query.Where(x => x.LastActivityDateUtc < createdToUtc.Value);
- if (onlyWithoutShoppingCart)
- query = query.Where(x => !x.ShoppingCartItems.Any());
+ //clear selected payment method
+ if (clearPayment)
+ {
+ await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.SelectedPaymentMethod, null,
+ storeId);
+ await _userFieldService.SaveField<string>(customer, SystemCustomerFieldNames.PaymentTransaction, null,
+ storeId);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PaymentOptionAttribute, "", storeId);
+ }
+ }
- query = query.Where(x => !x.HasContributions);
+ /// <summary>
+ /// Delete guest customer records
+ /// </summary>
+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
+ /// <param name="onlyWithoutShoppingCart">A value indicating whether to delete customers only without shopping cart</param>
+ /// <returns>Number of deleted customers</returns>
+ public virtual async Task<int> DeleteGuestCustomers(DateTime? createdFromUtc, DateTime? createdToUtc,
+ bool onlyWithoutShoppingCart)
+ {
+ var guestGroup = await _mediator.Send(new GetGroupBySystemNameQuery
+ { SystemName = SystemCustomerGroupNames.Guests });
+ if (guestGroup == null)
+ throw new GrandException("Guests group could not be loaded");
- query = query.Where(x => !x.IsSystemAccount);
+ var query = from p in _customerRepository.Table
+ select p;
- var customers = await _customerRepository.DeleteAsync(query);
+ query = query.Where(x => x.Groups.Contains(guestGroup.Id));
- return customers.Count();
+ if (createdFromUtc.HasValue)
+ query = query.Where(x => x.LastActivityDateUtc > createdFromUtc.Value);
+ if (createdToUtc.HasValue)
+ query = query.Where(x => x.LastActivityDateUtc < createdToUtc.Value);
+ if (onlyWithoutShoppingCart)
+ query = query.Where(x => !x.ShoppingCartItems.Any());
- }
+ query = query.Where(x => !x.HasContributions);
- #endregion
+ query = query.Where(x => !x.IsSystemAccount);
- #region Customer group in customer
+ var customers = await _customerRepository.DeleteAsync(query);
- public virtual async Task DeleteCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId)
- {
- ArgumentNullException.ThrowIfNull(customerGroup);
+ return customers.Count();
+ }
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ #endregion
- await _customerRepository.Pull(customerId, x => x.Groups, customerGroup.Id);
- }
+ #region Customer group in customer
- public virtual async Task InsertCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId)
- {
- ArgumentNullException.ThrowIfNull(customerGroup);
+ public virtual async Task DeleteCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroup);
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- await _customerRepository.AddToSet(customerId, x => x.Groups, customerGroup.Id);
+ await _customerRepository.Pull(customerId, x => x.Groups, customerGroup.Id);
+ }
- }
+ public virtual async Task InsertCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroup);
- #endregion
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- #region Customer Address
+ await _customerRepository.AddToSet(customerId, x => x.Groups, customerGroup.Id);
+ }
- public virtual async Task DeleteAddress(Address address, string customerId)
- {
- ArgumentNullException.ThrowIfNull(address);
+ #endregion
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ #region Customer Address
- await _customerRepository.PullFilter(customerId, x => x.Addresses, x => x.Id, address.Id);
+ public virtual async Task DeleteAddress(Address address, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- //event notification
- await _mediator.EntityDeleted(address);
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- }
+ await _customerRepository.PullFilter(customerId, x => x.Addresses, x => x.Id, address.Id);
- public virtual async Task InsertAddress(Address address, string customerId)
- {
- ArgumentNullException.ThrowIfNull(address);
+ //event notification
+ await _mediator.EntityDeleted(address);
+ }
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ public virtual async Task InsertAddress(Address address, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- if (address.StateProvinceId == "0")
- address.StateProvinceId = "";
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- await _customerRepository.AddToSet(customerId, x => x.Addresses, address);
+ if (address.StateProvinceId == "0")
+ address.StateProvinceId = "";
- //event notification
- await _mediator.EntityInserted(address);
- }
+ await _customerRepository.AddToSet(customerId, x => x.Addresses, address);
- public virtual async Task UpdateAddress(Address address, string customerId)
- {
- ArgumentNullException.ThrowIfNull(address);
+ //event notification
+ await _mediator.EntityInserted(address);
+ }
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ public virtual async Task UpdateAddress(Address address, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- await _customerRepository.UpdateToSet(customerId, x => x.Addresses, z => z.Id, address.Id, address);
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- //event notification
- await _mediator.EntityUpdated(address);
- }
+ await _customerRepository.UpdateToSet(customerId, x => x.Addresses, z => z.Id, address.Id, address);
+ //event notification
+ await _mediator.EntityUpdated(address);
+ }
- public virtual async Task UpdateBillingAddress(Address address, string customerId)
- {
- ArgumentNullException.ThrowIfNull(address);
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ public virtual async Task UpdateBillingAddress(Address address, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- await _customerRepository.UpdateField(customerId, x => x.BillingAddress, address);
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- }
- public virtual async Task UpdateShippingAddress(Address address, string customerId)
- {
- ArgumentNullException.ThrowIfNull(address);
+ await _customerRepository.UpdateField(customerId, x => x.BillingAddress, address);
+ }
- if (string.IsNullOrEmpty(customerId))
- throw new ArgumentNullException(nameof(customerId));
+ public virtual async Task UpdateShippingAddress(Address address, string customerId)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- await _customerRepository.UpdateField(customerId, x => x.ShippingAddress, address);
- }
+ if (string.IsNullOrEmpty(customerId))
+ throw new ArgumentNullException(nameof(customerId));
- #endregion
+ await _customerRepository.UpdateField(customerId, x => x.ShippingAddress, address);
+ }
- #region Customer Shopping Cart Item
+ #endregion
- public virtual async Task DeleteShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
- {
- ArgumentNullException.ThrowIfNull(shoppingCartItem);
+ #region Customer Shopping Cart Item
- await _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, shoppingCartItem.Id);
+ public virtual async Task DeleteShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
+ {
+ ArgumentNullException.ThrowIfNull(shoppingCartItem);
- if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
- await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
- else
- await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
+ await _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, shoppingCartItem.Id);
- }
+ if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
+ await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
+ else
+ await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
+ }
- public virtual async Task ClearShoppingCartItem(string customerId, IList<ShoppingCartItem> cart)
- {
- foreach (var item in cart)
- {
- await _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, item.Id);
- }
-
- if (cart.Any(c => c.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions))
- await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
- if (cart.Any(c => c.ShoppingCartTypeId == ShoppingCartType.Wishlist))
- await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
- }
+ public virtual async Task ClearShoppingCartItem(string customerId, IList<ShoppingCartItem> cart)
+ {
+ foreach (var item in cart)
+ await _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, item.Id);
- public virtual async Task InsertShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
- {
- ArgumentNullException.ThrowIfNull(shoppingCartItem);
+ if (cart.Any(c => c.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions))
+ await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
+ if (cart.Any(c => c.ShoppingCartTypeId == ShoppingCartType.Wishlist))
+ await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
+ }
- await _customerRepository.AddToSet(customerId, x => x.ShoppingCartItems, shoppingCartItem);
+ public virtual async Task InsertShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
+ {
+ ArgumentNullException.ThrowIfNull(shoppingCartItem);
- if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
- await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
- else
- await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
- }
+ await _customerRepository.AddToSet(customerId, x => x.ShoppingCartItems, shoppingCartItem);
- public virtual async Task UpdateShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
- {
- ArgumentNullException.ThrowIfNull(shoppingCartItem);
+ if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
+ await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
+ else
+ await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
+ }
- await _customerRepository.UpdateToSet(customerId, x => x.ShoppingCartItems, z => z.Id, shoppingCartItem.Id, shoppingCartItem);
+ public virtual async Task UpdateShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem)
+ {
+ ArgumentNullException.ThrowIfNull(shoppingCartItem);
- if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
- await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
- else
- await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
+ await _customerRepository.UpdateToSet(customerId, x => x.ShoppingCartItems, z => z.Id, shoppingCartItem.Id,
+ shoppingCartItem);
- }
- #endregion
+ if (shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
+ await UpdateCustomerField(customerId, x => x.LastUpdateCartDateUtc, DateTime.UtcNow);
+ else
+ await UpdateCustomerField(customerId, x => x.LastUpdateWishListDateUtc, DateTime.UtcNow);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/ExportImport/AddressSchemaProperty.cs b/src/Business/Grand.Business.Customers/Services/ExportImport/AddressSchemaProperty.cs
index 92df96c47..e5ac71c30 100644
--- a/src/Business/Grand.Business.Customers/Services/ExportImport/AddressSchemaProperty.cs
+++ b/src/Business/Grand.Business.Customers/Services/ExportImport/AddressSchemaProperty.cs
@@ -3,32 +3,31 @@ using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Common;
-namespace Grand.Business.Customers.Services.ExportImport
+namespace Grand.Business.Customers.Services.ExportImport;
+
+public class AddressSchemaProperty : ISchemaProperty<Address>
{
- public class AddressSchemaProperty : ISchemaProperty<Address>
- {
- private readonly ICountryService _countryService;
+ private readonly ICountryService _countryService;
- public AddressSchemaProperty(ICountryService countryService)
- {
- _countryService = countryService;
- }
+ public AddressSchemaProperty(ICountryService countryService)
+ {
+ _countryService = countryService;
+ }
- public virtual async Task<PropertyByName<Address>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Address>("Email", p=>p.Email),
- new PropertyByName<Address>("FirstName", p=>p.FirstName),
- new PropertyByName<Address>("LastName", p=>p.LastName),
- new PropertyByName<Address>("PhoneNumber", p=>p.PhoneNumber),
- new PropertyByName<Address>("FaxNumber", p=>p.FaxNumber),
- new PropertyByName<Address>("Address1", p=>p.Address1),
- new PropertyByName<Address>("Address2", p=>p.Address2),
- new PropertyByName<Address>("City", p=>p.City),
- new PropertyByName<Address>("Country", p=> !string.IsNullOrEmpty(p.CountryId) ? _countryService.GetCountryById(p.CountryId).Result?.Name : "")
- };
- return await Task.FromResult(properties);
- }
+ public virtual async Task<PropertyByName<Address>[]> GetProperties()
+ {
+ var properties = new[] {
+ new PropertyByName<Address>("Email", p => p.Email),
+ new PropertyByName<Address>("FirstName", p => p.FirstName),
+ new PropertyByName<Address>("LastName", p => p.LastName),
+ new PropertyByName<Address>("PhoneNumber", p => p.PhoneNumber),
+ new PropertyByName<Address>("FaxNumber", p => p.FaxNumber),
+ new PropertyByName<Address>("Address1", p => p.Address1),
+ new PropertyByName<Address>("Address2", p => p.Address2),
+ new PropertyByName<Address>("City", p => p.City),
+ new PropertyByName<Address>("Country",
+ p => !string.IsNullOrEmpty(p.CountryId) ? _countryService.GetCountryById(p.CountryId).Result?.Name : "")
+ };
+ return await Task.FromResult(properties);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/ExportImport/CustomerSchemaProperty.cs b/src/Business/Grand.Business.Customers/Services/ExportImport/CustomerSchemaProperty.cs
index 96aa476da..8d8b01411 100644
--- a/src/Business/Grand.Business.Customers/Services/ExportImport/CustomerSchemaProperty.cs
+++ b/src/Business/Grand.Business.Customers/Services/ExportImport/CustomerSchemaProperty.cs
@@ -3,42 +3,52 @@ using Grand.Business.Core.Utilities.ExportImport;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-namespace Grand.Business.Customers.Services.ExportImport
+namespace Grand.Business.Customers.Services.ExportImport;
+
+public class CustomerSchemaProperty : ISchemaProperty<Customer>
{
- public class CustomerSchemaProperty : ISchemaProperty<Customer>
+ public virtual async Task<PropertyByName<Customer>[]> GetProperties()
{
- public virtual async Task<PropertyByName<Customer>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<Customer>("CustomerId", p => p.Id),
- new PropertyByName<Customer>("CustomerGuid", p => p.CustomerGuid),
- new PropertyByName<Customer>("Email", p => p.Email),
- new PropertyByName<Customer>("Username", p => p.Username),
- new PropertyByName<Customer>("Password", p => p.Password),
- new PropertyByName<Customer>("PasswordFormatId", p => p.PasswordFormatId),
- new PropertyByName<Customer>("PasswordSalt", p => p.PasswordSalt),
- new PropertyByName<Customer>("IsTaxExempt", p => p.IsTaxExempt),
- new PropertyByName<Customer>("AffiliateId", p => p.AffiliateId),
- new PropertyByName<Customer>("VendorId", p => p.VendorId),
- new PropertyByName<Customer>("Active", p => p.Active),
- //attributes
- new PropertyByName<Customer>("FirstName", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName)),
- new PropertyByName<Customer>("LastName", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName)),
- new PropertyByName<Customer>("Gender", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Gender)),
- new PropertyByName<Customer>("Company", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company)),
- new PropertyByName<Customer>("StreetAddress", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress)),
- new PropertyByName<Customer>("StreetAddress2", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress2)),
- new PropertyByName<Customer>("ZipPostalCode", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ZipPostalCode)),
- new PropertyByName<Customer>("City", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.City)),
- new PropertyByName<Customer>("CountryId", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId)),
- new PropertyByName<Customer>("StateProvinceId", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StateProvinceId)),
- new PropertyByName<Customer>("Phone", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Phone)),
- new PropertyByName<Customer>("Fax", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Fax)),
- new PropertyByName<Customer>("VatNumber", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber)),
- new PropertyByName<Customer>("VatNumberStatusId", p => p.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId))
- };
- return await Task.FromResult(properties);
- }
+ var properties = new[] {
+ new PropertyByName<Customer>("CustomerId", p => p.Id),
+ new PropertyByName<Customer>("CustomerGuid", p => p.CustomerGuid),
+ new PropertyByName<Customer>("Email", p => p.Email),
+ new PropertyByName<Customer>("Username", p => p.Username),
+ new PropertyByName<Customer>("Password", p => p.Password),
+ new PropertyByName<Customer>("PasswordFormatId", p => p.PasswordFormatId),
+ new PropertyByName<Customer>("PasswordSalt", p => p.PasswordSalt),
+ new PropertyByName<Customer>("IsTaxExempt", p => p.IsTaxExempt),
+ new PropertyByName<Customer>("AffiliateId", p => p.AffiliateId),
+ new PropertyByName<Customer>("VendorId", p => p.VendorId),
+ new PropertyByName<Customer>("Active", p => p.Active),
+ //attributes
+ new PropertyByName<Customer>("FirstName",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName)),
+ new PropertyByName<Customer>("LastName",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName)),
+ new PropertyByName<Customer>("Gender",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Gender)),
+ new PropertyByName<Customer>("Company",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company)),
+ new PropertyByName<Customer>("StreetAddress",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress)),
+ new PropertyByName<Customer>("StreetAddress2",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StreetAddress2)),
+ new PropertyByName<Customer>("ZipPostalCode",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ZipPostalCode)),
+ new PropertyByName<Customer>("City", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.City)),
+ new PropertyByName<Customer>("CountryId",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CountryId)),
+ new PropertyByName<Customer>("StateProvinceId",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.StateProvinceId)),
+ new PropertyByName<Customer>("Phone",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Phone)),
+ new PropertyByName<Customer>("Fax", p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Fax)),
+ new PropertyByName<Customer>("VatNumber",
+ p => p.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber)),
+ new PropertyByName<Customer>("VatNumberStatusId",
+ p => p.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId))
+ };
+ return await Task.FromResult(properties);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs
index 3074cddbc..27ea5c60f 100644
--- a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs
+++ b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs
@@ -1,108 +1,107 @@
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain.Customers;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+public class SalesEmployeeService : ISalesEmployeeService
{
- public class SalesEmployeeService : ISalesEmployeeService
+ public SalesEmployeeService(
+ IRepository<SalesEmployee> salesEmployeeRepository,
+ IMediator mediator,
+ ICacheBase cacheBase)
{
- #region Fields
-
- private readonly IRepository<SalesEmployee> _salesEmployeeRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ _salesEmployeeRepository = salesEmployeeRepository;
+ _mediator = mediator;
+ _cacheBase = cacheBase;
+ }
- #endregion
+ /// <summary>
+ /// Gets a sales employee
+ /// </summary>
+ /// <param name="salesEmployeeId">The sales employee identifier</param>
+ /// <returns>SalesEmployee</returns>
+ public virtual Task<SalesEmployee> GetSalesEmployeeById(string salesEmployeeId)
+ {
+ var key = string.Format(CacheKey.SALESEMPLOYEE_BY_ID_KEY, salesEmployeeId);
+ return _cacheBase.GetAsync(key, () => _salesEmployeeRepository.GetByIdAsync(salesEmployeeId));
+ }
- public SalesEmployeeService(
- IRepository<SalesEmployee> salesEmployeeRepository,
- IMediator mediator,
- ICacheBase cacheBase)
- {
- _salesEmployeeRepository = salesEmployeeRepository;
- _mediator = mediator;
- _cacheBase = cacheBase;
- }
-
- /// <summary>
- /// Gets a sales employee
- /// </summary>
- /// <param name="salesEmployeeId">The sales employee identifier</param>
- /// <returns>SalesEmployee</returns>
- public virtual Task<SalesEmployee> GetSalesEmployeeById(string salesEmployeeId)
- {
- var key = string.Format(CacheKey.SALESEMPLOYEE_BY_ID_KEY, salesEmployeeId);
- return _cacheBase.GetAsync(key, () => _salesEmployeeRepository.GetByIdAsync(salesEmployeeId));
- }
-
- /// <summary>
- /// Gets all sales employees
- /// </summary>
- /// <returns>Warehouses</returns>
- public virtual async Task<IList<SalesEmployee>> GetAll()
- {
- return await _cacheBase.GetAsync(CacheKey.SALESEMPLOYEE_ALL, async () =>
- {
- var query = from se in _salesEmployeeRepository.Table
- orderby se.DisplayOrder
- select se;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Inserts a sales employee
- /// </summary>
- /// <param name="salesEmployee">Sales Employee</param>
- public virtual async Task InsertSalesEmployee(SalesEmployee salesEmployee)
+ /// <summary>
+ /// Gets all sales employees
+ /// </summary>
+ /// <returns>Warehouses</returns>
+ public virtual async Task<IList<SalesEmployee>> GetAll()
+ {
+ return await _cacheBase.GetAsync(CacheKey.SALESEMPLOYEE_ALL, async () =>
{
- ArgumentNullException.ThrowIfNull(salesEmployee);
+ var query = from se in _salesEmployeeRepository.Table
+ orderby se.DisplayOrder
+ select se;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- await _salesEmployeeRepository.InsertAsync(salesEmployee);
+ /// <summary>
+ /// Inserts a sales employee
+ /// </summary>
+ /// <param name="salesEmployee">Sales Employee</param>
+ public virtual async Task InsertSalesEmployee(SalesEmployee salesEmployee)
+ {
+ ArgumentNullException.ThrowIfNull(salesEmployee);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
+ await _salesEmployeeRepository.InsertAsync(salesEmployee);
- //event notification
- await _mediator.EntityInserted(salesEmployee);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
- /// <summary>
- /// Updates the sales employee
- /// </summary>
- /// <param name="salesEmployee">Sales Employee</param>
- public virtual async Task UpdateSalesEmployee(SalesEmployee salesEmployee)
- {
- ArgumentNullException.ThrowIfNull(salesEmployee);
+ //event notification
+ await _mediator.EntityInserted(salesEmployee);
+ }
- await _salesEmployeeRepository.UpdateAsync(salesEmployee);
+ /// <summary>
+ /// Updates the sales employee
+ /// </summary>
+ /// <param name="salesEmployee">Sales Employee</param>
+ public virtual async Task UpdateSalesEmployee(SalesEmployee salesEmployee)
+ {
+ ArgumentNullException.ThrowIfNull(salesEmployee);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
+ await _salesEmployeeRepository.UpdateAsync(salesEmployee);
- //event notification
- await _mediator.EntityUpdated(salesEmployee);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
- /// <summary>
- /// Deletes a sales employee
- /// </summary>
- /// <param name="salesEmployee">The sales employee</param>
- public virtual async Task DeleteSalesEmployee(SalesEmployee salesEmployee)
- {
- ArgumentNullException.ThrowIfNull(salesEmployee);
+ //event notification
+ await _mediator.EntityUpdated(salesEmployee);
+ }
+
+ /// <summary>
+ /// Deletes a sales employee
+ /// </summary>
+ /// <param name="salesEmployee">The sales employee</param>
+ public virtual async Task DeleteSalesEmployee(SalesEmployee salesEmployee)
+ {
+ ArgumentNullException.ThrowIfNull(salesEmployee);
- await _salesEmployeeRepository.DeleteAsync(salesEmployee);
+ await _salesEmployeeRepository.DeleteAsync(salesEmployee);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.SALESEMPLOYEE_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(salesEmployee);
- }
+ //event notification
+ await _mediator.EntityDeleted(salesEmployee);
}
-}
+
+ #region Fields
+
+ private readonly IRepository<SalesEmployee> _salesEmployeeRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/UserApiService.cs b/src/Business/Grand.Business.Customers/Services/UserApiService.cs
index c365e2254..40535f587 100644
--- a/src/Business/Grand.Business.Customers/Services/UserApiService.cs
+++ b/src/Business/Grand.Business.Customers/Services/UserApiService.cs
@@ -1,96 +1,96 @@
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Infrastructure.Extensions;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+public class UserApiService : IUserApiService
{
- public class UserApiService : IUserApiService
+ public UserApiService(IRepository<UserApi> userRepository, IMediator mediator)
+ {
+ _userRepository = userRepository;
+ _mediator = mediator;
+ }
+
+ /// <summary>
+ /// Get user api by id
+ /// </summary>
+ /// <param name="id">id</param>
+ public virtual Task<UserApi> GetUserById(string id)
{
- #region Fields
-
- private readonly IRepository<UserApi> _userRepository;
- private readonly IMediator _mediator;
-
- #endregion
- public UserApiService(IRepository<UserApi> userRepository, IMediator mediator)
- {
- _userRepository = userRepository;
- _mediator = mediator;
- }
-
- /// <summary>
- /// Get user api by id
- /// </summary>
- /// <param name="id">id</param>
- public virtual Task<UserApi> GetUserById(string id)
- {
- return _userRepository.GetByIdAsync(id);
- }
-
- /// <summary>
- /// Get user api by email
- /// </summary>
- /// <param name="email">email</param>
- public virtual async Task<UserApi> GetUserByEmail(string email)
- {
- return await Task.FromResult(_userRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant()));
- }
-
- /// <summary>
- /// Insert user api
- /// </summary>
- /// <param name="userApi">User api</param>
- public virtual async Task InsertUserApi(UserApi userApi)
- {
- await _userRepository.InsertAsync(userApi);
-
- //event notification
- await _mediator.EntityInserted(userApi);
- }
-
- /// <summary>
- /// Update user api
- /// </summary>
- /// <param name="userApi">User api</param>
- public virtual async Task UpdateUserApi(UserApi userApi)
- {
- await _userRepository.UpdateAsync(userApi);
-
- //event notification
- await _mediator.EntityUpdated(userApi);
- }
-
- /// <summary>
- /// Delete user api
- /// </summary>
- /// <param name="userApi">User api</param>
- public virtual async Task DeleteUserApi(UserApi userApi)
- {
- await _userRepository.DeleteAsync(userApi);
-
- //event notification
- await _mediator.EntityDeleted(userApi);
-
- }
-
- /// <summary>
- /// Get users api
- /// </summary>
- /// <param name="email"></param>
- /// <param name="pageIndex"></param>
- /// <param name="pageSize"></param>
- public virtual async Task<IPagedList<UserApi>> GetUsers(string email = "", int pageIndex = 0, int pageSize = 2147483647)
- {
- var query = from p in _userRepository.Table
- select p;
-
- if (!string.IsNullOrEmpty(email))
- query = query.Where(x => x.Email.Contains(email.ToLowerInvariant()));
-
- return await PagedList<UserApi>.Create(query, pageIndex, pageSize);
- }
+ return _userRepository.GetByIdAsync(id);
}
-}
+
+ /// <summary>
+ /// Get user api by email
+ /// </summary>
+ /// <param name="email">email</param>
+ public virtual async Task<UserApi> GetUserByEmail(string email)
+ {
+ return await Task.FromResult(_userRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant()));
+ }
+
+ /// <summary>
+ /// Insert user api
+ /// </summary>
+ /// <param name="userApi">User api</param>
+ public virtual async Task InsertUserApi(UserApi userApi)
+ {
+ await _userRepository.InsertAsync(userApi);
+
+ //event notification
+ await _mediator.EntityInserted(userApi);
+ }
+
+ /// <summary>
+ /// Update user api
+ /// </summary>
+ /// <param name="userApi">User api</param>
+ public virtual async Task UpdateUserApi(UserApi userApi)
+ {
+ await _userRepository.UpdateAsync(userApi);
+
+ //event notification
+ await _mediator.EntityUpdated(userApi);
+ }
+
+ /// <summary>
+ /// Delete user api
+ /// </summary>
+ /// <param name="userApi">User api</param>
+ public virtual async Task DeleteUserApi(UserApi userApi)
+ {
+ await _userRepository.DeleteAsync(userApi);
+
+ //event notification
+ await _mediator.EntityDeleted(userApi);
+ }
+
+ /// <summary>
+ /// Get users api
+ /// </summary>
+ /// <param name="email"></param>
+ /// <param name="pageIndex"></param>
+ /// <param name="pageSize"></param>
+ public virtual async Task<IPagedList<UserApi>> GetUsers(string email = "", int pageIndex = 0,
+ int pageSize = 2147483647)
+ {
+ var query = from p in _userRepository.Table
+ select p;
+
+ if (!string.IsNullOrEmpty(email))
+ query = query.Where(x => x.Email.Contains(email.ToLowerInvariant()));
+
+ return await PagedList<UserApi>.Create(query, pageIndex, pageSize);
+ }
+
+ #region Fields
+
+ private readonly IRepository<UserApi> _userRepository;
+ private readonly IMediator _mediator;
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Services/VendorService.cs b/src/Business/Grand.Business.Customers/Services/VendorService.cs
index 93dbe20fa..8dbecf37a 100644
--- a/src/Business/Grand.Business.Customers/Services/VendorService.cs
+++ b/src/Business/Grand.Business.Customers/Services/VendorService.cs
@@ -1,343 +1,336 @@
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Infrastructure.Extensions;
-using Grand.Domain;
using Grand.Data;
+using Grand.Domain;
using Grand.Domain.Vendors;
+using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Customers.Services
+namespace Grand.Business.Customers.Services;
+
+/// <summary>
+/// Vendor service
+/// </summary>
+public class VendorService : IVendorService
{
+ #region Ctor
+
/// <summary>
- /// Vendor service
+ /// Ctor
/// </summary>
- public class VendorService : IVendorService
+ /// <param name="vendorRepository">Vendor repository</param>
+ /// <param name="vendorReviewRepository">Vendor review repository</param>
+ /// <param name="mediator">Mediator</param>
+ public VendorService(IRepository<Vendor> vendorRepository, IRepository<VendorReview> vendorReviewRepository,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<Vendor> _vendorRepository;
- private readonly IRepository<VendorReview> _vendorReviewRepository;
- private readonly IMediator _mediator;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="vendorRepository">Vendor repository</param>
- /// <param name="vendorReviewRepository">Vendor review repository</param>
- /// <param name="mediator">Mediator</param>
- public VendorService(IRepository<Vendor> vendorRepository, IRepository<VendorReview> vendorReviewRepository,
- IMediator mediator)
- {
- _vendorRepository = vendorRepository;
- _vendorReviewRepository = vendorReviewRepository;
- _mediator = mediator;
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets a vendor by vendor identifier
- /// </summary>
- /// <param name="vendorId">Vendor identifier</param>
- /// <returns>Vendor</returns>
- public virtual Task<Vendor> GetVendorById(string vendorId)
- {
- return _vendorRepository.GetByIdAsync(vendorId);
- }
-
- /// <summary>
- /// Gets all vendors
- /// </summary>
- /// <param name="name">Vendor name</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <returns>Vendors</returns>
- public virtual async Task<IPagedList<Vendor>> GetAllVendors(string name = "",
- int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
- {
- var query = from p in _vendorRepository.Table
- select p;
-
- if (!string.IsNullOrWhiteSpace(name))
- query = query.Where(v => v.Name.ToLower().Contains(name.ToLower()));
- if (!showHidden)
- query = query.Where(v => v.Active);
- query = query.Where(v => !v.Deleted);
- query = query.OrderBy(v => v.DisplayOrder).ThenBy(v => v.Name);
- return await PagedList<Vendor>.Create(query, pageIndex, pageSize);
- }
-
- /// <summary>
- /// Inserts a vendor
- /// </summary>
- /// <param name="vendor">Vendor</param>
- public virtual async Task InsertVendor(Vendor vendor)
- {
- ArgumentNullException.ThrowIfNull(vendor);
-
- await _vendorRepository.InsertAsync(vendor);
-
- //event notification
- await _mediator.EntityInserted(vendor);
- }
-
- /// <summary>
- /// Updates the vendor
- /// </summary>
- /// <param name="vendor">Vendor</param>
- public virtual async Task UpdateVendor(Vendor vendor)
- {
- ArgumentNullException.ThrowIfNull(vendor);
-
- await _vendorRepository.UpdateAsync(vendor);
-
- //event notification
- await _mediator.EntityUpdated(vendor);
- }
-
- /// <summary>
- /// Delete a vendor
- /// </summary>
- /// <param name="vendor">Vendor</param>
- public virtual async Task DeleteVendor(Vendor vendor)
- {
- ArgumentNullException.ThrowIfNull(vendor);
-
- vendor.Deleted = true;
- await UpdateVendor(vendor);
- }
-
-
- /// <summary>
- /// Gets a vendor note note
- /// </summary>
- /// <param name="vendorId">Vendor ident</param>
- /// <param name="vendorNoteId">The vendor note identifier</param>
- /// <returns>Vendor note</returns>
- public virtual async Task<VendorNote> GetVendorNoteById(string vendorId, string vendorNoteId)
- {
- if (string.IsNullOrEmpty(vendorNoteId))
- return null;
- var vendor = await _vendorRepository.GetByIdAsync(vendorId);
- return vendor?.VendorNotes.FirstOrDefault(x => x.Id == vendorNoteId);
- }
- /// <summary>
- /// Insert vendor note
- /// </summary>
- /// <param name="vendorNote"></param>
- /// <param name="vendorId"></param>
- /// <returns></returns>
- public virtual async Task InsertVendorNote(VendorNote vendorNote, string vendorId)
- {
- ArgumentNullException.ThrowIfNull(vendorNote);
-
- await _vendorRepository.AddToSet(vendorId, x => x.VendorNotes, vendorNote);
-
- //event notification
- await _mediator.EntityInserted(vendorNote);
- }
-
- /// <summary>
- /// Deletes a vendor note
- /// </summary>
- /// <param name="vendorNote">The vendor note</param>
- /// <param name="vendorId">Vendor ident</param>
- public virtual async Task DeleteVendorNote(VendorNote vendorNote, string vendorId)
- {
- ArgumentNullException.ThrowIfNull(vendorNote);
-
- await _vendorRepository.PullFilter(vendorId, x => x.VendorNotes, x => x.Id, vendorNote.Id);
-
- //event notification
- await _mediator.EntityDeleted(vendorNote);
- }
-
- /// <summary>
- /// Gets a vendor mapping
- /// </summary>
- /// <param name="discountId">Discount id mapping identifier</param>
- /// <returns>vendor mapping</returns>
- public virtual async Task<IList<Vendor>> GetAllVendorsByDiscount(string discountId)
- {
- var query = from c in _vendorRepository.Table
- where c.AppliedDiscounts.Any(x => x == discountId)
- select c;
- return await Task.FromResult(query.ToList());
- }
-
- #region Vendor reviews
-
- /// <summary>
- /// Gets all vendor reviews
- /// </summary>
- /// <param name="customerId">Customer identifier; "" to load all records</param>
- /// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
- /// <param name="fromUtc">Item creation from; null to load all records</param>
- /// <param name="toUtc">Item item creation to; null to load all records</param>
- /// <param name="message">Search title or review text; null to load all records</param>
- /// <param name="vendorId"></param>
- /// <param name="pageIndex"></param>
- /// <param name="pageSize"></param>
- /// <returns>Reviews</returns>
- public virtual async Task<IPagedList<VendorReview>> GetAllVendorReviews(string customerId, bool? approved,
- DateTime? fromUtc = null, DateTime? toUtc = null,
- string message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _vendorReviewRepository.Table
- select p;
-
- if (approved.HasValue)
- query = query.Where(c => c.IsApproved == approved.Value);
- if (!string.IsNullOrEmpty(customerId))
- query = query.Where(c => c.CustomerId == customerId);
- if (fromUtc.HasValue)
- query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);
- if (toUtc.HasValue)
- query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);
- if (!string.IsNullOrEmpty(message))
- query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));
- if (!string.IsNullOrEmpty(vendorId))
- query = query.Where(c => c.VendorId == vendorId);
- query = query.OrderByDescending(c => c.CreatedOnUtc);
- return await PagedList<VendorReview>.Create(query, pageIndex, pageSize);
- }
-
-
- /// <summary>
- /// Update vendor review totals
- /// </summary>
- /// <param name="vendor">Vendor</param>
- public virtual async Task UpdateVendorReviewTotals(Vendor vendor)
- {
- ArgumentNullException.ThrowIfNull(vendor);
-
- var approvedRatingSum = 0;
- var notApprovedRatingSum = 0;
- var approvedTotalReviews = 0;
- var notApprovedTotalReviews = 0;
- var reviews = _vendorReviewRepository.Table.Where(x => x.VendorId == vendor.Id);
- foreach (var pr in reviews)
- {
- if (pr.IsApproved)
- {
- approvedRatingSum += pr.Rating;
- approvedTotalReviews++;
- }
- else
- {
- notApprovedRatingSum += pr.Rating;
- notApprovedTotalReviews++;
- }
- }
+ _vendorRepository = vendorRepository;
+ _vendorReviewRepository = vendorReviewRepository;
+ _mediator = mediator;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IRepository<Vendor> _vendorRepository;
+ private readonly IRepository<VendorReview> _vendorReviewRepository;
+ private readonly IMediator _mediator;
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets a vendor by vendor identifier
+ /// </summary>
+ /// <param name="vendorId">Vendor identifier</param>
+ /// <returns>Vendor</returns>
+ public virtual Task<Vendor> GetVendorById(string vendorId)
+ {
+ return _vendorRepository.GetByIdAsync(vendorId);
+ }
+
+ /// <summary>
+ /// Gets all vendors
+ /// </summary>
+ /// <param name="name">Vendor name</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <returns>Vendors</returns>
+ public virtual async Task<IPagedList<Vendor>> GetAllVendors(string name = "",
+ int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
+ {
+ var query = from p in _vendorRepository.Table
+ select p;
+
+ if (!string.IsNullOrWhiteSpace(name))
+ query = query.Where(v => v.Name.ToLower().Contains(name.ToLower()));
+ if (!showHidden)
+ query = query.Where(v => v.Active);
+ query = query.Where(v => !v.Deleted);
+ query = query.OrderBy(v => v.DisplayOrder).ThenBy(v => v.Name);
+ return await PagedList<Vendor>.Create(query, pageIndex, pageSize);
+ }
+
+ /// <summary>
+ /// Inserts a vendor
+ /// </summary>
+ /// <param name="vendor">Vendor</param>
+ public virtual async Task InsertVendor(Vendor vendor)
+ {
+ ArgumentNullException.ThrowIfNull(vendor);
+
+ await _vendorRepository.InsertAsync(vendor);
+
+ //event notification
+ await _mediator.EntityInserted(vendor);
+ }
+
+ /// <summary>
+ /// Updates the vendor
+ /// </summary>
+ /// <param name="vendor">Vendor</param>
+ public virtual async Task UpdateVendor(Vendor vendor)
+ {
+ ArgumentNullException.ThrowIfNull(vendor);
+
+ await _vendorRepository.UpdateAsync(vendor);
+
+ //event notification
+ await _mediator.EntityUpdated(vendor);
+ }
+
+ /// <summary>
+ /// Delete a vendor
+ /// </summary>
+ /// <param name="vendor">Vendor</param>
+ public virtual async Task DeleteVendor(Vendor vendor)
+ {
+ ArgumentNullException.ThrowIfNull(vendor);
+
+ vendor.Deleted = true;
+ await UpdateVendor(vendor);
+ }
+
+
+ /// <summary>
+ /// Gets a vendor note note
+ /// </summary>
+ /// <param name="vendorId">Vendor ident</param>
+ /// <param name="vendorNoteId">The vendor note identifier</param>
+ /// <returns>Vendor note</returns>
+ public virtual async Task<VendorNote> GetVendorNoteById(string vendorId, string vendorNoteId)
+ {
+ if (string.IsNullOrEmpty(vendorNoteId))
+ return null;
+ var vendor = await _vendorRepository.GetByIdAsync(vendorId);
+ return vendor?.VendorNotes.FirstOrDefault(x => x.Id == vendorNoteId);
+ }
+
+ /// <summary>
+ /// Insert vendor note
+ /// </summary>
+ /// <param name="vendorNote"></param>
+ /// <param name="vendorId"></param>
+ /// <returns></returns>
+ public virtual async Task InsertVendorNote(VendorNote vendorNote, string vendorId)
+ {
+ ArgumentNullException.ThrowIfNull(vendorNote);
+
+ await _vendorRepository.AddToSet(vendorId, x => x.VendorNotes, vendorNote);
+
+ //event notification
+ await _mediator.EntityInserted(vendorNote);
+ }
- vendor.ApprovedRatingSum = approvedRatingSum;
- vendor.NotApprovedRatingSum = notApprovedRatingSum;
- vendor.ApprovedTotalReviews = approvedTotalReviews;
- vendor.NotApprovedTotalReviews = notApprovedTotalReviews;
-
- var update = UpdateBuilder<Vendor>.Create()
- .Set(x => x.ApprovedRatingSum, vendor.ApprovedRatingSum)
- .Set(x => x.NotApprovedRatingSum, vendor.NotApprovedRatingSum)
- .Set(x => x.ApprovedTotalReviews, vendor.ApprovedTotalReviews)
- .Set(x => x.NotApprovedTotalReviews, vendor.NotApprovedTotalReviews);
-
- await _vendorRepository.UpdateOneAsync(x=>x.Id == vendor.Id, update);
-
- //event notification
- await _mediator.EntityUpdated(vendor);
- }
-
- public virtual async Task UpdateVendorReview(VendorReview vendorReview)
- {
- ArgumentNullException.ThrowIfNull(vendorReview);
-
- var update = UpdateBuilder<VendorReview>.Create()
- .Set(x => x.Title, vendorReview.Title)
- .Set(x => x.ReviewText, vendorReview.ReviewText)
- .Set(x => x.IsApproved, vendorReview.IsApproved)
- .Set(x => x.HelpfulYesTotal, vendorReview.HelpfulYesTotal)
- .Set(x => x.HelpfulNoTotal, vendorReview.HelpfulNoTotal);
-
- await _vendorReviewRepository.UpdateOneAsync(x => x.Id == vendorReview.Id, update);
-
- //event notification
- await _mediator.EntityUpdated(vendorReview);
- }
-
- /// <summary>
- /// Inserts a vendor review
- /// </summary>
- /// <param name="vendorReview">Vendor review</param>
- public virtual async Task InsertVendorReview(VendorReview vendorReview)
- {
- ArgumentNullException.ThrowIfNull(vendorReview);
-
- await _vendorReviewRepository.InsertAsync(vendorReview);
-
- //event notification
- await _mediator.EntityInserted(vendorReview);
- }
-
- /// <summary>
- /// Deletes a vendor review
- /// </summary>
- /// <param name="vendorReview">Vendor review</param>
- public virtual async Task DeleteVendorReview(VendorReview vendorReview)
- {
- ArgumentNullException.ThrowIfNull(vendorReview);
-
- await _vendorReviewRepository.DeleteAsync(vendorReview);
-
- //event notification
- await _mediator.EntityDeleted(vendorReview);
- }
-
- /// <summary>
- /// Gets vendor review
- /// </summary>
- /// <param name="vendorReviewId">Vendor review identifier</param>
- /// <returns>Vendor review</returns>
- public virtual Task<VendorReview> GetVendorReviewById(string vendorReviewId)
- {
- return _vendorReviewRepository.GetByIdAsync(vendorReviewId);
- }
-
-
- /// <summary>
- /// Search vendors
- /// </summary>
- /// <param name="vendorId">Vendor identifier; "" to load all records</param>
- /// <param name="keywords">Keywords</param>
- /// <returns>Vendors</returns>
- public virtual async Task<IList<Vendor>> SearchVendors(
- string vendorId = "",
- string keywords = null)
- {
- //vendors
- var query = from p in _vendorRepository.Table
- select p;
-
- //searching by keyword
- if (!string.IsNullOrWhiteSpace(keywords))
+ /// <summary>
+ /// Deletes a vendor note
+ /// </summary>
+ /// <param name="vendorNote">The vendor note</param>
+ /// <param name="vendorId">Vendor ident</param>
+ public virtual async Task DeleteVendorNote(VendorNote vendorNote, string vendorId)
+ {
+ ArgumentNullException.ThrowIfNull(vendorNote);
+
+ await _vendorRepository.PullFilter(vendorId, x => x.VendorNotes, x => x.Id, vendorNote.Id);
+
+ //event notification
+ await _mediator.EntityDeleted(vendorNote);
+ }
+
+ /// <summary>
+ /// Gets a vendor mapping
+ /// </summary>
+ /// <param name="discountId">Discount id mapping identifier</param>
+ /// <returns>vendor mapping</returns>
+ public virtual async Task<IList<Vendor>> GetAllVendorsByDiscount(string discountId)
+ {
+ var query = from c in _vendorRepository.Table
+ where c.AppliedDiscounts.Any(x => x == discountId)
+ select c;
+ return await Task.FromResult(query.ToList());
+ }
+
+ #region Vendor reviews
+
+ /// <summary>
+ /// Gets all vendor reviews
+ /// </summary>
+ /// <param name="customerId">Customer identifier; "" to load all records</param>
+ /// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
+ /// <param name="fromUtc">Item creation from; null to load all records</param>
+ /// <param name="toUtc">Item item creation to; null to load all records</param>
+ /// <param name="message">Search title or review text; null to load all records</param>
+ /// <param name="vendorId"></param>
+ /// <param name="pageIndex"></param>
+ /// <param name="pageSize"></param>
+ /// <returns>Reviews</returns>
+ public virtual async Task<IPagedList<VendorReview>> GetAllVendorReviews(string customerId, bool? approved,
+ DateTime? fromUtc = null, DateTime? toUtc = null,
+ string message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = from p in _vendorReviewRepository.Table
+ select p;
+
+ if (approved.HasValue)
+ query = query.Where(c => c.IsApproved == approved.Value);
+ if (!string.IsNullOrEmpty(customerId))
+ query = query.Where(c => c.CustomerId == customerId);
+ if (fromUtc.HasValue)
+ query = query.Where(c => fromUtc.Value <= c.CreatedOnUtc);
+ if (toUtc.HasValue)
+ query = query.Where(c => toUtc.Value >= c.CreatedOnUtc);
+ if (!string.IsNullOrEmpty(message))
+ query = query.Where(c => c.Title.Contains(message) || c.ReviewText.Contains(message));
+ if (!string.IsNullOrEmpty(vendorId))
+ query = query.Where(c => c.VendorId == vendorId);
+ query = query.OrderByDescending(c => c.CreatedOnUtc);
+ return await PagedList<VendorReview>.Create(query, pageIndex, pageSize);
+ }
+
+
+ /// <summary>
+ /// Update vendor review totals
+ /// </summary>
+ /// <param name="vendor">Vendor</param>
+ public virtual async Task UpdateVendorReviewTotals(Vendor vendor)
+ {
+ ArgumentNullException.ThrowIfNull(vendor);
+
+ var approvedRatingSum = 0;
+ var notApprovedRatingSum = 0;
+ var approvedTotalReviews = 0;
+ var notApprovedTotalReviews = 0;
+ var reviews = _vendorReviewRepository.Table.Where(x => x.VendorId == vendor.Id);
+ foreach (var pr in reviews)
+ if (pr.IsApproved)
{
- query = query.Where(p => p.Name.ToLower().Contains(keywords.ToLower()));
+ approvedRatingSum += pr.Rating;
+ approvedTotalReviews++;
}
- //vendor filtering
- if (!string.IsNullOrEmpty(vendorId))
+ else
{
- query = query.Where(x => x.Id == vendorId);
+ notApprovedRatingSum += pr.Rating;
+ notApprovedTotalReviews++;
}
- return await Task.FromResult(query.ToList());
- }
- #endregion
+ vendor.ApprovedRatingSum = approvedRatingSum;
+ vendor.NotApprovedRatingSum = notApprovedRatingSum;
+ vendor.ApprovedTotalReviews = approvedTotalReviews;
+ vendor.NotApprovedTotalReviews = notApprovedTotalReviews;
- #endregion
+ var update = UpdateBuilder<Vendor>.Create()
+ .Set(x => x.ApprovedRatingSum, vendor.ApprovedRatingSum)
+ .Set(x => x.NotApprovedRatingSum, vendor.NotApprovedRatingSum)
+ .Set(x => x.ApprovedTotalReviews, vendor.ApprovedTotalReviews)
+ .Set(x => x.NotApprovedTotalReviews, vendor.NotApprovedTotalReviews);
+
+ await _vendorRepository.UpdateOneAsync(x => x.Id == vendor.Id, update);
+
+ //event notification
+ await _mediator.EntityUpdated(vendor);
}
+
+ public virtual async Task UpdateVendorReview(VendorReview vendorReview)
+ {
+ ArgumentNullException.ThrowIfNull(vendorReview);
+
+ var update = UpdateBuilder<VendorReview>.Create()
+ .Set(x => x.Title, vendorReview.Title)
+ .Set(x => x.ReviewText, vendorReview.ReviewText)
+ .Set(x => x.IsApproved, vendorReview.IsApproved)
+ .Set(x => x.HelpfulYesTotal, vendorReview.HelpfulYesTotal)
+ .Set(x => x.HelpfulNoTotal, vendorReview.HelpfulNoTotal);
+
+ await _vendorReviewRepository.UpdateOneAsync(x => x.Id == vendorReview.Id, update);
+
+ //event notification
+ await _mediator.EntityUpdated(vendorReview);
+ }
+
+ /// <summary>
+ /// Inserts a vendor review
+ /// </summary>
+ /// <param name="vendorReview">Vendor review</param>
+ public virtual async Task InsertVendorReview(VendorReview vendorReview)
+ {
+ ArgumentNullException.ThrowIfNull(vendorReview);
+
+ await _vendorReviewRepository.InsertAsync(vendorReview);
+
+ //event notification
+ await _mediator.EntityInserted(vendorReview);
+ }
+
+ /// <summary>
+ /// Deletes a vendor review
+ /// </summary>
+ /// <param name="vendorReview">Vendor review</param>
+ public virtual async Task DeleteVendorReview(VendorReview vendorReview)
+ {
+ ArgumentNullException.ThrowIfNull(vendorReview);
+
+ await _vendorReviewRepository.DeleteAsync(vendorReview);
+
+ //event notification
+ await _mediator.EntityDeleted(vendorReview);
+ }
+
+ /// <summary>
+ /// Gets vendor review
+ /// </summary>
+ /// <param name="vendorReviewId">Vendor review identifier</param>
+ /// <returns>Vendor review</returns>
+ public virtual Task<VendorReview> GetVendorReviewById(string vendorReviewId)
+ {
+ return _vendorReviewRepository.GetByIdAsync(vendorReviewId);
+ }
+
+
+ /// <summary>
+ /// Search vendors
+ /// </summary>
+ /// <param name="vendorId">Vendor identifier; "" to load all records</param>
+ /// <param name="keywords">Keywords</param>
+ /// <returns>Vendors</returns>
+ public virtual async Task<IList<Vendor>> SearchVendors(
+ string vendorId = "",
+ string keywords = null)
+ {
+ //vendors
+ var query = from p in _vendorRepository.Table
+ select p;
+
+ //searching by keyword
+ if (!string.IsNullOrWhiteSpace(keywords))
+ query = query.Where(p => p.Name.ToLower().Contains(keywords.ToLower()));
+ //vendor filtering
+ if (!string.IsNullOrEmpty(vendorId)) query = query.Where(x => x.Id == vendorId);
+ return await Task.FromResult(query.ToList());
+ }
+
+ #endregion
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Customers/Startup/StartupApplication.cs b/src/Business/Grand.Business.Customers/Startup/StartupApplication.cs
index a044c40e1..c2835e49c 100644
--- a/src/Business/Grand.Business.Customers/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Customers/Startup/StartupApplication.cs
@@ -10,36 +10,35 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-namespace Grand.Business.Customers.Startup
+namespace Grand.Business.Customers.Startup;
+
+public class StartupApplication : IStartupApplication
{
- public class StartupApplication : IStartupApplication
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
- {
- RegisterCustomerService(services);
+ RegisterCustomerService(services);
+ }
- }
- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
- {
+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
+ {
+ }
- }
- public int Priority => 100;
- public bool BeforeConfigure => false;
+ public int Priority => 100;
+ public bool BeforeConfigure => false;
- private void RegisterCustomerService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IVendorService, VendorService>();
- serviceCollection.AddScoped<ICustomerAttributeParser, CustomerAttributeParser>();
- serviceCollection.AddScoped<ICustomerAttributeService, CustomerAttributeService>();
- serviceCollection.AddScoped<ICustomerService, CustomerService>();
- serviceCollection.AddScoped<ICustomerNoteService, CustomerNoteService>();
- serviceCollection.AddScoped<ICustomerHistoryPasswordService, CustomerHistoryPasswordService>();
- serviceCollection.AddScoped<ICustomerManagerService, CustomerManagerService>();
- serviceCollection.AddScoped<ISalesEmployeeService, SalesEmployeeService>();
- serviceCollection.AddScoped<IUserApiService, UserApiService>();
- serviceCollection.AddScoped<IAffiliateService, AffiliateService>();
- serviceCollection.AddScoped<ISchemaProperty<Customer>, CustomerSchemaProperty>();
- serviceCollection.AddScoped<ISchemaProperty<Address>, AddressSchemaProperty>();
- }
+ private void RegisterCustomerService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IVendorService, VendorService>();
+ serviceCollection.AddScoped<ICustomerAttributeParser, CustomerAttributeParser>();
+ serviceCollection.AddScoped<ICustomerAttributeService, CustomerAttributeService>();
+ serviceCollection.AddScoped<ICustomerService, CustomerService>();
+ serviceCollection.AddScoped<ICustomerNoteService, CustomerNoteService>();
+ serviceCollection.AddScoped<ICustomerHistoryPasswordService, CustomerHistoryPasswordService>();
+ serviceCollection.AddScoped<ICustomerManagerService, CustomerManagerService>();
+ serviceCollection.AddScoped<ISalesEmployeeService, SalesEmployeeService>();
+ serviceCollection.AddScoped<IUserApiService, UserApiService>();
+ serviceCollection.AddScoped<IAffiliateService, AffiliateService>();
+ serviceCollection.AddScoped<ISchemaProperty<Customer>, CustomerSchemaProperty>();
+ serviceCollection.AddScoped<ISchemaProperty<Address>, AddressSchemaProperty>();
}
-}
+}
\ No newline at end of file