Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
2
Indexable
Never
using Ezrx.AccountIdentity.Application.Contract.Repositories;
using Ezrx.AccountIdentity.Common.Constants;
using Ezrx.AccountIdentity.Common.Exceptions;
using Ezrx.AccountIdentity.Common.Extension;
using Ezrx.AccountIdentity.Common.Helpers;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Ezrx.AccountIdentity.Application.Features.Accounts.Commands
{
    public class PinAndLimitCommand : IRequest<Unit>
    {
        public string? Pin { get; set; }

        public decimal? Limit { get; set; }

        public Guid? AccountId { get; set; }

        public string? RequestHeader { get; set; }

        public PinAndLimitCommand(string? pin, decimal? limit)
        {
            Pin = pin;
            Limit = limit;
        }

        public class PinAndLimitCommandHandler : IRequestHandler<PinAndLimitCommand, Unit>
        {
            private readonly IApplicationDbContext _dbContext;

            public PinAndLimitCommandHandler(IApplicationDbContext dbContext)
            {
                _dbContext = dbContext;
            }

            public async Task<Unit> Handle(PinAndLimitCommand request, CancellationToken cancellationToken)
            {
                var account = await _dbContext.Accounts
                                .Where(x => x.Id == request.AccountId)
                                .Where(x => x.IsActive == true)
                                .Include(x => x.AccountPins.Where(x => x.IsActive == true))
                                .Include(x => x.AccountSetting)
                                .AsNoTracking()
                                .FirstOrDefaultAsync();

                if (account == null)
                    throw new BadRequestException(ApplicationConstant.DataNotFoundMessage);

                if (account.AccountSetting != null || (account.AccountPins != null && account.AccountPins.Count > 0))
                    throw new BadRequestException(ApplicationConstant.DataNotFoundMessage);

                var newAccountSetting = new Data.Entities.AccountSetting()
                {
                    AccountId = request.AccountId.Value,
                    Limit = request.Limit.Value
                };

                byte[] generatedSalt = PasswordManagerHelper.GetSalt();
                var newAccountPin = new Data.Entities.AccountPin()
                 {
                    AccountId = request.AccountId.Value,
                    Salt = generatedSalt,
                    Pin = request.Pin.ToSHA256().ToRADHashed(generatedSalt)
                };

                _dbContext.AccountSettings.Add(newAccountSetting);
                _dbContext.AccountPins.Add(newAccountPin);

                await _dbContext.SaveChangesAsync(cancellationToken);

                return Unit.Value;
            }
        }
    }
}