fix files

subProduct
Amir Hossein Khademi 2024-08-09 21:55:16 +03:30
parent 19f1f29548
commit ae9b65adbd
109 changed files with 716 additions and 1354 deletions

View File

@ -1 +1 @@
1.0.9.11
1.2.10.12

View File

@ -1,7 +1,5 @@
using Marten.Events;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
using Netina.Domain.Entities.Blogs;
using Netina.Domain.Entities.Products;
using System.Web;
namespace Netina.Api.Controllers;

View File

@ -2,17 +2,11 @@
using Netina.Domain.Entities.Blogs;
namespace Netina.Api.Controllers;
public class SeedController : ICarterModule
public class SeedController(IWebHostEnvironment environment) : ICarterModule
{
private readonly IWebHostEnvironment _environment;
public SeedController(IWebHostEnvironment environment)
{
_environment = environment;
}
public void AddRoutes(IEndpointRouteBuilder app)
{
if (_environment.IsDevelopment())
if (environment.IsDevelopment())
{
var group = app.NewVersionedApi("Seed")
.MapGroup("api/seed");

View File

@ -6,8 +6,8 @@
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<AssemblyVersion>1.0.9.11</AssemblyVersion>
<FileVersion>1.0.9.11</FileVersion>
<AssemblyVersion>1.2.10.12</AssemblyVersion>
<FileVersion>1.2.10.12</FileVersion>
</PropertyGroup>
<ItemGroup>
@ -15,7 +15,7 @@
<PackageReference Include="Asp.Versioning.Http" Version="8.1.0" />
<PackageReference Include="Ben.BlockingDetector" Version="0.0.4" />
<PackageReference Include="Carter" Version="8.2.1" />
<PackageReference Include="Carter" Version="8.1.0" />
<PackageReference Include="FluentValidation" Version="11.9.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.0" />
<PackageReference Include="MediatR.Extensions.Autofac.DependencyInjection" Version="12.0.0" />

View File

@ -3,24 +3,17 @@ using Netina.Repository.Abstracts;
namespace Netina.Api.Services;
public class CurrentUserService : ICurrentUserService
public class CurrentUserService(IHttpContextAccessor httpContextAccessor) : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string? UserId => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public string? UserName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
public string? DeviceId => GetDeviceId(_httpContextAccessor.HttpContext);
public string? UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public string? UserName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
public string? DeviceId => GetDeviceId(httpContextAccessor.HttpContext);
public bool IsAuthorized => GetAuthorized();
public JwtSecurityToken? JwtToken => GetJwtToken();
private JwtSecurityToken? GetJwtToken()
{
var stream = _httpContextAccessor.HttpContext?.Request.Headers.Authorization.FirstOrDefault();
var stream = httpContextAccessor.HttpContext?.Request.Headers.Authorization.FirstOrDefault();
if (stream == null)
return null;
var handler = new JwtSecurityTokenHandler();
@ -28,7 +21,7 @@ public class CurrentUserService : ICurrentUserService
return jsonToken as JwtSecurityToken;
}
public List<string>? Permissions => _httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c => c.Value)?.ToList();
public List<string>? Permissions => httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c => c.Value)?.ToList();
private string? GetDeviceId(HttpContext? context)
{
@ -52,9 +45,9 @@ public class CurrentUserService : ICurrentUserService
private bool GetAuthorized()
{
if (_httpContextAccessor.HttpContext?.User.Identity == null)
if (httpContextAccessor.HttpContext?.User.Identity == null)
return false;
return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
return httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
}

View File

@ -1,7 +1,4 @@
using Netina.Common.Models.Api;
using Netina.Core.Models.Api;
namespace Netina.Api.WebFramework.Bases;
namespace Netina.Api.WebFramework.Bases;
public class ApiResultFactory
{

View File

@ -1,23 +1,13 @@
using Netina.Common.Models.Entity;
using Netina.Common.Models.Exception;
using Netina.Common.Models.Mapper;
using Netina.Repository.Repositories.Base.Contracts;
namespace Netina.Api.WebFramework.Bases;
namespace Netina.Api.WebFramework.Bases;
public class CrudEndpoint<TEntity,TGetAllQuery,TGetOneQuery,TCreateCommand,TUpdateCommand,TDeleteCommand> where TEntity : ApiEntity, new()
public class CrudEndpoint<TEntity, TGetAllQuery, TGetOneQuery, TCreateCommand, TUpdateCommand, TDeleteCommand>(
string endpointName)
where TEntity : ApiEntity, new()
{
private readonly string _endpointName;
public CrudEndpoint(string endpointName)
{
_endpointName = endpointName;
}
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi(_endpointName).MapGroup($"api/{_endpointName}");
var group = app.NewVersionedApi(endpointName).MapGroup($"api/{endpointName}");
group.MapGet("", GetAllAsync)
.WithDisplayName("GetAll")
@ -83,16 +73,11 @@ public class BaseController : ControllerBase
}
[Authorize(AuthenticationSchemes = "Bearer")]
public class CrudController<TDto, TEntity> : BaseController
public class CrudController<TDto, TEntity>(IRepositoryWrapper repositoryWrapper) : BaseController
where TDto : BaseDto<TDto, TEntity>, new()
where TEntity : ApiEntity, new()
{
protected readonly IRepositoryWrapper _repositoryWrapper;
public CrudController(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper;
// GET:Get All Entity
[HttpGet]
@ -168,15 +153,10 @@ public class CrudController<TDto, TEntity> : BaseController
}
[Authorize(AuthenticationSchemes = "Bearer")]
public class CrudController<TEntity> : BaseController
public class CrudController<TEntity>(IRepositoryWrapper repositoryWrapper) : BaseController
where TEntity : ApiEntity, new()
{
protected readonly IRepositoryWrapper _repositoryWrapper;
public CrudController(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
protected readonly IRepositoryWrapper _repositoryWrapper = repositoryWrapper;
// GET:Get All Entity
[HttpGet]

View File

@ -1,6 +1,4 @@
using Netina.Infrastructure.Models;
namespace Netina.Api.WebFramework.Configurations;
namespace Netina.Api.WebFramework.Configurations;
public static class LoggerConfig
{

View File

@ -10,22 +10,11 @@ public static class ExceptionHandlerMiddlewareExtensions
}
}
public class ExceptionHandlerMiddleware
{
private readonly IWebHostEnvironment _env;
private readonly ILogger<ExceptionHandlerMiddleware> _logger;
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(
public class ExceptionHandlerMiddleware(
RequestDelegate next,
IWebHostEnvironment env,
ILogger<ExceptionHandlerMiddleware> logger)
{
_next = next;
_env = env;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
string message = null;
@ -34,17 +23,17 @@ public class ExceptionHandlerMiddleware
try
{
await _next(context);
await next(context);
}
catch (BaseApiException exception)
{
_logger.LogError(exception, exception.Message);
logger.LogError(exception, exception.Message);
httpStatusCode = exception.ApiStatusCode == ApiResultStatusCode.NotFound ? HttpStatusCode.NotFound :
exception.ApiStatusCode == ApiResultStatusCode.BadRequest ?
HttpStatusCode.BadRequest : exception.HttpStatusCode;
apiStatusCode = exception.ApiStatusCode;
if (_env.IsDevelopment())
if (env.IsDevelopment())
{
var dic = new Dictionary<string, string>
{
@ -82,19 +71,19 @@ public class ExceptionHandlerMiddleware
}
catch (SecurityTokenExpiredException exception)
{
_logger.LogError(exception, exception.Message);
logger.LogError(exception, exception.Message);
SetUnAuthorizeResponse(exception);
await WriteToResponseAsync();
}
catch (UnauthorizedAccessException exception)
{
_logger.LogError(exception, exception.Message);
logger.LogError(exception, exception.Message);
SetUnAuthorizeResponse(exception);
await WriteToResponseAsync();
}
catch (ApiException apiException)
{
_logger.LogError(apiException, apiException.Message);
logger.LogError(apiException, apiException.Message);
httpStatusCode = HttpStatusCode.InternalServerError;
apiStatusCode = ApiResultStatusCode.RefitError;
@ -105,9 +94,9 @@ public class ExceptionHandlerMiddleware
}
catch (Exception exception)
{
_logger.LogError(exception, exception.Message);
logger.LogError(exception, exception.Message);
if (_env.IsDevelopment())
if (env.IsDevelopment())
{
if (exception?.InnerException?.Message != null)
{
@ -185,7 +174,7 @@ public class ExceptionHandlerMiddleware
httpStatusCode = HttpStatusCode.Unauthorized;
apiStatusCode = ApiResultStatusCode.UnAuthorized;
if (_env.IsDevelopment())
if (env.IsDevelopment())
{
var dic = new Dictionary<string, string>
{

View File

@ -8,28 +8,19 @@ public static class PerformanceMiddlewareExtensions
}
}
public class PerformanceMiddleware
{
private readonly ILogger<ExceptionHandlerMiddleware> _logger;
private readonly RequestDelegate _next;
private readonly Stopwatch _timer;
public PerformanceMiddleware(
public class PerformanceMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlerMiddleware> logger)
{
_next = next;
_logger = logger;
_timer = new Stopwatch();
}
private readonly Stopwatch _timer = new();
public async System.Threading.Tasks.Task Invoke(HttpContext context)
{
_timer.Start();
await _next(context);
await next(context);
_timer.Stop();
var elapsedMilliseconds = _timer.ElapsedMilliseconds;
_logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}");
logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}");
}
}

View File

@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Netina.Common.Extensions;
using Pluralize.NET;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
@ -139,17 +138,12 @@ public class SetVersionInPaths : IDocumentFilter
}
}
public class UnauthorizedResponsesOperationFilter : IOperationFilter
{
private readonly bool includeUnauthorizedAndForbiddenResponses;
private readonly string schemeName;
public UnauthorizedResponsesOperationFilter(bool includeUnauthorizedAndForbiddenResponses,
public class UnauthorizedResponsesOperationFilter(
bool includeUnauthorizedAndForbiddenResponses,
string schemeName = "Bearer")
: IOperationFilter
{
this.includeUnauthorizedAndForbiddenResponses = includeUnauthorizedAndForbiddenResponses;
this.schemeName = schemeName;
}
private readonly string schemeName = schemeName;
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{

View File

@ -1,5 +1,4 @@
using System.Web;
using System.Xml.Linq;
namespace Netina.Common.Extensions
{

View File

@ -1,25 +1,16 @@
namespace Netina.Common.Models.Entity
{
[AttributeUsage(AttributeTargets.Class)]
public class PageClassDisplay : Attribute
public class PageClassDisplay(string name, string description) : Attribute
{
private readonly string _description;
private readonly string _name;
public PageClassDisplay(string name, string description)
{
_name = name;
_description = description;
}
public string GetName()
{
return _name;
return name;
}
public string GetDescription()
{
return _description;
return description;
}
}
}

View File

@ -1,18 +1,7 @@
namespace Netina.Core.BaseServices;
public class AccountService : IAccountService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _userSignInManager;
private readonly IJwtService _jwtService;
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ISmsService _smsService;
private readonly IUserService _managerUserService;
public AccountService(
public class AccountService(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> userSignInManager,
IJwtService jwtService,
@ -20,34 +9,24 @@ public class AccountService : IAccountService
IRepositoryWrapper repositoryWrapper,
ISmsService smsService,
IUserService managerUserService)
: IAccountService
{
_userManager = userManager;
_userSignInManager = userSignInManager;
_jwtService = jwtService;
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_smsService = smsService;
_managerUserService = managerUserService;
}
public async Task<bool> ForgetPasswordAsync(string phoneNumber)
{
var user = await _userManager.FindByNameAsync(phoneNumber);
var user = await userManager.FindByNameAsync(phoneNumber);
if (user != null)
{
var rand = new Random(DateTime.Now.Millisecond);
var newPass = rand.Next(1000000, 9000000).ToString();
if (!user.PhoneNumberConfirmed)
throw new AppException("شماره تلفن شما تایید نشده است و قابلیت استفاده از فراموشی رمز عبور را ندارید");
var rp = await _userManager.RemovePasswordAsync(user);
var rp = await userManager.RemovePasswordAsync(user);
if (!rp.Succeeded)
throw new AppException(string.Join('-', rp.Errors.Select(e => e.Description)));
var ap = await _userManager.AddPasswordAsync(user, newPass);
var ap = await userManager.AddPasswordAsync(user, newPass);
if (!ap.Succeeded)
throw new AppException(string.Join('-', ap.Errors.Select(e => e.Description)));
await _smsService.SendForgerPasswordAsync(user.PhoneNumber, newPass);
await smsService.SendForgerPasswordAsync(user.PhoneNumber, newPass);
return true;
}
@ -56,7 +35,7 @@ public class AccountService : IAccountService
public async Task<bool> CheckMemberShipAsync(string phoneNumber)
{
var user = await _userManager.FindByNameAsync(phoneNumber);
var user = await userManager.FindByNameAsync(phoneNumber);
if (user == null)
return false;
return true;
@ -67,23 +46,23 @@ public class AccountService : IAccountService
var newPhoneNumber = StringExtensions.CheckPhoneNumber(phoneNumber);
if (!PhoneNumberExtensions.CheckPhoneNumber(newPhoneNumber))
throw new AppException("شماره تلفن ارسالی اشتباه است");
var user = await _userManager.FindByNameAsync(newPhoneNumber);
var user = await userManager.FindByNameAsync(newPhoneNumber);
if (user == null)
user = await _managerUserService.CreateUserAsync(phoneNumber);
user = await managerUserService.CreateUserAsync(phoneNumber);
var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Phone");
await _smsService.SendVerifyCodeAsync(newPhoneNumber, token);
var token = await userManager.GenerateTwoFactorTokenAsync(user, "Phone");
await smsService.SendVerifyCodeAsync(newPhoneNumber, token);
return new VerifyCodeResponseDto { SignUpStatus = SignUpStatus.StartSignOn };
}
public async Task<AccessToken<ApplicationUserSDto>> LoginWithPasswordAsync(string userName, string password, CancellationToken cancellationToken)
{
var result = await _userSignInManager.PasswordSignInAsync(userName, password, false, false);
var result = await userSignInManager.PasswordSignInAsync(userName, password, false, false);
if (!result.Succeeded)
throw new AppException("رمز عبور یا نام کاربری اشتباه است");
var admin = await _userManager.FindByNameAsync(userName);
var admin = await userManager.FindByNameAsync(userName);
if (admin == null)
throw new AppException("نام کاربری یا رمز عبور اشتباه است");
return await CompleteLogin(admin, cancellationToken);
@ -91,11 +70,11 @@ public class AccountService : IAccountService
public async Task<AccessToken<ApplicationUserSDto>> LoginWithVerifyCodeAsync(string userName, string verifyCode, CancellationToken cancellationToken)
{
var user = await _userManager.FindByNameAsync(userName);
var user = await userManager.FindByNameAsync(userName);
if (user == null)
throw new AppException("نام کاربری یا کد ارسالی اشتباه است", ApiResultStatusCode.NotFound);
var verfiyResult = await _userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode);
var verfiyResult = await userManager.VerifyTwoFactorTokenAsync(user, "Phone", verifyCode);
if (verifyCode == "859585")
verfiyResult = true;
if (!verfiyResult)
@ -104,7 +83,7 @@ public class AccountService : IAccountService
{
user.PhoneNumberConfirmed = true;
user.SignUpStatus = SignUpStatus.PhoneNumberVerified;
var result = await _userManager.UpdateAsync(user);
var result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors));
}
@ -113,9 +92,9 @@ public class AccountService : IAccountService
public async Task<AccessToken<ApplicationUserSDto>> CompleteSignUpAsync(SignUpRequestDto requestDto, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("User Id is null");
var user = await _userManager.FindByIdAsync(_currentUserService.UserId);
var user = await userManager.FindByIdAsync(currentUserService.UserId);
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
if (user.SignUpStatus == SignUpStatus.SignUpCompleted)
@ -132,19 +111,19 @@ public class AccountService : IAccountService
user.FirstName = requestDto.FirstName;
user.LastName = requestDto.LastName;
user.SignUpStatus = SignUpStatus.SignUpCompleted;
var result = await _userManager.UpdateAsync(user);
var result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
var roleResult = await _userManager.AddToRoleAsync(user, "Customer");
var roleResult = await userManager.AddToRoleAsync(user, "Customer");
if (!roleResult.Succeeded)
throw new AppException(string.Join('|', roleResult.Errors.Select(e => e.Description)));
_repositoryWrapper.SetRepository<Customer>()
repositoryWrapper.SetRepository<Customer>()
.Add(new Customer
{
UserId = user.Id,
});
await _repositoryWrapper.SaveChangesAsync(default);
await repositoryWrapper.SaveChangesAsync(default);
return await CompleteLogin(user, cancellationToken);
}
@ -153,8 +132,8 @@ public class AccountService : IAccountService
private async Task<AccessToken<ApplicationUserSDto>> CompleteLogin(ApplicationUser user, CancellationToken cancellationToken)
{
AccessToken<ApplicationUserSDto> jwt;
var role = await _userManager.GetRolesAsync(user);
jwt = await _jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, role.ToList());
var role = await userManager.GetRolesAsync(user);
jwt = await jwtService.Generate<ApplicationUserSDto, ApplicationUser>(user, role.ToList());
jwt.User.RoleName = jwt.RoleName;
return jwt;
}

View File

@ -2,38 +2,31 @@
namespace Netina.Core.BaseServices;
public class DashboardService : IDashboardService
public class DashboardService(IRepositoryWrapper repositoryWrapper, UserManager<ApplicationUser> userManager)
: IDashboardService
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly UserManager<ApplicationUser> _userManager;
public DashboardService(IRepositoryWrapper repositoryWrapper,UserManager<ApplicationUser> userManager)
{
_repositoryWrapper = repositoryWrapper;
_userManager = userManager;
}
public async Task<HomeDashboardDto> GetHomeDashboardAsyncTask(CancellationToken cancellationToken = default)
{
var response = new HomeDashboardDto
{
BlogsCount = await _repositoryWrapper.SetRepository<Blog>()
BlogsCount = await repositoryWrapper.SetRepository<Blog>()
.TableNoTracking
.CountAsync(cancellationToken),
ProductsCount = await _repositoryWrapper.SetRepository<Product>()
ProductsCount = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.CountAsync(cancellationToken),
TodayOrdersCount = await _repositoryWrapper.SetRepository<Order>()
TodayOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.OrderAt.Date == DateTime.Today.Date)
.CountAsync(cancellationToken),
UnSubmittedOrdersCount = await _repositoryWrapper.SetRepository<Order>()
UnSubmittedOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.OrderStatus == OrderStatus.Paid || o.OrderStatus == OrderStatus.Submitted)
.CountAsync(cancellationToken),
BrandsCount = await _repositoryWrapper.SetRepository<Brand>()
BrandsCount = await repositoryWrapper.SetRepository<Brand>()
.TableNoTracking
.CountAsync(cancellationToken),
SubscribersCount = await _userManager.Users.CountAsync(cancellationToken)
SubscribersCount = await userManager.Users.CountAsync(cancellationToken)
};
return response;
@ -45,19 +38,19 @@ public class DashboardService : IDashboardService
DateTime endOfThisMonth = startOfThisMonth.AddMonths(1);
var response = new OrderDashboardDto
{
PayedOrdersCount = await _repositoryWrapper.SetRepository<Order>()
PayedOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o=>o.IsPayed && o.OrderStatus==OrderStatus.Paid)
.CountAsync(cancellationToken),
ThisMonthOrdersCount = await _repositoryWrapper.SetRepository<Order>()
ThisMonthOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(s => s.OrderAt.Date >= startOfThisMonth.Date && s.OrderAt.Date < endOfThisMonth.Date)
.CountAsync(cancellationToken),
TodayOrdersCount = await _repositoryWrapper.SetRepository<Order>()
TodayOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.OrderAt.Date == DateTime.Now.Date)
.CountAsync(cancellationToken),
UnSendOrdersCount = await _repositoryWrapper.SetRepository<Order>()
UnSendOrdersCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.IsPayed && o.OrderStatus == OrderStatus.Processing)
.CountAsync(cancellationToken)

View File

@ -1,21 +1,14 @@
namespace Netina.Core.BaseServices;
public class JwtService : IJwtService
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly SiteSettings _siteSettings;
public JwtService(
public class JwtService(
IOptionsSnapshot<SiteSettings> siteSettings,
SignInManager<ApplicationUser> userSignInManager,
RoleManager<ApplicationRole> roleManager)
: IJwtService
{
_signInManager = userSignInManager;
_roleManager = roleManager;
_siteSettings = siteSettings.Value;
}
private readonly SiteSettings _siteSettings = siteSettings.Value;
public async Task<AccessToken<TUser>> Generate<TUser>(TUser user) where TUser : ApplicationUser
{
var tokenId = StringExtensions.GetId(8);
@ -89,7 +82,7 @@ public class JwtService : IJwtService
private async Task<List<Claim>> GetClaims<TUser>(TUser baseUser, string jwtId) where TUser : ApplicationUser
{
var clFac = (await _signInManager.ClaimsFactory.CreateAsync(baseUser));
var clFac = (await userSignInManager.ClaimsFactory.CreateAsync(baseUser));
var claims = new List<Claim>();
claims.Add(new Claim("JwtID", jwtId));
claims.Add(new Claim(ClaimTypes.Name, baseUser.UserName));
@ -108,10 +101,10 @@ public class JwtService : IJwtService
foreach (var roleName in roleNames)
{
var applicationRole = await _roleManager.FindByNameAsync(roleName);
var applicationRole = await roleManager.FindByNameAsync(roleName);
if(applicationRole==null)
continue;
var roleClaims = await _roleManager.GetClaimsAsync(applicationRole);
var roleClaims = await roleManager.GetClaimsAsync(applicationRole);
claims.AddRange(roleClaims);
claims.Add(new Claim(ClaimTypes.Role, applicationRole.EnglishName));
claims.Add(new Claim("RoleId", applicationRole.Id.ToString()));

View File

@ -2,27 +2,22 @@
namespace Netina.Core.BaseServices;
public class PageService : IPageService
public class PageService(
IMartenRepositoryWrapper martenRepositoryWrapperWrapper,
ICurrentUserService currentUserService)
: IPageService
{
private readonly IMartenRepositoryWrapper _martenRepositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public PageService(IMartenRepositoryWrapper martenRepositoryWrapperWrapper, ICurrentUserService currentUserService)
{
_martenRepositoryWrapper = martenRepositoryWrapperWrapper;
_currentUserService = currentUserService;
}
public async Task<BasePageSDto> GetPageAsync(Guid? id = null, string? pageName = null, string? pageSlug = null, string? type = null, CancellationToken cancellationToken = default)
{
BasePage? page = null;
if (id != null)
page = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntityAsync(id.Value, cancellationToken);
page = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntityAsync(id.Value, cancellationToken);
else if (pageSlug != null)
page = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Slug == pageSlug, cancellationToken);
page = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Slug == pageSlug, cancellationToken);
else if (pageName != null)
page = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Title == pageName, cancellationToken);
page = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Title == pageName, cancellationToken);
else if (type != null)
page = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Type == type, cancellationToken);
page = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntityAsync(entity => entity.Type == type, cancellationToken);
if (page == null)
throw new AppException("Page not found", ApiResultStatusCode.NotFound);
@ -45,7 +40,7 @@ public class PageService : IPageService
public async Task<List<BasePageSDto>> GetPagesAsync(CancellationToken cancellationToken = default)
{
List<BasePageSDto> sDtos = new List<BasePageSDto>();
var pages = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntitiesAsync(cancellationToken);
var pages = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntitiesAsync(cancellationToken);
foreach (var page in pages)
{
var dto = new BasePageSDto
@ -79,23 +74,23 @@ public class PageService : IPageService
Type = entity.Type,
Slug = entity.Slug,
CreatedAt = DateTime.Now,
CreatedBy = _currentUserService.UserName ?? string.Empty
CreatedBy = currentUserService.UserName ?? string.Empty
};
if (!basePage.Type.IsNullOrEmpty())
{
var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType(entity.Type);
basePage.Data = JsonConvert.SerializeObject(((JsonElement)entity.Data).Deserialize(type));
}
await _martenRepositoryWrapper.SetRepository<BasePage>().AddOrUpdateEntityAsync(basePage, cancellationToken);
await martenRepositoryWrapperWrapper.SetRepository<BasePage>().AddOrUpdateEntityAsync(basePage, cancellationToken);
return true;
}
public async Task<bool> DeletePageAsync(Guid id, CancellationToken cancellationToken = default)
{
var page = await _martenRepositoryWrapper.SetRepository<BasePage>().GetEntityAsync(p => p.Id == id, cancellationToken);
var page = await martenRepositoryWrapperWrapper.SetRepository<BasePage>().GetEntityAsync(p => p.Id == id, cancellationToken);
if (page == null)
throw new AppException("Page not found", ApiResultStatusCode.NotFound);
await _martenRepositoryWrapper.SetRepository<BasePage>().RemoveEntityAsync(page, cancellationToken);
await martenRepositoryWrapperWrapper.SetRepository<BasePage>().RemoveEntityAsync(page, cancellationToken);
return true;
}
}

View File

@ -1,21 +1,14 @@

public class SettingService : ISettingService
public class SettingService(IMartenRepositoryWrapper martenRepositoryWrapper) : ISettingService
{
private readonly IMartenRepositoryWrapper _martenRepositoryWrapper;
public SettingService(IMartenRepositoryWrapper martenRepositoryWrapper)
{
_martenRepositoryWrapper = martenRepositoryWrapper;
}
public async Task<object> GetSettingAsync(string settingName, CancellationToken cancellationToken = default)
{
var type = Assembly.GetAssembly(typeof(DomainConfig))?.GetType($"Netina.Domain.MartenEntities.Settings.{settingName}");
if (type == null)
throw new AppException("Setting not found", ApiResultStatusCode.NotFound);
var baseSetting = await _martenRepositoryWrapper.SetRepository<BaseSetting>()
var baseSetting = await martenRepositoryWrapper.SetRepository<BaseSetting>()
.GetEntityAsync(s => s.Name == settingName, cancellationToken);
object? setting;
if (baseSetting == null)
@ -34,7 +27,7 @@ public class SettingService : ISettingService
if (type == null)
throw new AppException("Setting not found", ApiResultStatusCode.NotFound);
var baseSetting = await _martenRepositoryWrapper.SetRepository<BaseSetting>()
var baseSetting = await martenRepositoryWrapper.SetRepository<BaseSetting>()
.GetEntityAsync(s => s.Name == settingName, cancellationToken);
if (baseSetting == null)
@ -51,7 +44,7 @@ public class SettingService : ISettingService
baseSetting.JsonData = JsonConvert.SerializeObject(settingObj.Deserialize(type));
}
await _martenRepositoryWrapper.SetRepository<BaseSetting>()
await martenRepositoryWrapper.SetRepository<BaseSetting>()
.AddOrUpdateEntityAsync(baseSetting, cancellationToken);
}
}

View File

@ -6,23 +6,15 @@ using Netina.Domain.Entities.ProductCategories;
namespace Netina.Core.BaseServices;
public class SiteMapService : ISiteMapService
{
private readonly IUploadFileService _uploadFileService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IPageService _pageService;
private readonly SiteSettings _siteSetting;
public SiteMapService(IOptionsSnapshot<SiteSettings> snapshot,
public class SiteMapService(
IOptionsSnapshot<SiteSettings> snapshot,
IUploadFileService uploadFileService,
IRepositoryWrapper repositoryWrapper,
IPageService pageService)
: ISiteMapService
{
_uploadFileService = uploadFileService;
_repositoryWrapper = repositoryWrapper;
_pageService = pageService;
_siteSetting = snapshot.Value;
}
private readonly SiteSettings _siteSetting = snapshot.Value;
public async Task CreateSiteMapAsync()
{
XmlDocument doc = new XmlDocument();
@ -38,11 +30,11 @@ public class SiteMapService : ISiteMapService
doc.AppendChild(root);
var productCategories = await _repositoryWrapper.SetRepository<ProductCategory>()
var productCategories = await repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.ToListAsync();
var blogCategories= await _repositoryWrapper.SetRepository<BlogCategory>()
var blogCategories= await repositoryWrapper.SetRepository<BlogCategory>()
.TableNoTracking
.ToListAsync();
@ -96,7 +88,7 @@ public class SiteMapService : ISiteMapService
doc.WriteTo(writer);
writer.Flush();
byte[] byteArray = stream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = byteArray,
ContentType = "text/xml",
@ -118,7 +110,7 @@ public class SiteMapService : ISiteMapService
{
var siteMapsUId = SiteMapUIds.Pages;
var pages = await _pageService.GetPagesAsync();
var pages = await pageService.GetPagesAsync();
XmlDocument doc = new XmlDocument();
XmlDeclaration documentType = doc.CreateXmlDeclaration("1.0", "utf-8", null);
@ -170,7 +162,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",
@ -184,7 +176,7 @@ public class SiteMapService : ISiteMapService
{
var siteMapsUId = SiteMapUIds.Brands;
var brands = await _repositoryWrapper.SetRepository<Brand>()
var brands = await repositoryWrapper.SetRepository<Brand>()
.TableNoTracking
.ToListAsync();
@ -238,7 +230,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",
@ -253,7 +245,7 @@ public class SiteMapService : ISiteMapService
{
var siteMapsUId = SiteMapUIds.Categories;
var categories = await _repositoryWrapper.SetRepository<ProductCategory>()
var categories = await repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.ToListAsync();
@ -307,7 +299,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",
@ -321,7 +313,7 @@ public class SiteMapService : ISiteMapService
private async Task CreateProductsSiteMapsAsync()
{
var products = await _repositoryWrapper.SetRepository<Product>()
var products = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.Select(ProductMapper.ProjectToSDto)
.ToListAsync();
@ -400,7 +392,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",
@ -417,7 +409,7 @@ public class SiteMapService : ISiteMapService
private async Task CreateBlogsSiteMapsAsync()
{
var blogs = await _repositoryWrapper.SetRepository<Blog>()
var blogs = await repositoryWrapper.SetRepository<Blog>()
.TableNoTracking
.Select(BlogMapper.ProjectToSDto)
.ToListAsync();
@ -530,7 +522,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",
@ -548,7 +540,7 @@ public class SiteMapService : ISiteMapService
{
var siteMapsUId = SiteMapUIds.BlogCategories;
var blogCategories = await _repositoryWrapper.SetRepository<BlogCategory>()
var blogCategories = await repositoryWrapper.SetRepository<BlogCategory>()
.TableNoTracking
.ToListAsync();
@ -602,7 +594,7 @@ public class SiteMapService : ISiteMapService
zipStream.Close();
var siteMapArray = compressedStream.ToArray();
await _uploadFileService.UploadFileByteAsync(new FileUploadRequest
await uploadFileService.UploadFileByteAsync(new FileUploadRequest
{
FileBytes = siteMapArray,
ContentType = "text/plain",

View File

@ -1,21 +1,17 @@
namespace Netina.Core.CoreServices.SearchServices;
public class GetEmallsProductsQueryHandler : IRequestHandler<GetEmallsProductsQuery, EmallsResponseDto>
public class GetEmallsProductsQueryHandler(
IRepositoryWrapper repositoryWrapper,
IMediator mediator,
IOptionsSnapshot<SiteSettings> optionsSnapshot)
: IRequestHandler<GetEmallsProductsQuery, EmallsResponseDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
private readonly SiteSettings _siteSetting;
public GetEmallsProductsQueryHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator, IOptionsSnapshot<SiteSettings> optionsSnapshot)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
_siteSetting = optionsSnapshot.Value;
}
private readonly SiteSettings _siteSetting = optionsSnapshot.Value;
public async Task<EmallsResponseDto> Handle(GetEmallsProductsQuery request, CancellationToken cancellationToken)
{
var page = request.Page;
var productsSDto = await _repositoryWrapper.SetRepository<Product>()
var productsSDto = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.OrderByDescending(p => p.ModifiedAt == DateTime.MinValue ? p.CreatedAt : p.ModifiedAt)
.Select(p => new ProductSDto
@ -37,7 +33,7 @@ public class GetEmallsProductsQueryHandler : IRequestHandler<GetEmallsProductsQu
foreach (var productSDto in productsSDto)
await _mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
await mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
var products = new List<EmallsProductResponseDto>();
foreach (var product in productsSDto)
{
@ -62,7 +58,7 @@ public class GetEmallsProductsQueryHandler : IRequestHandler<GetEmallsProductsQu
var response = new EmallsResponseDto();
response.item_per_page = request.Count;
response.page_num = request.Page;
response.total_items = (await _repositoryWrapper.SetRepository<Product>().TableNoTracking.CountAsync(cancellationToken));
response.total_items = (await repositoryWrapper.SetRepository<Product>().TableNoTracking.CountAsync(cancellationToken));
response.pages_count = response.total_items / request.Count;
response.products = products;

View File

@ -2,27 +2,22 @@
namespace Netina.Core.CoreServices.SearchServices;
public class GetThumbSearchProductsQueryHandler : IRequestHandler<GetThumbSearchProductsQuery, SearchResponseDto>
public class GetThumbSearchProductsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetThumbSearchProductsQuery, SearchResponseDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetThumbSearchProductsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<SearchResponseDto> Handle(GetThumbSearchProductsQuery request, CancellationToken cancellationToken)
{
var searchQuery = request.Name;
var products = await _repositoryWrapper.SetRepository<Product>()
var products = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.OrderByDescending(p => EF.Functions.TrigramsSimilarity(p.PersianName, searchQuery))
.Take(8)
.Select(ProductMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
var categories = await _repositoryWrapper.SetRepository<ProductCategory>()
var categories = await repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.OrderByDescending(p => EF.Functions.TrigramsSimilarity(p.Name.ToLower().Trim(), searchQuery))
.Take(8)

View File

@ -1,21 +1,17 @@
namespace Netina.Core.CoreServices.SearchServices;
public class GetTorobProductsQueryHandler : IRequestHandler<GetTorobProductsQuery, List<TorobProductResponseDto>>
public class GetTorobProductsQueryHandler(
IRepositoryWrapper repositoryWrapper,
IMediator mediator,
IOptionsSnapshot<SiteSettings> optionsSnapshot)
: IRequestHandler<GetTorobProductsQuery, List<TorobProductResponseDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
private readonly SiteSettings _siteSetting;
private readonly SiteSettings _siteSetting = optionsSnapshot.Value;
public GetTorobProductsQueryHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator, IOptionsSnapshot<SiteSettings> optionsSnapshot)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
_siteSetting = optionsSnapshot.Value;
}
public async Task<List<TorobProductResponseDto>> Handle(GetTorobProductsQuery request, CancellationToken cancellationToken)
{
int page = request.Page == 0 ? 1 : request.Page;
var productsSDto = await _repositoryWrapper.SetRepository<Product>()
var productsSDto = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.OrderByDescending(p => p.ModifiedAt == DateTime.MinValue ? p.CreatedAt : p.ModifiedAt)
.Select(p => new ProductSDto
@ -37,7 +33,7 @@ public class GetTorobProductsQueryHandler : IRequestHandler<GetTorobProductsQuer
foreach (var productSDto in productsSDto)
await _mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
await mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
var products = new List<TorobProductResponseDto>();
foreach (var product in productsSDto)
{

View File

@ -2,22 +2,17 @@
namespace Netina.Core.CoreServices.WebSiteServices;
public class GetWebSiteNavBarCommandHandler : IRequestHandler<GetWebSiteNavBarCommand , List<NavMenuItem>>
public class GetWebSiteNavBarCommandHandler(
IRepositoryWrapper repositoryWrapper,
ISettingService settingService,
IOptionsSnapshot<SiteSettings> optionsSnapshot)
: IRequestHandler<GetWebSiteNavBarCommand, List<NavMenuItem>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ISettingService _settingService;
private readonly SiteSettings _siteSetting;
public GetWebSiteNavBarCommandHandler(IRepositoryWrapper repositoryWrapper , ISettingService settingService,IOptionsSnapshot<SiteSettings> optionsSnapshot)
{
_repositoryWrapper = repositoryWrapper;
_settingService = settingService;
_siteSetting = optionsSnapshot.Value;
}
private readonly SiteSettings _siteSetting = optionsSnapshot.Value;
public async Task<List<NavMenuItem>> Handle(GetWebSiteNavBarCommand request, CancellationToken cancellationToken)
{
var navBarSetting = await _settingService.GetSettingAsync(nameof(NavMenuSetting), cancellationToken) as NavMenuSetting;
var navBarSetting = await settingService.GetSettingAsync(nameof(NavMenuSetting), cancellationToken) as NavMenuSetting;
var navBarItems = new List<NavMenuItem>();
if (navBarSetting == null)
return new List<NavMenuItem>();
@ -30,7 +25,7 @@ public class GetWebSiteNavBarCommandHandler : IRequestHandler<GetWebSiteNavBarCo
if (navBarSetting.ShowBlogCategories)
{
var baseCategories = await _repositoryWrapper.SetRepository<BlogCategory>()
var baseCategories = await repositoryWrapper.SetRepository<BlogCategory>()
.TableNoTracking
.OrderByDescending(c => c.CreatedAt)
.Select(BlogCategoryMapper.ProjectToSDto)
@ -54,7 +49,7 @@ public class GetWebSiteNavBarCommandHandler : IRequestHandler<GetWebSiteNavBarCo
}
else if (navBarSetting.ShowProductCategories)
{
var baseCategories = await _repositoryWrapper.SetRepository<ProductCategory>()
var baseCategories = await repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.OrderByDescending(c => c.CreatedAt)
.Select(ProductCategoryMapper.ProjectToSDto)

View File

@ -1,21 +1,16 @@
namespace Netina.Core.EntityServices.DiscountHandlers;
public class CalculateOrderDiscountCommandHandler : IRequestHandler<CalculateOrderDiscountCommand , double>
public class CalculateOrderDiscountCommandHandler(
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService)
: IRequestHandler<CalculateOrderDiscountCommand, double>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CalculateOrderDiscountCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<double> Handle(CalculateOrderDiscountCommand request, CancellationToken cancellationToken)
{
if (request.Order == null)
throw new AppException("Order is null", ApiResultStatusCode.BadRequest);
var discount = await _repositoryWrapper.SetRepository<Discount>()
var discount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
@ -25,14 +20,14 @@ public class CalculateOrderDiscountCommandHandler : IRequestHandler<CalculateOrd
if (discount.IsForFirstPurchase)
{
if (_currentUserService.UserId != null && Guid.TryParse(_currentUserService.UserId, out Guid firstPurchaseUserId))
if (currentUserService.UserId != null && Guid.TryParse(currentUserService.UserId, out Guid firstPurchaseUserId))
{
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == firstPurchaseUserId, cancellationToken);
if (customer == null)
throw new BaseApiException(ApiResultStatusCode.NotFound, "Customer not found");
var userOrderCount = await _repositoryWrapper.SetRepository<Order>()
var userOrderCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.CountAsync(f => f.CustomerId == customer.Id && f.DiscountCode == discount.Code, cancellationToken);
if (userOrderCount > 0)
@ -51,7 +46,7 @@ public class CalculateOrderDiscountCommandHandler : IRequestHandler<CalculateOrd
}
else if (discount.Type == DiscountType.Category)
{
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
var categoryDiscount = await repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
if ( categoryDiscount!=null && !categoryDiscount.IsExpired())
@ -62,7 +57,7 @@ public class CalculateOrderDiscountCommandHandler : IRequestHandler<CalculateOrd
}
else if (discount.Type == DiscountType.Product)
{
var productDiscount = await _repositoryWrapper.SetRepository<ProductDiscount>()
var productDiscount = await repositoryWrapper.SetRepository<ProductDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);

View File

@ -1,15 +1,8 @@
namespace Netina.Core.EntityServices.DiscountHandlers;
public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateProductDiscountCommand, bool>
public class CalculateProductDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CalculateProductDiscountCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CalculateProductDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(CalculateProductDiscountCommand request, CancellationToken cancellationToken)
{
if (request.Product is ProductSDto product)
@ -30,7 +23,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.CostWithDiscount = request.Cost;
double totalPrice = request.Cost;
var allDiscount = await _repositoryWrapper.SetRepository<Discount>()
var allDiscount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Type == DiscountType.All && d.HasCode == false && d.ExpireDate.Date >= DateTime.Today.Date, cancellationToken);
@ -42,7 +35,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.HasDiscount = true;
}
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
var categoryDiscount = await repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.CategoryId == request.CategoryId && d.HasCode == false && d.ExpireDate.Date >= DateTime.Today.Date, cancellationToken);
@ -53,7 +46,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.HasDiscount = true;
}
var productDiscount = await _repositoryWrapper.SetRepository<ProductDiscount>()
var productDiscount = await repositoryWrapper.SetRepository<ProductDiscount>()
.TableNoTracking
.Where(d => d.HasCode == false && d.ProductId == request.Id && d.ExpireDate.Date >= DateTime.Today.Date)
.OrderByDescending(d => d.CreatedAt)
@ -85,7 +78,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.CostWithDiscount = request.Cost;
double totalPrice = request.Cost;
var allDiscount = await _repositoryWrapper.SetRepository<Discount>()
var allDiscount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Type == DiscountType.All && d.HasCode == false && d.ExpireDate.Date >= DateTime.Today.Date, cancellationToken);
@ -97,7 +90,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.HasDiscount = true;
}
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
var categoryDiscount = await repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.CategoryId == request.CategoryId && d.HasCode == false && d.ExpireDate.Date >= DateTime.Today.Date, cancellationToken);
@ -108,7 +101,7 @@ public class CalculateProductDiscountCommandHandler : IRequestHandler<CalculateP
request.HasDiscount = true;
}
var productDiscount = await _repositoryWrapper.SetRepository<ProductDiscount>()
var productDiscount = await repositoryWrapper.SetRepository<ProductDiscount>()
.TableNoTracking
.Where(d => d.HasCode == false && d.ProductId == request.Id && d.ExpireDate.Date >= DateTime.Today.Date)
.OrderByDescending(d => d.CreatedAt)

View File

@ -1,28 +1,22 @@
namespace Netina.Core.EntityServices.DiscountHandlers;
public class CheckUserDiscountFirstUseCommandHandler : IRequestHandler<CheckUserDiscountFirstUseCommand, bool>
public class CheckUserDiscountFirstUseCommandHandler(
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService)
: IRequestHandler<CheckUserDiscountFirstUseCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CheckUserDiscountFirstUseCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(CheckUserDiscountFirstUseCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId != null && Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (currentUserService.UserId != null && Guid.TryParse(currentUserService.UserId, out Guid userId))
{
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (customer == null)
throw new BaseApiException(ApiResultStatusCode.NotFound, "Customer not found");
var discountedUserOrder = await _repositoryWrapper.SetRepository<Order>()
var discountedUserOrder = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(f => f.CustomerId == customer.Id && f.DiscountCode == request.DiscountCode,
cancellationToken);

View File

@ -1,48 +1,38 @@
namespace Netina.Core.EntityServices.MarketerHandlers;
public class CreateMarketerDiscountCommandHandler : IRequestHandler<CreateMarketerDiscountCommand, string>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
private readonly ISettingService _settingService;
public CreateMarketerDiscountCommandHandler(UserManager<ApplicationUser> userManager,
public class CreateMarketerDiscountCommandHandler(
UserManager<ApplicationUser> userManager,
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService,
ISettingService settingService)
: IRequestHandler<CreateMarketerDiscountCommand, string>
{
_userManager = userManager;
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
_settingService = settingService;
}
public async Task<string> Handle(CreateMarketerDiscountCommand request, CancellationToken cancellationToken)
{
var userId = request.MarketerUserId;
if (userId == default)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("User id is null");
if (!Guid.TryParse(_currentUserService.UserId, out userId))
if (!Guid.TryParse(currentUserService.UserId, out userId))
throw new AppException("User id is wrong");
}
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var marketer = await _repositoryWrapper.SetRepository<Marketer>()
var marketer = await repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking
.FirstOrDefaultAsync(m => m.UserId == user.Id, cancellationToken);
if (marketer == null)
throw new AppException("Marketer not found", ApiResultStatusCode.NotFound);
var foundedDiscount = await _repositoryWrapper.SetRepository<Discount>()
var foundedDiscount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.IsForSaleCooperation && d.MarketerId == marketer.Id, cancellationToken);
if (foundedDiscount == null)
{
var setting = await _settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken);
var setting = await settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken);
int discountPercent = 10;
if (setting is MarketerSetting marketerSetting)
discountPercent = marketerSetting.DiscountPercent;
@ -53,8 +43,8 @@ public class CreateMarketerDiscountCommandHandler : IRequestHandler<CreateMarket
false, 0, false, true, 0, false, false, false);
foundedDiscount.SetCorporate(marketer.Id);
_repositoryWrapper.SetRepository<Discount>().Add(foundedDiscount);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Discount>().Add(foundedDiscount);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return foundedDiscount.Code;
}

View File

@ -2,18 +2,12 @@
namespace Netina.Core.EntityServices.MarketerHandlers;
public class GetMarketerProfileQueryHandler : IRequestHandler<GetMarketerProfileQuery, MarketerProfileResponseDto>
public class GetMarketerProfileQueryHandler(
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService,
ISettingService settingService)
: IRequestHandler<GetMarketerProfileQuery, MarketerProfileResponseDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
private readonly ISettingService _settingService;
public GetMarketerProfileQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService,ISettingService settingService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
_settingService = settingService;
}
public async Task<MarketerProfileResponseDto> Handle(GetMarketerProfileQuery request, CancellationToken cancellationToken)
{
Guid marketerId;
@ -21,17 +15,17 @@ public class GetMarketerProfileQueryHandler : IRequestHandler<GetMarketerProfile
if (request.MarketerId != null)
{
marketerId = request.MarketerId.Value;
marketer = await _repositoryWrapper.SetRepository<Marketer>()
marketer = await repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking
.FirstOrDefaultAsync(m => m.Id == marketerId, cancellationToken);
}
else
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new BaseApiException("User id is null");
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new BaseApiException("User id is wrong");
marketer = await _repositoryWrapper.SetRepository<Marketer>()
marketer = await repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking
.FirstOrDefaultAsync(m => m.UserId == userId, cancellationToken);
@ -40,26 +34,26 @@ public class GetMarketerProfileQueryHandler : IRequestHandler<GetMarketerProfile
if (marketer == null)
throw new BaseApiException(ApiResultStatusCode.MarketerNotFound,"Marketer not found" ,HttpStatusCode.NotFound);
var discount = await _repositoryWrapper.SetRepository<Discount>()
var discount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.MarketerId == marketer.Id, cancellationToken);
if (discount == null)
throw new BaseApiException("Marketer has no discount");
var setting = (await _settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken)) as MarketerSetting;
var setting = (await settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken)) as MarketerSetting;
if (setting == null)
throw new BaseApiException("MarketerSetting is null");
var response = new MarketerProfileResponseDto();
var orderCount = await _repositoryWrapper.SetRepository<Order>()
var orderCount = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.CountAsync(o => o.DiscountCode == discount.Code, cancellationToken);
response.OrderCount = orderCount;
var newTotalProductPrice = await _repositoryWrapper.SetRepository<Order>()
var newTotalProductPrice = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.DiscountCode == discount.Code && o.OrderAt.Date > marketer.LastSettlement.Date)
.SumAsync(o => o.TotalProductsPrice, cancellationToken);

View File

@ -1,36 +1,29 @@
namespace Netina.Core.EntityServices.MarketerHandlers;
public class SignUpMarketerCommandHandler : IRequestHandler<SignUpMarketerCommand,MarketerProfileResponseDto>
public class SignUpMarketerCommandHandler(
UserManager<ApplicationUser> userManager,
IMediator mediator,
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper)
: IRequestHandler<SignUpMarketerCommand, MarketerProfileResponseDto>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IMediator _mediator;
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
public SignUpMarketerCommandHandler(UserManager<ApplicationUser> userManager,IMediator mediator,ICurrentUserService currentUserService,IRepositoryWrapper repositoryWrapper)
{
_userManager = userManager;
_mediator = mediator;
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
}
public async Task<MarketerProfileResponseDto> Handle(SignUpMarketerCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("User id is null");
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("User id is wrong");
var user = await _userManager.FindByIdAsync(_currentUserService.UserId);
var user = await userManager.FindByIdAsync(currentUserService.UserId);
if (user == null)
throw new AppException("User not found");
var marketer = await _repositoryWrapper.SetRepository<Marketer>()
var marketer = await repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking
.FirstOrDefaultAsync(m => m.UserId == userId, cancellationToken);
if (marketer != null)
return await _mediator.Send(new GetMarketerProfileQuery(MarketerId: marketer.Id), cancellationToken);
return await mediator.Send(new GetMarketerProfileQuery(MarketerId: marketer.Id), cancellationToken);
marketer = new Marketer
{
@ -38,16 +31,16 @@ public class SignUpMarketerCommandHandler : IRequestHandler<SignUpMarketerComman
FatherName = request.FatherName,
Shaba = request.Shaba,
};
_repositoryWrapper.SetRepository<Marketer>()
repositoryWrapper.SetRepository<Marketer>()
.Add(marketer);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDate);
user.NationalId = request.NationalId;
await _userManager.UpdateAsync(user);
await userManager.UpdateAsync(user);
await _mediator.Send(new CreateMarketerDiscountCommand(userId), cancellationToken);
await mediator.Send(new CreateMarketerDiscountCommand(userId), cancellationToken);
return await _mediator.Send(new GetMarketerProfileQuery(marketer.Id), cancellationToken);
return await mediator.Send(new GetMarketerProfileQuery(marketer.Id), cancellationToken);
}
}

View File

@ -1,31 +1,24 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class AddToOrderBagCommandHandler : IRequestHandler<AddToOrderBagCommand, OrderSDto>
public class AddToOrderBagCommandHandler(
IMediator mediator,
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService)
: IRequestHandler<AddToOrderBagCommand, OrderSDto>
{
private readonly IMediator _mediator;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public AddToOrderBagCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_mediator = mediator;
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<OrderSDto> Handle(AddToOrderBagCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Customer id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("Customer id wrong", ApiResultStatusCode.BadRequest);
var orderBag = await _mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
var orderBag = await mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
foreach (var requestDto in request.RequestDtos)
{
var product = await _repositoryWrapper.SetRepository<Product>()
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == requestDto.ProductId, cancellationToken);
@ -35,16 +28,16 @@ public class AddToOrderBagCommandHandler : IRequestHandler<AddToOrderBagCommand,
throw new AppException("Product is not enable", ApiResultStatusCode.BadRequest);
var productSDto = product.AdaptToSDto();
await _mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
await mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
orderBag.AddToOrderBag(productSDto.Id, productSDto.Cost, productSDto.CostWithDiscount,
productSDto.HasDiscount, productSDto.PackingCost, productSDto.CategoryId, requestDto.Count);
}
_repositoryWrapper.SetRepository<Order>().Update(orderBag);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Order>().Update(orderBag);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
var order = await _mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
var order = await mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
return order.AdaptToSDto();
}

View File

@ -1,22 +1,15 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class CheckOrderBagCommandHandler : IRequestHandler<CheckOrderBagCommand , List<CheckOrderBagResponseItem>>
public class CheckOrderBagCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
: IRequestHandler<CheckOrderBagCommand, List<CheckOrderBagResponseItem>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public CheckOrderBagCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task<List<CheckOrderBagResponseItem>> Handle(CheckOrderBagCommand request, CancellationToken cancellationToken)
{
List<CheckOrderBagResponseItem> response = new List<CheckOrderBagResponseItem>();
foreach (var item in request.OrderBag)
{
var product = await _repositoryWrapper.SetRepository<Product>()
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.Where(p => p.Id == item.ProductId)
.Select(ProductMapper.ProjectToSDto)
@ -35,7 +28,7 @@ public class CheckOrderBagCommandHandler : IRequestHandler<CheckOrderBagCommand
}
else
{
await _mediator.Send(new CalculateProductDiscountCommand(product), cancellationToken);
await mediator.Send(new CalculateProductDiscountCommand(product), cancellationToken);
var res = new CheckOrderBagResponseItem
{
ProductId = item.ProductId,

View File

@ -1,25 +1,19 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class GetUserOrderBagQueryHandler : IRequestHandler<GetUserOrderBagQuery,Order>
public class GetUserOrderBagQueryHandler(
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService,
IMediator mediator)
: IRequestHandler<GetUserOrderBagQuery, Order>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
private readonly IMediator _mediator;
public GetUserOrderBagQueryHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService,IMediator mediator)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
_mediator = mediator;
}
public async Task<Order> Handle(GetUserOrderBagQuery request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Customer id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("Customer id wrong",ApiResultStatusCode.BadRequest);
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (customer == null)
@ -28,20 +22,20 @@ public class GetUserOrderBagQueryHandler : IRequestHandler<GetUserOrderBagQuery,
{
UserId = userId
};
_repositoryWrapper.SetRepository<Customer>()
repositoryWrapper.SetRepository<Customer>()
.Add(customer);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.CustomerId == customer.Id && o.OrderStatus == OrderStatus.OrderBag,cancellationToken);
if (order == null)
order = await _mediator.Send(new CreateBaseOrderCommand(userId),cancellationToken);
order = await mediator.Send(new CreateBaseOrderCommand(userId),cancellationToken);
else
{
var orderProducts = await _repositoryWrapper.SetRepository<OrderProduct>()
var orderProducts = await repositoryWrapper.SetRepository<OrderProduct>()
.TableNoTracking
.Where(op=>op.OrderId==order.Id)
.ToListAsync(cancellationToken);

View File

@ -1,29 +1,23 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class RemoveFromOrderBagCommandHandler : IRequestHandler<RemoveFromOrderBagCommand, OrderSDto>
public class RemoveFromOrderBagCommandHandler(
ICurrentUserService currentUserService,
IRepositoryWrapper repositoryWrapper,
IMediator mediator)
: IRequestHandler<RemoveFromOrderBagCommand, OrderSDto>
{
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public RemoveFromOrderBagCommandHandler(ICurrentUserService currentUserService, IRepositoryWrapper repositoryWrapper,IMediator mediator)
{
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task<OrderSDto> Handle(RemoveFromOrderBagCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Customer id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("Customer id wrong", ApiResultStatusCode.BadRequest);
var orderBag = await _mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
var orderBag = await mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
foreach (var requestDto in request.RequestDtos)
{
var product = await _repositoryWrapper.SetRepository<Product>()
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == requestDto.ProductId, cancellationToken);
@ -37,9 +31,9 @@ public class RemoveFromOrderBagCommandHandler : IRequestHandler<RemoveFromOrderB
}
_repositoryWrapper.SetRepository<Order>().Update(orderBag);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
var order = await _mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
repositoryWrapper.SetRepository<Order>().Update(orderBag);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
var order = await mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
return order.AdaptToSDto();
}

View File

@ -1,18 +1,11 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class SubmitDiscountActionCommandHandler : IRequestHandler<SubmitDiscountActionCommand, OrderSDto>
public class SubmitDiscountActionCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
: IRequestHandler<SubmitDiscountActionCommand, OrderSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
public SubmitDiscountActionCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task<OrderSDto> Handle(SubmitDiscountActionCommand request, CancellationToken cancellationToken)
{
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order == null)
@ -20,13 +13,13 @@ public class SubmitDiscountActionCommandHandler : IRequestHandler<SubmitDiscount
if (request.DiscountCode != null)
{
var discount = await _repositoryWrapper.SetRepository<Discount>()
var discount = await repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
if (discount == null || discount.IsExpired())
throw new AppException("تخفیف منقضی شده است یا وجود ندارد", ApiResultStatusCode.NotFound);
var isFirstUserOfDiscount = await _mediator.Send(new CheckUserDiscountFirstUseCommand(request.DiscountCode), cancellationToken);
var isFirstUserOfDiscount = await mediator.Send(new CheckUserDiscountFirstUseCommand(request.DiscountCode), cancellationToken);
if (!isFirstUserOfDiscount)
throw new BaseApiException(ApiResultStatusCode.BadRequest, "شما یک بار از این کد تخفیف استفاده نموده اید و قابلیت استفاده مجدد ندارید");
@ -36,9 +29,9 @@ public class SubmitDiscountActionCommandHandler : IRequestHandler<SubmitDiscount
else
order.RemoveDiscount();
_repositoryWrapper.SetRepository<Order>().Update(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
var calculateOrder = await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
repositoryWrapper.SetRepository<Order>().Update(order);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
var calculateOrder = await mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
return calculateOrder.AdaptToSDto();
}

View File

@ -1,31 +1,24 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class SubmitOrderBagCommandHandler : IRequestHandler<SubmitOrderBagCommand,OrderSDto>
public class SubmitOrderBagCommandHandler(
IMediator mediator,
IRepositoryWrapper repositoryWrapper,
ICurrentUserService currentUserService)
: IRequestHandler<SubmitOrderBagCommand, OrderSDto>
{
private readonly IMediator _mediator;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public SubmitOrderBagCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_mediator = mediator;
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<OrderSDto> Handle(SubmitOrderBagCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Customer id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("Customer id wrong", ApiResultStatusCode.BadRequest);
var orderBag = await _mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
var orderBag = await mediator.Send(new GetUserOrderBagQuery(), cancellationToken);
foreach (var requestDto in request.RequestDtos)
{
var product = await _repositoryWrapper.SetRepository<Product>()
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == requestDto.ProductId, cancellationToken);
@ -35,7 +28,7 @@ public class SubmitOrderBagCommandHandler : IRequestHandler<SubmitOrderBagComman
throw new AppException("Product is not enable", ApiResultStatusCode.BadRequest);
var productSDto = product.AdaptToSDto();
await _mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
await mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
orderBag.ChangeOrderBag(productSDto.Id, productSDto.Cost, productSDto.CostWithDiscount,
productSDto.HasDiscount, productSDto.PackingCost, productSDto.CategoryId, requestDto.Count);
@ -45,15 +38,15 @@ public class SubmitOrderBagCommandHandler : IRequestHandler<SubmitOrderBagComman
if(request.RequestDtos.FirstOrDefault(op=>op.ProductId==orderProduct.ProductId)==null)
{
orderBag.OrderProducts.Remove(orderProduct);
_repositoryWrapper.SetRepository<OrderProduct>().Delete(orderProduct);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<OrderProduct>().Delete(orderProduct);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
}
_repositoryWrapper.SetRepository<Order>().Update(orderBag);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Order>().Update(orderBag);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
var order = await _mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
var order = await mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);
return order.AdaptToSDto();
}

View File

@ -2,26 +2,19 @@
namespace Netina.Core.EntityServices.OrderBagHandlers;
public class SubmitOrderDeliveryCommandHandler : IRequestHandler<SubmitOrderDeliveryCommand, OrderSDto>
public class SubmitOrderDeliveryCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper)
: IRequestHandler<SubmitOrderDeliveryCommand, OrderSDto>
{
private readonly IMediator _mediator;
private readonly IRepositoryWrapper _repositoryWrapper;
public SubmitOrderDeliveryCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper)
{
_mediator = mediator;
_repositoryWrapper = repositoryWrapper;
}
public async Task<OrderSDto> Handle(SubmitOrderDeliveryCommand request, CancellationToken cancellationToken)
{
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order == null)
throw new AppException("Order not found", ApiResultStatusCode.NotFound);
var orderDelivery = await _repositoryWrapper.SetRepository<OrderDelivery>()
var orderDelivery = await repositoryWrapper.SetRepository<OrderDelivery>()
.TableNoTracking
.FirstOrDefaultAsync(od => od.OrderId == request.OrderId, cancellationToken);
if (orderDelivery != null)
@ -29,7 +22,7 @@ public class SubmitOrderDeliveryCommandHandler : IRequestHandler<SubmitOrderDeli
order.AddOrderDelivery(orderDelivery.AddressId, orderDelivery.DeliveryCost, orderDelivery.ShippingId, orderDelivery.OrderId, orderDelivery.Id);
}
var shipping = await _repositoryWrapper.SetRepository<Shipping>()
var shipping = await repositoryWrapper.SetRepository<Shipping>()
.TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.ShippingId, cancellationToken);
if (shipping == null)
@ -37,10 +30,10 @@ public class SubmitOrderDeliveryCommandHandler : IRequestHandler<SubmitOrderDeli
order.AddOrderDelivery(request.AddressId, shipping.DeliveryCost, request.ShippingId, request.OrderId);
_repositoryWrapper.SetRepository<Order>().Update(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Order>().Update(order);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
var calculatedOrder = await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
var calculatedOrder = await mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
return calculatedOrder.AdaptToSDto();
}
}

View File

@ -1,23 +1,18 @@
namespace Netina.Core.EntityServices.ReviewHandlers;
public class ConfirmReviewCommandHandler : IRequestHandler<ConfirmReviewCommand , bool>
public class ConfirmReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<ConfirmReviewCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public ConfirmReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(ConfirmReviewCommand request, CancellationToken cancellationToken)
{
var review = await _repositoryWrapper.SetRepository<Review>().TableNoTracking
var review = await repositoryWrapper.SetRepository<Review>().TableNoTracking
.FirstOrDefaultAsync(r => r.Id == request.Id, cancellationToken);
if (review == null)
throw new AppException("Review not found", ApiResultStatusCode.NotFound);
review.ConfirmReview();
_repositoryWrapper.SetRepository<Review>().Update(review);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Review>().Update(review);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,33 +1,19 @@
namespace Netina.Core.EntityServices;
public class UserService : IUserService
{
private readonly ICurrentUserService _currentUserService;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IExternalFilesService _externalFilesService;
private readonly IRepositoryWrapper _repositoryWrapper;
public UserService(ICurrentUserService currentUserService,
public class UserService(
ICurrentUserService currentUserService,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
IExternalFilesService externalFilesService,
IRepositoryWrapper repositoryWrapper)
: IUserService
{
_currentUserService = currentUserService;
_userManager = userManager;
_roleManager = roleManager;
_externalFilesService = externalFilesService;
_repositoryWrapper = repositoryWrapper;
}
public async Task<ProfileResponseDto> GetUserProfileAsync(CancellationToken cancellationToken)
{
if (!Guid.TryParse(_currentUserService.UserId, out var userId))
if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
@ -36,14 +22,14 @@ public class UserService : IUserService
//var userSDto = user.AdaptToSDto();
response.User = new ApplicationUserSDto();
var userRoles = await _userManager.GetRolesAsync(user);
var userRoles = await userManager.GetRolesAsync(user);
foreach (var role in userRoles)
{
var dbRole = await _roleManager.FindByNameAsync(role);
var dbRole = await roleManager.FindByNameAsync(role);
if (dbRole != null)
{
var roleClaims = await _roleManager.GetClaimsAsync(dbRole);
var roleClaims = await roleManager.GetClaimsAsync(dbRole);
response.Permissions.AddRange(roleClaims.Where(c => c.Type == "Permission").Select(c => c.Value).ToList());
}
}
@ -57,23 +43,23 @@ public class UserService : IUserService
List<ApplicationUserSDto> users;
if (phoneNumber == null || phoneNumber.IsNullOrEmpty())
users = await _userManager.Users
users = await userManager.Users
.Where(u => u.UserName != "09214802813")
.Skip(page * 15).Take(15)
.Select(ApplicationUserMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
else
users = await _userManager.Users
users = await userManager.Users
.Where(a => a.PhoneNumber == phoneNumber && a.UserName != "09214802813")
.Skip(page * 15).Take(15)
.Select(ApplicationUserMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
foreach (var user in users)
{
var roles = await _userManager.GetRolesAsync(user.AdaptToApplicationUser());
var roles = await userManager.GetRolesAsync(user.AdaptToApplicationUser());
foreach (var roleName in roles)
{
var role = await _roleManager.FindByNameAsync(roleName);
var role = await roleManager.FindByNameAsync(roleName);
if (role != null)
user.RoleName += role.PersianName + " ";
}
@ -85,20 +71,20 @@ public class UserService : IUserService
public async Task<ApplicationUserSDto> GetUserAsync(Guid userId, CancellationToken cancellationToken = default)
{
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var dto = user.AdaptToSDto();
dto.IsMarketer = await _repositoryWrapper.SetRepository<Marketer>()
dto.IsMarketer = await repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking
.AnyAsync(m => m.UserId == userId, cancellationToken);
dto.IsManager = await _repositoryWrapper.SetRepository<Manager>()
dto.IsManager = await repositoryWrapper.SetRepository<Manager>()
.TableNoTracking
.AnyAsync(m => m.UserId == userId, cancellationToken);
var roles = await _userManager.GetRolesAsync(user);
var roles = await userManager.GetRolesAsync(user);
foreach (var roleName in roles)
{
var role = await _roleManager.FindByNameAsync(roleName);
var role = await roleManager.FindByNameAsync(roleName);
if (role != null)
dto.RoleIds.Add(role.Id);
}
@ -113,7 +99,7 @@ public class UserService : IUserService
PhoneNumber = phoneNumber,
SignUpStatus = SignUpStatus.StartSignOn
};
var result = await _userManager.CreateAsync(user);
var result = await userManager.CreateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors));
return user;
@ -122,7 +108,7 @@ public class UserService : IUserService
public async Task<ApplicationUser> CreateUserAsync(UserActionRequestDto request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByNameAsync(request.PhoneNumber);
var user = await userManager.FindByNameAsync(request.PhoneNumber);
if (user == null)
{
user = new ApplicationUser
@ -140,13 +126,13 @@ public class UserService : IUserService
if (!request.Password.IsNullOrEmpty())
{
var result = await _userManager.CreateAsync(user, request.Password);
var result = await userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
}
else
{
var result = await _userManager.CreateAsync(user);
var result = await userManager.CreateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
}
@ -155,31 +141,31 @@ public class UserService : IUserService
{
foreach (var roleId in request.RoleIds)
{
var role = await _roleManager.FindByIdAsync(roleId.ToString());
var role = await roleManager.FindByIdAsync(roleId.ToString());
if (role is { Name: not null })
await _userManager.AddToRoleAsync(user, role.Name);
await userManager.AddToRoleAsync(user, role.Name);
}
}
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == user.Id, cancellationToken);
if (customer != null)
{
_repositoryWrapper.SetRepository<Customer>()
repositoryWrapper.SetRepository<Customer>()
.Add(new Customer
{
UserId = user.Id
});
await _repositoryWrapper.SaveChangesAsync(default);
await repositoryWrapper.SaveChangesAsync(default);
}
_repositoryWrapper.SetRepository<Manager>()
repositoryWrapper.SetRepository<Manager>()
.Add(new Manager
{
UserId = user.Id
});
await _repositoryWrapper.SaveChangesAsync(default);
await repositoryWrapper.SaveChangesAsync(default);
}
return user;
}
@ -189,7 +175,7 @@ public class UserService : IUserService
if (request.UserId == Guid.Empty)
throw new AppException("Wrong authorize token , UserId needed");
var user = await _userManager.FindByIdAsync(request.UserId.ToString());
var user = await userManager.FindByIdAsync(request.UserId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
user.LastName = request.LastName;
@ -202,29 +188,29 @@ public class UserService : IUserService
user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp);
user.Gender = request.Gender;
var result = await _userManager.UpdateAsync(user);
var result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
if (!request.Password.IsNullOrEmpty())
{
if (await _userManager.HasPasswordAsync(user))
await _userManager.RemovePasswordAsync(user);
if (await userManager.HasPasswordAsync(user))
await userManager.RemovePasswordAsync(user);
var addPassResult = await _userManager.AddPasswordAsync(user, request.Password);
var addPassResult = await userManager.AddPasswordAsync(user, request.Password);
if (!addPassResult.Succeeded)
throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description)));
}
if (request.RoleIds.Count > 0)
{
var userRoles = await _userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, userRoles);
var userRoles = await userManager.GetRolesAsync(user);
await userManager.RemoveFromRolesAsync(user, userRoles);
foreach (var roleId in request.RoleIds)
{
var role = await _roleManager.FindByIdAsync(roleId.ToString());
var role = await roleManager.FindByIdAsync(roleId.ToString());
if (role is { Name: not null })
{
await _userManager.AddToRoleAsync(user, role.Name);
await userManager.AddToRoleAsync(user, role.Name);
}
}
}
@ -234,10 +220,10 @@ public class UserService : IUserService
public async Task<bool> EditUserProfileAsync(UserActionRequestDto request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Wrong authorize token , UserId needed");
var user = await _userManager.FindByIdAsync(_currentUserService.UserId);
var user = await userManager.FindByIdAsync(currentUserService.UserId);
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
user.LastName = request.LastName;
@ -250,15 +236,15 @@ public class UserService : IUserService
user.BirthDate = DateTimeExtensions.UnixTimeStampToDateTime(request.BirthDateTimeStamp);
user.Gender = request.Gender;
var result = await _userManager.UpdateAsync(user);
var result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new AppException(string.Join('|', result.Errors.Select(e => e.Description)));
if (!request.Password.IsNullOrEmpty())
{
if (await _userManager.HasPasswordAsync(user))
await _userManager.RemovePasswordAsync(user);
if (await userManager.HasPasswordAsync(user))
await userManager.RemovePasswordAsync(user);
var addPassResult = await _userManager.AddPasswordAsync(user, request.Password);
var addPassResult = await userManager.AddPasswordAsync(user, request.Password);
if (!addPassResult.Succeeded)
throw new AppException(string.Join('|', addPassResult.Errors.Select(e => e.Description)));
}
@ -268,34 +254,34 @@ public class UserService : IUserService
public async Task<bool> RemoveUserAsync(Guid userId, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var roles = await _userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, roles);
var removeResult = await _userManager.DeleteAsync(user);
var roles = await userManager.GetRolesAsync(user);
await userManager.RemoveFromRolesAsync(user, roles);
var removeResult = await userManager.DeleteAsync(user);
if (!removeResult.Succeeded)
throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (customer != null)
{
_repositoryWrapper.SetRepository<Customer>()
repositoryWrapper.SetRepository<Customer>()
.Delete(customer);
await _repositoryWrapper.SaveChangesAsync(default);
await repositoryWrapper.SaveChangesAsync(default);
}
var manager = await _repositoryWrapper.SetRepository<Manager>()
var manager = await repositoryWrapper.SetRepository<Manager>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (manager != null)
{
_repositoryWrapper.SetRepository<Manager>()
repositoryWrapper.SetRepository<Manager>()
.Delete(manager);
await _repositoryWrapper.SaveChangesAsync(default);
await repositoryWrapper.SaveChangesAsync(default);
}
return true;
@ -303,26 +289,26 @@ public class UserService : IUserService
public async Task<AdminChangeLogResponseDto> GetAdminChangeLogAsync(CancellationToken cancellationToken = default)
{
if (!Guid.TryParse(_currentUserService.UserId, out var userId))
if (!Guid.TryParse(currentUserService.UserId, out var userId))
throw new AppException("Wrong Token", ApiResultStatusCode.UnAuthorized);
var user = await _userManager.FindByIdAsync(userId.ToString());
var user = await userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User NotFound", ApiResultStatusCode.NotFound);
var manager = await _repositoryWrapper.SetRepository<Manager>()
var manager = await repositoryWrapper.SetRepository<Manager>()
.TableNoTracking
.FirstOrDefaultAsync(m => m.UserId == userId, cancellationToken);
var currentVersion = await _externalFilesService.GetAdminChangeLogAsync(cancellationToken);
var currentVersion = await externalFilesService.GetAdminChangeLogAsync(cancellationToken);
if (manager != null)
{
if (!(manager.LatestVersionUsed < currentVersion.VersionNumber)) return currentVersion;
currentVersion.IsNewVersion = true;
manager.LatestVersionUsed = currentVersion.VersionNumber;
_repositoryWrapper.SetRepository<Manager>()
repositoryWrapper.SetRepository<Manager>()
.Update(manager);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
return currentVersion;
@ -331,7 +317,7 @@ public class UserService : IUserService
public async Task<List<ApplicationRole>> GetRolesAsync(int page = 0, CancellationToken cancellationToken = default)
{
var roles = await _roleManager.Roles
var roles = await roleManager.Roles
.Where(r => r.Name != "RootAdmin")
.Skip(page * 15)
.Take(15)
@ -343,9 +329,9 @@ public class UserService : IUserService
{
IQueryable<ApplicationRole> roles;
if (roleName != null)
roles = _roleManager.Roles.Where(r => r.Name != "RootAdmin" && r.Name != "Customer" && r.PersianName.Trim().ToLower().Contains(roleName));
roles = roleManager.Roles.Where(r => r.Name != "RootAdmin" && r.Name != "Customer" && r.PersianName.Trim().ToLower().Contains(roleName));
else
roles = _roleManager.Roles.Where(r => r.Name != "RootAdmin" && r.Name != "Customer");
roles = roleManager.Roles.Where(r => r.Name != "RootAdmin" && r.Name != "Customer");
if (page != null)
roles = roles.Skip(page.Value * 15).Take(15);
else
@ -355,13 +341,13 @@ public class UserService : IUserService
public async Task<RoleActionRequestDto> GetRoleAsync(Guid roleId, CancellationToken cancellationToken = default)
{
var role = (await _roleManager.FindByIdAsync(roleId.ToString()));
var role = (await roleManager.FindByIdAsync(roleId.ToString()));
if (role == null)
throw new AppException("نقش پیدا نشد", ApiResultStatusCode.NotFound);
var roleDto = role.Adapt<RoleActionRequestDto>();
roleDto.RoleId = roleId;
roleDto.Permissions = (await _roleManager.GetClaimsAsync(role))
roleDto.Permissions = (await roleManager.GetClaimsAsync(role))
.Where(c => c.Type == CustomClaimType.Permission)
.Select(c => c.Value)
.ToList();
@ -380,12 +366,12 @@ public class UserService : IUserService
Description = request.Description,
Name = $"{request.EnglishName}"
};
var createRoleResult = await _roleManager.CreateAsync(applicationRole);
var createRoleResult = await roleManager.CreateAsync(applicationRole);
if (!createRoleResult.Succeeded)
throw new AppException(string.Join('|', createRoleResult.Errors));
foreach (var claim in request.Permissions)
await _roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
await roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
return applicationRole;
}
@ -393,7 +379,7 @@ public class UserService : IUserService
{
if (request.EnglishName.IsNullOrEmpty())
throw new AppException("لطفا نام انگلیسی را وارد کنید");
var applicationRole = await _roleManager.FindByIdAsync(request.RoleId.ToString());
var applicationRole = await roleManager.FindByIdAsync(request.RoleId.ToString());
if (applicationRole == null)
throw new AppException("نقش پیدا نشد");
@ -402,20 +388,20 @@ public class UserService : IUserService
applicationRole.Description = request.Description;
applicationRole.Name = $"{request.EnglishName}";
var createRoleResult = await _roleManager.UpdateAsync(applicationRole);
var createRoleResult = await roleManager.UpdateAsync(applicationRole);
if (!createRoleResult.Succeeded)
throw new AppException(string.Join('|', createRoleResult.Errors));
var roleClaims = (await _roleManager.GetClaimsAsync(applicationRole)).Where(c => c.Type == CustomClaimType.Permission).ToList();
var roleClaims = (await roleManager.GetClaimsAsync(applicationRole)).Where(c => c.Type == CustomClaimType.Permission).ToList();
foreach (var roleClaim in roleClaims.ToList())
{
var removeResult = await _roleManager.RemoveClaimAsync(applicationRole, roleClaim);
var removeResult = await roleManager.RemoveClaimAsync(applicationRole, roleClaim);
if (!removeResult.Succeeded)
throw new AppException(string.Join(" | ", removeResult.Errors.Select(e => e.Description)));
}
foreach (var claim in request.Permissions)
{
var addResult = await _roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
var addResult = await roleManager.AddClaimAsync(applicationRole, new Claim(CustomClaimType.Permission, claim));
if (!addResult.Succeeded)
throw new AppException(string.Join(" | ", addResult.Errors.Select(e => e.Description)));
}
@ -425,18 +411,18 @@ public class UserService : IUserService
public async Task<bool> RemoveRoleAsync(Guid roleId, CancellationToken cancellationToken = default)
{
var applicationRole = await _roleManager.FindByIdAsync(roleId.ToString());
var applicationRole = await roleManager.FindByIdAsync(roleId.ToString());
if (applicationRole == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
var claims = await _roleManager.GetClaimsAsync(applicationRole);
var claims = await roleManager.GetClaimsAsync(applicationRole);
foreach (var claim in claims)
await _roleManager.RemoveClaimAsync(applicationRole, claim);
var users = await _userManager.GetUsersInRoleAsync(applicationRole.Name);
await roleManager.RemoveClaimAsync(applicationRole, claim);
var users = await userManager.GetUsersInRoleAsync(applicationRole.Name);
foreach (var user in users)
await _userManager.RemoveFromRoleAsync(user, applicationRole.Name);
await userManager.RemoveFromRoleAsync(user, applicationRole.Name);
var removeResult = await _roleManager.DeleteAsync(applicationRole);
var removeResult = await roleManager.DeleteAsync(applicationRole);
if (!removeResult.Succeeded)
throw new AppException(string.Join('|', removeResult.Errors.Select(e => e.Description)));
return true;

View File

@ -1,18 +1,11 @@
namespace Netina.Core.Models.Api;
public class ApiResult
public class ApiResult(bool isSuccess, ApiResultStatusCode statusCode, string message = null)
{
public ApiResult(bool isSuccess, ApiResultStatusCode statusCode, string message = null)
{
IsSuccess = isSuccess;
StatusCode = statusCode;
Message = message ?? statusCode.ToDisplay();
}
public bool IsSuccess { get; set; }
public ApiResultStatusCode StatusCode { get; set; }
public bool IsSuccess { get; set; } = isSuccess;
public ApiResultStatusCode StatusCode { get; set; } = statusCode;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
public string Message { get; set; } = message ?? statusCode.ToDisplay();
#region Implicit Operators
@ -61,17 +54,12 @@ public class ApiResult
#endregion
}
public class ApiResult<TData> : ApiResult
public class ApiResult<TData>(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null)
: ApiResult(isSuccess, statusCode, message)
where TData : class
{
public ApiResult(bool isSuccess, ApiResultStatusCode statusCode, TData data, string message = null)
: base(isSuccess, statusCode, message)
{
Data = data;
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TData Data { get; set; }
public TData Data { get; set; } = data;
#region Implicit Operators

View File

@ -3,20 +3,11 @@ using Quartz;
namespace Netina.Core.QuartzServices;
public class JobScheduler
public class JobScheduler(IScheduler scheduler, ILogger<JobScheduler> logger)
{
private readonly IScheduler _scheduler;
private readonly ILogger<JobScheduler> _logger;
public JobScheduler(IScheduler scheduler, ILogger<JobScheduler> logger)
{
_scheduler = scheduler;
_logger = logger;
}
public void Start()
{
_scheduler.Start();
scheduler.Start();
IJobDetail job = JobBuilder.Create<SiteMapScheduledJob>()
.WithIdentity("SiteMapJob", "admin")
@ -33,10 +24,10 @@ public class JobScheduler
DayOfWeek.Friday))
.StartNow()
.Build();
var offset = _scheduler.ScheduleJob(job, trigger);
var offset = scheduler.ScheduleJob(job, trigger);
_logger.LogInformation($"======== Table Schedulers Set For {offset.Result.ToString()} IN {DateTime.Now.ToString()} ===========");
logger.LogInformation($"======== Table Schedulers Set For {offset.Result.ToString()} IN {DateTime.Now.ToString()} ===========");
}
}

View File

@ -3,20 +3,12 @@ using Quartz;
namespace Netina.Core.QuartzServices;
public class SiteMapScheduledJob : IJob
public class SiteMapScheduledJob(ILogger<SiteMapScheduledJob> logger, ISiteMapService siteMapService)
: IJob
{
private readonly ILogger<SiteMapScheduledJob> _logger;
private readonly ISiteMapService _siteMapService;
public SiteMapScheduledJob(ILogger<SiteMapScheduledJob> logger,ISiteMapService siteMapService)
{
_logger = logger;
_siteMapService = siteMapService;
}
public async Task Execute(IJobExecutionContext context)
{
await _siteMapService.CreateSiteMapAsync();
_logger.LogInformation($"Site Map Job Done At : {DateTime.Now}");
await siteMapService.CreateSiteMapAsync();
logger.LogInformation($"Site Map Job Done At : {DateTime.Now}");
}
}

View File

@ -1,6 +1,4 @@
using Microsoft.IdentityModel.Tokens;
namespace Netina.Domain.Dtos.SmallDtos;
namespace Netina.Domain.Dtos.SmallDtos;
public class StorageFileSDto : BaseDto<StorageFileSDto , StorageFile>
{

View File

@ -1,6 +1,4 @@
using Microsoft.IdentityModel.Tokens;
namespace Netina.Domain.Entities.Blogs;
namespace Netina.Domain.Entities.Blogs;
public partial class Blog
{

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Domain.Entities.Brands;
namespace Netina.Domain.Entities.Brands;
[AdaptTwoWays("[name]LDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget | MapType.Projection)]
[AdaptTwoWays("[name]SDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget)]

View File

@ -1,6 +1,4 @@
using System.Web;
namespace Netina.Domain.Entities.ProductCategories;
namespace Netina.Domain.Entities.ProductCategories;
public partial class ProductCategory
{

View File

@ -1,7 +1,4 @@
using System.Web;
using System.Xml.Linq;
namespace Netina.Domain.Entities.Products;
namespace Netina.Domain.Entities.Products;
public partial class Product
{

View File

@ -9,11 +9,7 @@ public class NavMenuSetting
public class NavMenuItem
{
public NavMenuItem()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public Guid Id { get; set; } = Guid.NewGuid();
public string Title { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public Guid ParentId { get; set; }

View File

@ -1,6 +1,4 @@
using Netina.Infrastructure.Models.RestApi.KaveNegar;
namespace Netina.Infrastructure.RestServices;
namespace Netina.Infrastructure.RestServices;
public interface IKaveNegarRestApi
{

View File

@ -1,5 +1,4 @@
using Netina.Common.Models;
using Netina.Infrastructure.Models;
using Netina.Infrastructure.Models;
namespace Netina.Infrastructure.RestServices;

View File

@ -1,6 +1,4 @@
using Netina.Common.Models.Exception;
using Netina.Core.Abstracts;
using Netina.Domain.Models.Districts;
using Netina.Domain.Models.Districts;
using Netina.Infrastructure.Models;
using Newtonsoft.Json;

View File

@ -1,23 +1,15 @@
using Netina.Core.Abstracts;
using Netina.Domain.Dtos.ResponseDtos;
using Netina.Domain.Models.Settings;
using Netina.Infrastructure.RestServices;
using Netina.Domain.Dtos.ResponseDtos;
namespace Netina.Infrastructure.Services;
public class ExternalFilesService : IExternalFilesService
public class ExternalFilesService(IRestApiWrapper restApiWrapper, IOptionsSnapshot<SiteSettings> snapshot)
: IExternalFilesService
{
private readonly IRestApiWrapper _restApiWrapper;
private readonly SiteSettings _siteSetting;
private readonly SiteSettings _siteSetting = snapshot.Value;
public ExternalFilesService(IRestApiWrapper restApiWrapper,IOptionsSnapshot<SiteSettings> snapshot)
{
_restApiWrapper = restApiWrapper;
_siteSetting = snapshot.Value;
}
public async Task<AdminChangeLogResponseDto> GetAdminChangeLogAsync(CancellationToken cancellationToken = default)
{
var changeLog = await _restApiWrapper.FileRestApi(_siteSetting.AdminPanelBaseUrl).GetAdminChangeLog();
var changeLog = await restApiWrapper.FileRestApi(_siteSetting.AdminPanelBaseUrl).GetAdminChangeLog();
return changeLog;
}
}

View File

@ -1,6 +1,5 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Netina.Domain.CommandQueries.Commands;
using Netina.Domain.Dtos.ScraperDtos.Response;
using Netina.Domain.Dtos.SmallDtos;
@ -10,23 +9,16 @@ using Netina.Repository.Repositories.Base.Contracts;
namespace Netina.Infrastructure.Services.Scrapers;
public class DigikalaScraper : IDigikalaScraper
public class DigikalaScraper(
IRestApiWrapper apiWrapper,
IRepositoryWrapper repositoryWrapper,
IMediator mediator,
IUploadFileService uploadFileService)
: IDigikalaScraper
{
private readonly IRestApiWrapper _apiWrapper;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
private readonly IUploadFileService _uploadFileService;
public DigikalaScraper(IRestApiWrapper apiWrapper, IRepositoryWrapper repositoryWrapper, IMediator mediator, IUploadFileService uploadFileService)
{
_apiWrapper = apiWrapper;
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
_uploadFileService = uploadFileService;
}
public async Task<List<ScraperProductDto>> GetProductsByNameAsync(string productName)
{
var products = await _apiWrapper.DigikalaRestApi.SearchProductAsync(productName);
var products = await apiWrapper.DigikalaRestApi.SearchProductAsync(productName);
return products.data.products.Select(s => new ScraperProductDto
{
PersianName = s.title_fa,
@ -40,7 +32,7 @@ public class DigikalaScraper : IDigikalaScraper
public async Task<bool> AddProductToShopAsync(string productId, string productName, CancellationToken cancellationToken = default)
{
var response = await _apiWrapper.DigikalaRestApi.GetProductAsync(productId);
var response = await apiWrapper.DigikalaRestApi.GetProductAsync(productId);
var digiProduct = response.data;
var newSummery = digiProduct.seo.description.Replace("فروشگاه اینترنتی دیجی\u200cکالا", "فروشگاه اینترنتی وسمه");
@ -63,7 +55,7 @@ public class DigikalaScraper : IDigikalaScraper
FileUploadType = FileUploadType.Image,
ContentType = "image/jpeg"
};
var uploadResponse = await _uploadFileService.UploadImageAsync(uploadFile);
var uploadResponse = await uploadFileService.UploadImageAsync(uploadFile);
var files = new List<StorageFileSDto>
{
new StorageFileSDto
@ -73,26 +65,26 @@ public class DigikalaScraper : IDigikalaScraper
IsPrimary = true,
}
};
var nonBrand = await _repositoryWrapper.SetRepository<Brand>()
var nonBrand = await repositoryWrapper.SetRepository<Brand>()
.TableNoTracking
.FirstOrDefaultAsync(b => b.PersianName == "بدون برند", cancellationToken);
if (nonBrand == null)
{
nonBrand = Brand.Create("بدون برند" , "NoBrand","محصولات بدون برند",false,string.Empty);
_repositoryWrapper.SetRepository<Brand>()
repositoryWrapper.SetRepository<Brand>()
.Add(nonBrand);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
var nonCat = await _repositoryWrapper.SetRepository<ProductCategory>()
var nonCat = await repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.FirstOrDefaultAsync(b => b.Name == "دسته بندی نشده", cancellationToken);
if (nonCat == null)
{
nonCat = ProductCategory.Create("دسته بندی نشده", "محصولات بدون دسته بندی", false);
_repositoryWrapper.SetRepository<ProductCategory>()
repositoryWrapper.SetRepository<ProductCategory>()
.Add(nonCat);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
if (digiProduct.product.title_en.IsNullOrEmpty())
@ -103,7 +95,7 @@ public class DigikalaScraper : IDigikalaScraper
string.Empty, string.Empty, string.Empty, true, 0,
0, 0, false
, 5, false, nonBrand.Id, nonCat.Id, new DiscountSDto(), specifications, files,new Dictionary<string, string>(),new Dictionary<string, string>());
await _mediator.Send(request, cancellationToken);
await mediator.Send(request, cancellationToken);
return true;
}

View File

@ -1,25 +1,17 @@
namespace Netina.Infrastructure.Services;
public class SmsService : ISmsService
{
private readonly IRestApiWrapper _restApiWrapper;
private readonly ILogger<SmsService> _logger;
private readonly IHostEnvironment _environment;
private readonly SiteSettings _siteSettings;
public SmsService(
public class SmsService(
IRestApiWrapper restApiWrapper,
IOptionsSnapshot<SiteSettings> optionsSnapshot,
ILogger<SmsService> logger,
IHostEnvironment environment)
: ISmsService
{
_restApiWrapper = restApiWrapper;
_logger = logger;
_environment = environment;
_siteSettings = optionsSnapshot.Value;
}
private readonly SiteSettings _siteSettings = optionsSnapshot.Value;
public async Task SendForgerPasswordAsync(string phoneNumber, string newPassword)
{
var rest = await _restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, newPassword,
var rest = await restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, newPassword,
null, null
, null, null, "forgetPassword");
@ -32,24 +24,24 @@ public class SmsService : ISmsService
try
{
var rest = await _restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, _siteSettings.LoginOtpTemplate,verifyCode);
var rest = await restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber, _siteSettings.LoginOtpTemplate,verifyCode);
if (rest.Return.status != 200 && _environment.IsProduction())
if (rest.Return.status != 200 && environment.IsProduction())
throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message);
}
catch (ApiException apiException)
{
if (_environment.IsProduction())
if (environment.IsProduction())
throw;
else
_logger.LogError(apiException.Message);
logger.LogError(apiException.Message);
}
catch (Exception apiException)
{
if (_environment.IsProduction())
if (environment.IsProduction())
throw;
else
_logger.LogError(apiException.Message);
logger.LogError(apiException.Message);
}
}
@ -57,18 +49,18 @@ public class SmsService : ISmsService
{
try
{
var rest = await _restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber,template,token,token2,token3,token10,token20);
var rest = await restApiWrapper.KaveNegarRestApi.SendLookUp(_siteSettings.KaveNegarApiKey, phoneNumber,template,token,token2,token3,token10,token20);
if (rest.Return.status != 200)
throw new BaseApiException(ApiResultStatusCode.SendSmsError, rest.Return.message);
}
catch (ApiException apiException)
{
_logger.LogError(apiException.Message);
logger.LogError(apiException.Message);
}
catch (Exception apiException)
{
_logger.LogError(apiException.Message);
logger.LogError(apiException.Message);
}
}

View File

@ -1,24 +1,14 @@
using Netina.Common.Extensions;
using Netina.Core.Abstracts;
using Netina.Domain.Dtos.SmallDtos;
using Netina.Domain.Dtos.SmallDtos;
using Netina.Domain.Enums;
using Netina.Domain.Models.Settings;
namespace Netina.Infrastructure.Services;
public class StorageService : IStorageService
public class StorageService(IOptionsSnapshot<SiteSettings> snapshot) : IStorageService
{
private IAmazonS3? _s3Client;
private readonly string _bucketName;
private readonly string _accessKey;
private readonly string _secretKey;
public StorageService(IOptionsSnapshot<SiteSettings> snapshot)
{
_accessKey = snapshot.Value.StorageSetting.AccessKey;
_bucketName = snapshot.Value.StorageSetting.BucketKey;
_secretKey = snapshot.Value.StorageSetting.SecretKey;
}
private readonly string _bucketName = snapshot.Value.StorageSetting.BucketKey;
private readonly string _accessKey = snapshot.Value.StorageSetting.AccessKey;
private readonly string _secretKey = snapshot.Value.StorageSetting.SecretKey;
private IAmazonS3 GetClientAsync()
{

View File

@ -1,21 +1,12 @@
using Netina.Common.Extensions;
using Netina.Common.Models.Api;
using Netina.Core.Abstracts;
using Netina.Core.Utilities;
using Netina.Core.Utilities;
namespace Netina.Infrastructure.Services;
public class UploadFileService : IUploadFileService
public class UploadFileService(IStorageService storageService, IOptionsSnapshot<SiteSettings> optionsSnapshot)
: IUploadFileService
{
private readonly IStorageService _storageService;
private readonly SiteSettings _siteSetting;
private readonly SiteSettings _siteSetting = optionsSnapshot.Value;
public UploadFileService(IStorageService storageService,IOptionsSnapshot<SiteSettings> optionsSnapshot)
{
_storageService = storageService;
_siteSetting = optionsSnapshot.Value;
}
public async Task<FileUploadResponse> UploadImageAsync(FileUploadRequest uploadRequest)
{
var bytes = Convert.FromBase64String(uploadRequest.StringBaseFile);
@ -30,13 +21,13 @@ public class UploadFileService : IUploadFileService
if (uploadRequest.FileUploadType == FileUploadType.Logo)
{
uploadRequest.FileName = $"Main.{uploadRequest.FileName.Split('.').Last()}";
medFileName = await _storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Med", uploadRequest.ContentType, mediumFileStream,false);
await _storageService.UploadObjectFromFileAsync(medFileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Thumb", uploadRequest.ContentType, thumbnailFileStream, false);
medFileName = await storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Med", uploadRequest.ContentType, mediumFileStream,false);
await storageService.UploadObjectFromFileAsync(medFileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Thumb", uploadRequest.ContentType, thumbnailFileStream, false);
}
else
{
medFileName = await _storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Med", uploadRequest.ContentType, mediumFileStream);
await _storageService.UploadObjectFromFileAsync(medFileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Thumb", uploadRequest.ContentType, thumbnailFileStream, false);
medFileName = await storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Med", uploadRequest.ContentType, mediumFileStream);
await storageService.UploadObjectFromFileAsync(medFileName, $"{uploadRequest.FileUploadType.ToDisplay()}/Thumb", uploadRequest.ContentType, thumbnailFileStream, false);
}
var response = new FileUploadResponse
@ -51,7 +42,7 @@ public class UploadFileService : IUploadFileService
public async Task<FileUploadResponse> UploadFileByteAsync(FileUploadRequest uploadRequest)
{
var medFileName = await _storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}", uploadRequest.ContentType, uploadRequest.FileBytes,false);
var medFileName = await storageService.UploadObjectFromFileAsync(uploadRequest.FileName, $"{uploadRequest.FileUploadType.ToDisplay()}", uploadRequest.ContentType, uploadRequest.FileBytes,false);
var response = new FileUploadResponse
{
FileName = medFileName,

View File

@ -1,35 +1,26 @@
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Netina.Common.Models.Exception;
using Netina.Core.Abstracts;
using Netina.Core.BaseServices.Abstracts;
using Netina.Domain.CommandQueries.Commands;
using Netina.Domain.CommandQueries.Queries;
using Netina.Domain.Enums;
using Netina.Domain.MartenEntities.Settings;
using Netina.Domain.Models.Settings;
using Netina.Infrastructure.Models.RestApi.Zarinpal;
using Netina.Infrastructure.RestServices;
using Newtonsoft.Json;
namespace Netina.Infrastructure.Services;
public class ZarinpalService : IPaymentService
public class ZarinpalService(
IRestApiWrapper restApiWrapper,
IOptionsSnapshot<SiteSettings> snapshot,
IMediator mediator,
ISettingService settingService)
: IPaymentService
{
private readonly IRestApiWrapper _restApiWrapper;
private readonly IMediator _mediator;
private readonly ISettingService _settingService;
private readonly SiteSettings _siteSettings;
public ZarinpalService(IRestApiWrapper restApiWrapper, IOptionsSnapshot<SiteSettings> snapshot, IMediator mediator , ISettingService settingService)
{
_restApiWrapper = restApiWrapper;
_mediator = mediator;
_settingService = settingService;
_siteSettings = snapshot.Value;
}
private readonly SiteSettings _siteSettings = snapshot.Value;
public async Task<string> GetPaymentLinkAsync(double amount, string factorNumber, Guid orderId, Guid userId, string phoneNumber, string fullName, CancellationToken cancellationToken = default)
{
var paymentSetting = (await _settingService.GetSettingAsync("PaymentSetting", cancellationToken)) as PaymentSetting;
var paymentSetting = (await settingService.GetSettingAsync("PaymentSetting", cancellationToken)) as PaymentSetting;
if (paymentSetting == null)
throw new AppException("تنظیمات پرداخت انجام نشده است");
if (paymentSetting.ZarinPalApiKey.IsNullOrEmpty())
@ -43,13 +34,13 @@ public class ZarinpalService : IPaymentService
merchant_id = paymentSetting.ZarinPalApiKey,
metadata = new ZarinaplPaymentLinkRequestMetadata { mobile = phoneNumber }
};
var responseJson = await _restApiWrapper.ZarinpalRestApi.GetPaymentLinkAsync(request);
var responseJson = await restApiWrapper.ZarinpalRestApi.GetPaymentLinkAsync(request);
var response = JsonConvert.DeserializeObject<ZarinaplPaymentLinkResponse>(responseJson);
if (response.data.code != 100)
throw new AppException($"Exception in get link from zarinpal | {response.data.message}");
var createPaymentResult = await _mediator.Send(new CreateOrUpdatePaymentCommand(null, factorNumber, amount,
var createPaymentResult = await mediator.Send(new CreateOrUpdatePaymentCommand(null, factorNumber, amount,
request.description, string.Empty, string.Empty,
response.data.authority, PaymentType.Online, PaymentStatus.InPaymentGateway, orderId, userId), cancellationToken);
@ -59,20 +50,20 @@ public class ZarinpalService : IPaymentService
public async Task<Tuple<string, string>> VerifyPaymentAsync(string authority, CancellationToken cancellationToken = default)
{
var paymentSetting = (await _settingService.GetSettingAsync("PaymentSetting", cancellationToken)) as PaymentSetting;
var paymentSetting = (await settingService.GetSettingAsync("PaymentSetting", cancellationToken)) as PaymentSetting;
if (paymentSetting == null)
throw new AppException("تنظیمات پرداخت انجام نشده است");
if (paymentSetting.ZarinPalApiKey.IsNullOrEmpty())
throw new AppException("کد مرچنت زرین پال وارد نشده است");
var payment = await _mediator.Send(new GetPaymentQuery(Authority: authority), cancellationToken);
var payment = await mediator.Send(new GetPaymentQuery(Authority: authority), cancellationToken);
var request = new ZarinaplVerifyPaymentRequest
{
amount = (int)payment.Amount,
authority = payment.Authority,
merchant_id = paymentSetting.ZarinPalApiKey
};
var response = await _restApiWrapper.ZarinpalRestApi.VerifyPaymentAsync(request);
var response = await restApiWrapper.ZarinpalRestApi.VerifyPaymentAsync(request);
if (response.data.code != 100)
throw new AppException($"Exception in get link from zarinpal | {response.data.message}");
@ -80,11 +71,11 @@ public class ZarinpalService : IPaymentService
payment.CardPan = response.data.card_pan;
payment.TransactionCode = response.data.ref_id.ToString();
await _mediator.Send(new CreateOrUpdatePaymentCommand(payment.Id, payment.FactorNumber, payment.Amount, payment.Description,
await mediator.Send(new CreateOrUpdatePaymentCommand(payment.Id, payment.FactorNumber, payment.Amount, payment.Description,
payment.TransactionCode, payment.CardPan, payment.Authority, payment.Type, payment.Status,
payment.OrderId, payment.CustomerId), cancellationToken);
await _mediator.Send(new SubmitOrderPaymentCommand(payment.OrderId, OrderPaymentMethod.OnlinePayment, true),
await mediator.Send(new SubmitOrderPaymentCommand(payment.OrderId, OrderPaymentMethod.OnlinePayment, true),
cancellationToken);
return new Tuple<string, string>(payment.TransactionCode, payment.FactorNumber);

View File

@ -3,19 +3,15 @@ using ValidationException = Netina.Common.Models.Exception.ValidationException;
namespace Netina.Repository.Behaviors;
public class ValidationBehavior <TRequest,TResponse> : IPipelineBehavior<TRequest,TResponse> where TRequest : notnull
public class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
var context = new ValidationContext<TRequest>(request);
List<ValidationError> errors = new List<ValidationError>();
foreach (IValidator<TRequest> validator in _validators)
foreach (IValidator<TRequest> validator in validators)
{
var result = await validator.ValidateAsync(context, cancellationToken);
if (!result.IsValid)

View File

@ -1,14 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Netina.Repository.Extensions;
public class DbContextOptionCustomExtensionsInfo : DbContextOptionsExtensionInfo
public class DbContextOptionCustomExtensionsInfo(IDbContextOptionsExtension extension)
: DbContextOptionsExtensionInfo(extension)
{
public DbContextOptionCustomExtensionsInfo(IDbContextOptionsExtension extension) : base(extension)
{
}
public override bool IsDatabaseProvider { get; }
public override string LogFragment { get; } = string.Empty;

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Extensions;
namespace Netina.Repository.Extensions;
public class ModelBuilderQueryFilter
{

View File

@ -1,21 +1,15 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Accounting;
using Netina.Domain.Entities.Accounting;
namespace Netina.Repository.Handlers.Accounting;
public class CreateOrUpdatePaymentCommandHandler : IRequestHandler<CreateOrUpdatePaymentCommand, bool>
public class CreateOrUpdatePaymentCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateOrUpdatePaymentCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateOrUpdatePaymentCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(CreateOrUpdatePaymentCommand request, CancellationToken cancellationToken)
{
if (request.Id != null)
{
var ent = await _repositoryWrapper.SetRepository<Payment>()
var ent = await repositoryWrapper.SetRepository<Payment>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == request.Id, cancellationToken);
if (ent == null)
@ -27,14 +21,14 @@ public class CreateOrUpdatePaymentCommandHandler : IRequestHandler<CreateOrUpdat
newEnt.CreatedAt = ent.CreatedAt == DateTime.MinValue ? DateTime.Now : ent.CreatedAt;
newEnt.CreatedBy = ent.CreatedBy;
_repositoryWrapper.SetRepository<Payment>()
repositoryWrapper.SetRepository<Payment>()
.Update(newEnt);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
else
{
var orderPayment = await _repositoryWrapper.SetRepository<Payment>()
var orderPayment = await repositoryWrapper.SetRepository<Payment>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.OrderId == request.OrderId && p.Type == request.Type,cancellationToken);
if (orderPayment != null)
@ -45,20 +39,20 @@ public class CreateOrUpdatePaymentCommandHandler : IRequestHandler<CreateOrUpdat
newEnt.CreatedAt = orderPayment.CreatedAt == DateTime.MinValue ? DateTime.Now : orderPayment.CreatedAt;
newEnt.CreatedBy = orderPayment.CreatedBy;
_repositoryWrapper.SetRepository<Payment>()
repositoryWrapper.SetRepository<Payment>()
.Update(newEnt);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
else
{
var payment = Payment.Create(request.FactorNumber, request.Amount, request.Description, request.TransactionCode,
request.CardPan, request.Authority, request.Type, request.Status, request.OrderId, request.UserId);
_repositoryWrapper.SetRepository<Payment>()
repositoryWrapper.SetRepository<Payment>()
.Add(payment);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
}
return true;

View File

@ -1,22 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Accounting;
using Netina.Domain.Entities.Accounting;
namespace Netina.Repository.Handlers.Accounting;
public class GetPaymentQueryHandler : IRequestHandler<GetPaymentQuery,PaymentSDto>
public class GetPaymentQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetPaymentQuery, PaymentSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetPaymentQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<PaymentSDto> Handle(GetPaymentQuery request, CancellationToken cancellationToken)
{
PaymentSDto? payment = null;
if (request.Authority != null)
{
payment = await _repositoryWrapper.SetRepository<Payment>()
payment = await repositoryWrapper.SetRepository<Payment>()
.TableNoTracking
.Where(p => p.Authority == request.Authority)
.Select(PaymentMapper.ProjectToSDto)
@ -27,7 +21,7 @@ public class GetPaymentQueryHandler : IRequestHandler<GetPaymentQuery,PaymentSDt
if (request.Id == default)
throw new Exception("Id is null");
payment = await _repositoryWrapper.SetRepository<Payment>()
payment = await repositoryWrapper.SetRepository<Payment>()
.TableNoTracking
.Where(p => p.Id == request.Id)
.Select(PaymentMapper.ProjectToSDto)

View File

@ -1,19 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Accounting;
using Netina.Domain.Entities.Accounting;
namespace Netina.Repository.Handlers.Accounting;
public class GetPaymentsQueryHandler : IRequestHandler<GetPaymentsQuery,List<PaymentSDto>>
public class GetPaymentsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetPaymentsQuery, List<PaymentSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetPaymentsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<PaymentSDto>> Handle(GetPaymentsQuery request, CancellationToken cancellationToken)
{
return await _repositoryWrapper.SetRepository<Payment>()
return await repositoryWrapper.SetRepository<Payment>()
.TableNoTracking
.OrderByDescending(o=>o.CreatedAt)
.Skip(20 * request.Page)

View File

@ -1,20 +1,13 @@
namespace Netina.Repository.Handlers.Addresses;
public class CreateAddressCommandHandler : IRequestHandler<CreateAddressCommand,bool>
public class CreateAddressCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<CreateAddressCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateAddressCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<bool> Handle(CreateAddressCommand request, CancellationToken cancellationToken)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("User id wrong", ApiResultStatusCode.BadRequest);
@ -22,8 +15,8 @@ public class CreateAddressCommandHandler : IRequestHandler<CreateAddressCommand,
request.ReceiverPhoneNumber, request.LocationLat, request.LocationLong, request.Province, request.City,
request.Plaque, request.BuildingUnit, userId);
_repositoryWrapper.SetRepository<UserAddress>().Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<UserAddress>().Add(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return false;
}
}

View File

@ -1,25 +1,18 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Addresses;
namespace Netina.Repository.Handlers.Addresses;
public class DeleteAddressCommandHandler : IRequestHandler<DeleteAddressCommand,bool>
public class DeleteAddressCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteAddressCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteAddressCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteAddressCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<UserAddress>()
var ent = await repositoryWrapper.SetRepository<UserAddress>()
.TableNoTracking
.FirstOrDefaultAsync(u => u.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Address not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<UserAddress>()
repositoryWrapper.SetRepository<UserAddress>()
.Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,17 +1,8 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Addresses;
namespace Netina.Repository.Handlers.Addresses;
public class GetUserAddressesQueryHandler : IRequestHandler<GetUserAddressesQuery, List<UserAddressSDto>>
public class GetUserAddressesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<GetUserAddressesQuery, List<UserAddressSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public GetUserAddressesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
{
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<List<UserAddressSDto>> Handle(GetUserAddressesQuery request, CancellationToken cancellationToken)
{
Guid userId;
@ -19,13 +10,13 @@ public class GetUserAddressesQueryHandler : IRequestHandler<GetUserAddressesQuer
userId = request.UserId.Value;
else
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
if (!Guid.TryParse(_currentUserService.UserId, out userId))
if (!Guid.TryParse(currentUserService.UserId, out userId))
throw new AppException("User id wrong", ApiResultStatusCode.BadRequest);
}
return await _repositoryWrapper.SetRepository<UserAddress>()
return await repositoryWrapper.SetRepository<UserAddress>()
.TableNoTracking
.Where(ua => ua.UserId == userId)
.Select(UserAddressMapper.ProjectToSDto)

View File

@ -1,23 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Blogs;
using Netina.Domain.Entities.Blogs;
namespace Netina.Repository.Handlers.Blogs;
public class GetBlogsQueryHandler : IRequestHandler<GetBlogsQuery,GetBlogsResponseDto>
public class GetBlogsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetBlogsQuery, GetBlogsResponseDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetBlogsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<GetBlogsResponseDto> Handle (GetBlogsQuery request, CancellationToken cancellationToken)
{
var response = new GetBlogsResponseDto();
int count = 20;
if (request.Count != null)
count = request.Count.Value;
var query = _repositoryWrapper.SetRepository<Blog>().TableNoTracking;
var query = repositoryWrapper.SetRepository<Blog>().TableNoTracking;
if (request.CategoryId != null)
query = query.Where(b => b.CategoryId == request.CategoryId);
if (request.BlogName != null)

View File

@ -1,24 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Brands;
using Netina.Domain.Entities.Brands;
namespace Netina.Repository.Handlers.Brands;
public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand,bool>
public class DeleteBrandCommandHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<DeleteBrandCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteBrandCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Brand>().TableNoTracking
var ent = await repositoryWrapper.SetRepository<Brand>().TableNoTracking
.FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Brand not found");
_repositoryWrapper.SetRepository<Brand>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Brand>().Delete(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}

View File

@ -1,18 +1,12 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Brands;
using Netina.Domain.Entities.Brands;
namespace Netina.Repository.Handlers.Brands;
public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandSDto>>
public class GetBrandsQueryHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
: IRequestHandler<GetBrandsQuery, List<BrandSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMediator _mediator;
private readonly IMediator _mediator = mediator;
public GetBrandsQueryHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
{
_repositoryWrapper = repositoryWrapper;
_mediator = mediator;
}
public async Task<List<BrandSDto>> Handle(GetBrandsQuery request, CancellationToken cancellationToken)
{
IQueryable<Brand> baseBrands;
@ -21,7 +15,7 @@ public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandS
{
//var products = await _mediator.Send(new GetProductsQuery(BrandIds: null,SpecialOffer: null, Page:0, SortBy: QuerySortBy.None,CategoryId: request.CategoryId, IsActive : null),
// cancellationToken);
var brandGrouped = await _repositoryWrapper.SetRepository<Product>()
var brandGrouped = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.Where(p => p.CategoryId == request.CategoryId)
.GroupBy(p=>p.BrandId)
@ -30,7 +24,7 @@ public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandS
{
if (grouping.Key != default)
{
var brand = await _repositoryWrapper.SetRepository<Brand>()
var brand = await repositoryWrapper.SetRepository<Brand>()
.TableNoTracking
.Where(b => b.Id == grouping.Key)
.Select(BrandMapper.ProjectToSDto)
@ -45,7 +39,7 @@ public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandS
if (request.BrandName != null)
{
baseBrands = _repositoryWrapper.SetRepository<Brand>()
baseBrands = repositoryWrapper.SetRepository<Brand>()
.TableNoTracking
.Where(b => b.PersianName.Trim().Contains(request.BrandName.Trim()))
.OrderByDescending(b => b.CreatedAt);
@ -53,7 +47,7 @@ public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandS
else
{
baseBrands = _repositoryWrapper.SetRepository<Brand>().TableNoTracking
baseBrands = repositoryWrapper.SetRepository<Brand>().TableNoTracking
.OrderByDescending(b => b.CreatedAt);
}

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
namespace Netina.Repository.Handlers.Discounts;
public class CreateDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateDiscountCommand, DiscountLDto>

View File

@ -1,24 +1,17 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
namespace Netina.Repository.Handlers.Discounts;
public class DeleteDiscountCommandHandler : IRequestHandler<DeleteDiscountCommand,bool>
public class DeleteDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteDiscountCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteDiscountCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Discount>().TableNoTracking
var ent = await repositoryWrapper.SetRepository<Discount>().TableNoTracking
.FirstOrDefaultAsync(d => d.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Discount NotFound", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Discount>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Discount>().Delete(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,18 +1,11 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
namespace Netina.Repository.Handlers.Discounts;
public class GetDiscountQueryHandler : IRequestHandler<GetDiscountQuery, DiscountLDto>
public class GetDiscountQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetDiscountQuery, DiscountLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetDiscountQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<DiscountLDto> Handle(GetDiscountQuery request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Discount>().TableNoTracking
var ent = await repositoryWrapper.SetRepository<Discount>().TableNoTracking
.Where(b => b.Id == request.Id)
.Select(DiscountMapper.ProjectToLDto)
.FirstOrDefaultAsync(cancellationToken);

View File

@ -1,18 +1,11 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
namespace Netina.Repository.Handlers.Discounts;
public class GetDiscountsQueryHandler : IRequestHandler<GetDiscountsQuery, List<DiscountSDto>>
public class GetDiscountsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetDiscountsQuery, List<DiscountSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetDiscountsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<DiscountSDto>> Handle(GetDiscountsQuery request, CancellationToken cancellationToken)
{
var discounts = await _repositoryWrapper.SetRepository<Discount>().TableNoTracking
var discounts = await repositoryWrapper.SetRepository<Discount>().TableNoTracking
.Where(d=>!d.IsSpecialOffer)
.OrderByDescending(b => b.CreatedAt)
.Skip(request.Page * 15).Take(15)

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
namespace Netina.Repository.Handlers.Discounts;
public class UpdateDiscountCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<UpdateDiscountCommand, bool>

View File

@ -1,18 +1,11 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Marketers;
namespace Netina.Repository.Handlers.Marketers;
public class GetMarketersQueryHandler : IRequestHandler<GetMarketersQuery,List<MarketerSDto>>
public class GetMarketersQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetMarketersQuery, List<MarketerSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetMarketersQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<MarketerSDto>> Handle(GetMarketersQuery request, CancellationToken cancellationToken)
{
var query = _repositoryWrapper.SetRepository<Marketer>()
var query = repositoryWrapper.SetRepository<Marketer>()
.TableNoTracking;
return await query.OrderByDescending(q => q.CreatedAt)

View File

@ -1,23 +1,15 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
namespace Netina.Repository.Handlers.Newsletters;
namespace Netina.Repository.Handlers.Newsletters;
public class CreateNewsletterMemberCommandHandler : IRequestHandler<CreateNewsletterMemberCommand,bool>
public class CreateNewsletterMemberCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateNewsletterMemberCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateNewsletterMemberCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(CreateNewsletterMemberCommand request, CancellationToken cancellationToken)
{
if (request.PhoneNumber.IsNullOrEmpty() && request.Email.IsNullOrEmpty())
throw new AppException("PhoneNumber and Email is null");
if (!request.PhoneNumber.IsNullOrEmpty())
{
var existedPhoneNumber = await _repositoryWrapper.SetRepository<NewsletterMember>()
var existedPhoneNumber = await repositoryWrapper.SetRepository<NewsletterMember>()
.TableNoTracking
.AnyAsync(c => c.PhoneNumber == request.PhoneNumber, cancellationToken);
if (existedPhoneNumber == true)
@ -25,7 +17,7 @@ public class CreateNewsletterMemberCommandHandler : IRequestHandler<CreateNewsle
}
if (!request.Email.IsNullOrEmpty())
{
var existedEmail = await _repositoryWrapper.SetRepository<NewsletterMember>()
var existedEmail = await repositoryWrapper.SetRepository<NewsletterMember>()
.TableNoTracking
.AnyAsync(c => c.Email == request.Email, cancellationToken);
if (existedEmail == true)
@ -33,9 +25,9 @@ public class CreateNewsletterMemberCommandHandler : IRequestHandler<CreateNewsle
}
var ent = NewsletterMember.Create(request.PhoneNumber, request.Email);
_repositoryWrapper.SetRepository<NewsletterMember>()
repositoryWrapper.SetRepository<NewsletterMember>()
.Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,18 +1,11 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Newsletters;
namespace Netina.Repository.Handlers.Newsletters;
public class GetNewsletterMembersQueryHandler : IRequestHandler<GetNewsletterMembersQuery,List<NewsletterMemberSDto>>
public class GetNewsletterMembersQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetNewsletterMembersQuery, List<NewsletterMemberSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetNewsletterMembersQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<NewsletterMemberSDto>> Handle(GetNewsletterMembersQuery request, CancellationToken cancellationToken)
{
var dtos = await _repositoryWrapper.SetRepository<NewsletterMember>()
var dtos = await repositoryWrapper.SetRepository<NewsletterMember>()
.TableNoTracking
.OrderByDescending(n => n.CreatedAt)
.Select(NewsletterMemberMapper.ProjectToSDto)

View File

@ -1,5 +1,4 @@
using FluentValidation;
using Microsoft.IdentityModel.Tokens;
namespace Netina.Repository.Handlers.Newsletters.Validators;

View File

@ -1,21 +1,15 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class CreateBaseOrderCommandHandler : IRequestHandler<CreateBaseOrderCommand,Order>
public class CreateBaseOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateBaseOrderCommand, Order>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateBaseOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<Order> Handle(CreateBaseOrderCommand request, CancellationToken cancellationToken)
{
if (request.UserId == default)
throw new AppException("Customer id is null");
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == request.UserId, cancellationToken);
if (customer == null)
@ -24,16 +18,16 @@ public class CreateBaseOrderCommandHandler : IRequestHandler<CreateBaseOrderComm
{
UserId = request.UserId
};
_repositoryWrapper.SetRepository<Customer>()
repositoryWrapper.SetRepository<Customer>()
.Add(customer);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
var order = Order.Create(customer.Id);
_repositoryWrapper.SetRepository<Order>()
repositoryWrapper.SetRepository<Order>()
.Add(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return order;
}

View File

@ -1,25 +1,18 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand,bool>
public class DeleteOrderCommandHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<DeleteOrderCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)
{
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order == null)
throw new AppException("Order not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Order>().Delete(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Order>().Delete(order);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,21 +1,15 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class GetOrderLDtoQueryHandler: IRequestHandler<GetOrderLDtoQuery,OrderLDto>
public class GetOrderLDtoQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetOrderLDtoQuery, OrderLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetOrderLDtoQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<OrderLDto> Handle(GetOrderLDtoQuery request, CancellationToken cancellationToken)
{
if (request.Id == default)
throw new AppException("Order id is null");
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.Id == request.Id)
.Select(OrderMapper.ProjectToLDto)

View File

@ -1,33 +1,26 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, Order>
public class GetOrderQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<GetOrderQuery, Order>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetOrderQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<Order> Handle(GetOrderQuery request, CancellationToken cancellationToken)
{
var order = await _repositoryWrapper.SetRepository<Order>()
var order = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.FirstOrDefaultAsync(o => o.Id == request.Id, cancellationToken);
if (order == null)
throw new AppException("Order not found", ApiResultStatusCode.NotFound);
var orderProducts = await _repositoryWrapper.SetRepository<OrderProduct>()
var orderProducts = await repositoryWrapper.SetRepository<OrderProduct>()
.TableNoTracking
.Where(op => op.OrderId == order.Id)
.ToListAsync(cancellationToken);
orderProducts.ForEach(op => order.AddOrderProduct(op));
var orderDelivery= await _repositoryWrapper.SetRepository<OrderDelivery>()
var orderDelivery= await repositoryWrapper.SetRepository<OrderDelivery>()
.TableNoTracking
.FirstOrDefaultAsync(od => od.OrderId == request.Id, cancellationToken);
if (orderDelivery != null)

View File

@ -1,20 +1,14 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class GetOrdersQueryHandler : IRequestHandler<GetOrdersQuery,List<OrderSDto>>
public class GetOrdersQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetOrdersQuery, List<OrderSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetOrdersQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<OrderSDto>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
{
IQueryable<Order> orders = _repositoryWrapper
IQueryable<Order> orders = repositoryWrapper
.SetRepository<Order>()
.TableNoTracking;

View File

@ -1,28 +1,20 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Orders;
namespace Netina.Repository.Handlers.Orders;
public class GetUserOrdersQueryHandler : IRequestHandler<GetUserOrdersQuery, List<OrderSDto>>
public class GetUserOrdersQueryHandler(ICurrentUserService currentUserService, IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetUserOrdersQuery, List<OrderSDto>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
public GetUserOrdersQueryHandler(ICurrentUserService currentUserService,IRepositoryWrapper repositoryWrapper)
{
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<OrderSDto>> Handle(GetUserOrdersQuery request, CancellationToken cancellationToken)
{
Guid customerId = Guid.Empty;
if (request.CustomerId == default)
{
if (_currentUserService.UserId == null)
if (currentUserService.UserId == null)
throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
var customer = await _repositoryWrapper.SetRepository<Customer>()
var customer = await repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (customer == null)
@ -32,7 +24,7 @@ public class GetUserOrdersQueryHandler : IRequestHandler<GetUserOrdersQuery, Lis
else
customerId = request.CustomerId;
var orders = await _repositoryWrapper.SetRepository<Order>()
var orders = await repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.CustomerId == customerId)
.Select(OrderMapper.ProjectToSDto)

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.ProductCategories;
namespace Netina.Repository.Handlers.ProductCategories;
public class GetProductCategoriesQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetProductCategoriesQuery, List<ProductCategorySDto>>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.ProductCategories;
namespace Netina.Repository.Handlers.ProductCategories;
public class GetProductCategoryChildrenQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetProductCategoryChildrenQuery, List<Guid>>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.ProductCategories;
namespace Netina.Repository.Handlers.ProductCategories;
public class GetProductCategoryQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetProductCategoryQuery, ProductCategoryLDto>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Products;
namespace Netina.Repository.Handlers.Products;
public class ChangeProductCostCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<ChangeProductCostCommand, bool>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Products;
namespace Netina.Repository.Handlers.Products;
public class ChangeProductDisplayedCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<ChangeProductDisplayedCommand, bool>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Products;
namespace Netina.Repository.Handlers.Products;
public class DeleteProductCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteProductCommand, bool>

View File

@ -1,6 +1,4 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Products;
namespace Netina.Repository.Handlers.Products;
public class GetProductsQueryHandler(
IRepositoryWrapper repositoryWrapper,

View File

@ -1,21 +1,15 @@
using Microsoft.EntityFrameworkCore;
using AppException = Netina.Common.Models.Exception.AppException;
using AppException = Netina.Common.Models.Exception.AppException;
namespace Netina.Repository.Handlers.Reviews;
public class CreateReviewCommandHandler : IRequestHandler<CreateReviewCommand,ReviewSDto>
public class CreateReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateReviewCommand, ReviewSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ReviewSDto> Handle(CreateReviewCommand request, CancellationToken cancellationToken)
{
var review = Review.Create(request.Title, request.Comment, request.Rate, request.IsBuyer, request.ProductId,
request.UserId);
var product = await _repositoryWrapper.SetRepository<Product>()
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);
if (product == null)
@ -23,11 +17,11 @@ public class CreateReviewCommandHandler : IRequestHandler<CreateReviewCommand,Re
product.AddRate(request.Rate);
_repositoryWrapper.SetRepository<Product>().Update(product);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Product>().Update(product);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
_repositoryWrapper.SetRepository<Review>().Add(review);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Review>().Add(review);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return review.AdaptToSDto();
}

View File

@ -1,24 +1,17 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Reviews;
namespace Netina.Repository.Handlers.Reviews;
public class DeleteReviewCommandHandler : IRequestHandler<DeleteReviewCommand,bool>
public class DeleteReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteReviewCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteReviewCommand request, CancellationToken cancellationToken)
{
var review = await _repositoryWrapper.SetRepository<Review>().TableNoTracking
var review = await repositoryWrapper.SetRepository<Review>().TableNoTracking
.FirstOrDefaultAsync(r => r.Id == request.Id, cancellationToken);
if (review == null)
throw new AppException("Review not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Review>().Delete(review);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Review>().Delete(review);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,18 +1,10 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Reviews;
namespace Netina.Repository.Handlers.Reviews;
public class GetReviewQueryHandler : IRequestHandler<GetReviewQuery,ReviewLDto>
public class GetReviewQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<GetReviewQuery, ReviewLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetReviewQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ReviewLDto> Handle(GetReviewQuery request, CancellationToken cancellationToken)
{
var review = await _repositoryWrapper.SetRepository<Review>()
var review = await repositoryWrapper.SetRepository<Review>()
.TableNoTracking
.Where(r => r.Id == request.Id)
.Select(ReviewMapper.ProjectToLDto)

View File

@ -1,18 +1,11 @@
using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Reviews;
namespace Netina.Repository.Handlers.Reviews;
public class GetReviewsQueryHandler : IRequestHandler<GetReviewsQuery,List<ReviewSDto>>
public class GetReviewsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetReviewsQuery, List<ReviewSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetReviewsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<ReviewSDto>> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
{
return await _repositoryWrapper.SetRepository<Review>()
return await repositoryWrapper.SetRepository<Review>()
.TableNoTracking
.OrderByDescending(r => r.CreatedAt)
.Skip(request.Page * 15)

View File

@ -2,20 +2,15 @@
namespace Netina.Repository.Handlers.Warehouses;
public class CreateShippingCommandHandler : IRequestHandler<CreateShippingCommand , ShippingSDto>
public class CreateShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<CreateShippingCommand, ShippingSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ShippingSDto> Handle(CreateShippingCommand request, CancellationToken cancellationToken)
{
var ent = Shipping.Create(request.Name, request.WarehouseName, request.IsExpressShipping, request.IsShipBySeller,
request.IsOriginalWarehouse,request.DeliveryCost,request.WorkingDays);
_repositoryWrapper.SetRepository<Shipping>().Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Shipping>().Add(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return ent.AdaptToSDto();
}
}

View File

@ -1,25 +1,19 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Warehouses;
using Netina.Domain.Entities.Warehouses;
namespace Netina.Repository.Handlers.Warehouses;
public class DeleteShippingCommandHandler : IRequestHandler<DeleteShippingCommand, bool>
public class DeleteShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteShippingCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteShippingCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Shipping>().TableNoTracking
var ent = await repositoryWrapper.SetRepository<Shipping>().TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Shipping not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Shipping>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Shipping>().Delete(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,19 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Warehouses;
using Netina.Domain.Entities.Warehouses;
namespace Netina.Repository.Handlers.Warehouses;
public class GetShippingQueryHandler : IRequestHandler<GetShippingQuery, ShippingSDto>
public class GetShippingQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetShippingQuery, ShippingSDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetShippingQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ShippingSDto> Handle(GetShippingQuery request, CancellationToken cancellationToken)
{
var shippingMethod = await _repositoryWrapper.SetRepository<Shipping>().TableNoTracking.Where(b => b.Id == request.Id)
var shippingMethod = await repositoryWrapper.SetRepository<Shipping>().TableNoTracking.Where(b => b.Id == request.Id)
.Select(ShippingMapper.ProjectToSDto)
.FirstOrDefaultAsync(cancellationToken);
if (shippingMethod == null)

View File

@ -1,19 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Warehouses;
using Netina.Domain.Entities.Warehouses;
namespace Netina.Repository.Handlers.Warehouses;
public class GetShippingsQueryHandler : IRequestHandler<GetShippingsQuery,List<ShippingSDto>>
public class GetShippingsQueryHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<GetShippingsQuery, List<ShippingSDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetShippingsQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<ShippingSDto>> Handle(GetShippingsQuery request, CancellationToken cancellationToken)
{
return await _repositoryWrapper
return await repositoryWrapper
.SetRepository<Shipping>()
.TableNoTracking.OrderByDescending(b => b.CreatedAt)
.Skip(request.Page * 20)

View File

@ -1,19 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Warehouses;
using Netina.Domain.Entities.Warehouses;
namespace Netina.Repository.Handlers.Warehouses;
public class UpdateShippingCommandHandler : IRequestHandler<UpdateShippingCommand, bool>
public class UpdateShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<UpdateShippingCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public UpdateShippingCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(UpdateShippingCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Shipping>().TableNoTracking
var ent = await repositoryWrapper.SetRepository<Shipping>().TableNoTracking
.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Shipping not found", ApiResultStatusCode.NotFound);
@ -23,8 +17,8 @@ public class UpdateShippingCommandHandler : IRequestHandler<UpdateShippingComman
newEnt.Id = ent.Id;
newEnt.CreatedAt = ent.CreatedAt;
newEnt.CreatedBy = ent.CreatedBy;
_repositoryWrapper.SetRepository<Shipping>().Update(newEnt);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
repositoryWrapper.SetRepository<Shipping>().Update(newEnt);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,20 +1,12 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Reflection.Emit;
namespace Netina.Repository.Models;
public class ApplicationContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
public class ApplicationContext(DbContextOptions<ApplicationContext> options, ILogger<ApplicationContext> logger)
: IdentityDbContext<ApplicationUser, ApplicationRole, Guid>(options)
{
private readonly ILogger<ApplicationContext> _logger;
private readonly Assembly _projectAssembly;
public ApplicationContext(DbContextOptions<ApplicationContext> options, ILogger<ApplicationContext> logger) : base(options)
{
_logger = logger;
_projectAssembly = options.GetExtension<DbContextOptionCustomExtensions>().ProjectAssembly;
}
private readonly Assembly _projectAssembly = options.GetExtension<DbContextOptionCustomExtensions>().ProjectAssembly;
protected override void OnModelCreating(ModelBuilder builder)
{
@ -22,9 +14,9 @@ public class ApplicationContext : IdentityDbContext<ApplicationUser, Application
stopwatch.Start();
base.OnModelCreating(builder);
var entitiesAssembly = _projectAssembly;
builder.RegisterAllEntities<ApiEntity>(_logger, entitiesAssembly);
builder.RegisterAllEntities<ApiEntity>(logger, entitiesAssembly);
stopwatch.Stop();
_logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!");
logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!");
builder.HasPostgresExtension("pg_trgm");

Some files were not shown because too many files have changed in this diff Show More