Api/Netina.Repository/Handlers/Discounts/CreateSaleCooperationDiscou...

57 lines
2.6 KiB
C#

using Microsoft.EntityFrameworkCore;
namespace Netina.Repository.Handlers.Discounts;
public class CreateSaleCooperationDiscountHandler : IRequestHandler<CreateSaleCooperationDiscount,string>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly ICurrentUserService _currentUserService;
public CreateSaleCooperationDiscountHandler(UserManager<ApplicationUser> userManager,IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
{
_userManager = userManager;
_repositoryWrapper = repositoryWrapper;
_currentUserService = currentUserService;
}
public async Task<string> Handle(CreateSaleCooperationDiscount request, CancellationToken cancellationToken)
{
var userId = request.CorporateUserId;
if (userId == default)
{
if (_currentUserService.UserId == null)
throw new AppException("User id is null");
if (!Guid.TryParse(_currentUserService.UserId, out userId))
throw new AppException("User id is wrong");
}
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new AppException("User not found", ApiResultStatusCode.NotFound);
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>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.IsForSaleCooperation && d.MarketerId == marketer.Id, cancellationToken);
if (foundedDiscount == null)
{
var code = StringExtensions.GetId();
foundedDiscount = Discount.Create(code,$"کد مخصوص همکاری در فروش برای کاربر - {user.FirstName} {user.LastName}", 10, 0, true,
DiscountAmountType.Percent, DiscountType.All, 0, true, DateTime.Today, DateTime.Today.AddYears(10), 0,
false, 0, false, true, 0, false, false,false);
foundedDiscount.SetCorporate(marketer.Id);
_repositoryWrapper.SetRepository<Discount>().Add(foundedDiscount);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return foundedDiscount.Code;
}
else
return foundedDiscount.Code;
}
}