Bladeren bron

Add UserService, UserValidator, UserValidatorTest

Dalibor Votruba 3 jaren geleden
bovenliggende
commit
3b6b159733

+ 8 - 0
Common/qdr.app.qlbrc.common/ExceptionLibrary.cs

@@ -19,6 +19,9 @@ namespace Quadarax.Application.QLiberace.Common
             AddCode(ExceptionsCodes.TenantAlreadyExistsCode, ExceptionsCodes.TenantAlreadyExistsMsg);
             AddCode(ExceptionsCodes.TenantLockedCode, ExceptionsCodes.TenantLockedMsg);
             AddCode(ExceptionsCodes.TenantDifferentContextCode, ExceptionsCodes.TenantDifferentContextMsg);
+
+            AddCode(ExceptionsCodes.UserNotFoundCode, ExceptionsCodes.UserNotFoundMsg);
+            AddCode(ExceptionsCodes.UserAlreadyExistsCode, ExceptionsCodes.UserAlreadyExistsMsg);
         }
 
 
@@ -44,6 +47,11 @@ namespace Quadarax.Application.QLiberace.Common
             public const int TenantLockedCode = 10012;
             public const string TenantDifferentContextMsg = "Cannot update different Tenant with code '{0}' in tenant context '{1}'";
             public const int TenantDifferentContextCode = 10013;
+
+            public const string UserNotFoundMsg = "User with identifier {0}='{1}' not found";
+            public const int UserNotFoundCode = 10020;
+            public const string UserAlreadyExistsMsg = "User with login name '{0}' already exists";
+            public const int UserAlreadyExistsCode = 10021;
             
         }
 

+ 14 - 0
Modules/qdr.app.qlbrc.base/Dtos/Validators/UserValidator.cs

@@ -0,0 +1,14 @@
+using Quadarax.Foundation.Core.Value;
+
+namespace Quadarax.Application.QLiberace.Base.Dtos.Validators
+{
+    public class UserValidator : Validator<UserWDto>
+    {
+        protected override void OnValidate(UserWDto validatingObject, ValidatorContext context)
+        {
+            CheckIfEmpty("LoginName", validatingObject.LoginName, ValidationResult.ValidationSeverityEnum.Error);
+            CheckIfStringMaxLengthOverflow("LoginName", validatingObject.LoginName, 100,
+                ValidationResult.ValidationSeverityEnum.Error);
+        }
+    }
+}

+ 10 - 0
Modules/qdr.app.qlbrc.base/Repositories/RepoUser.cs

@@ -1,4 +1,5 @@
 using Quadarax.Application.QLiberace.Base.Entities;
+using Quadarax.Foundation.Core.Data;
 using Quadarax.Foundation.Core.Data.Domain;
 using Quadarax.Foundation.Core.Data.Interface.Domain;
 using Quadarax.Foundation.Core.Data.Repository;
@@ -10,5 +11,14 @@ namespace Quadarax.Application.QLiberace.Base.Repositories
         public RepoUser(IUnitOfWork<IDataDomain> unitOfWork) : base(unitOfWork)
         {
         }
+
+        public User? GetByLoginName(string loginName, bool includeLocked = false, bool usingUncommited = false)
+        {
+            if (string.IsNullOrEmpty(loginName)) throw new ArgumentNullException(nameof(loginName));
+
+            var query = Query(Paging.NoPaging(), usingUncommited).FirstOrDefault(x =>
+                string.Equals(x.LoginName, loginName, StringComparison.InvariantCultureIgnoreCase) && (x.IsLocked == false || includeLocked == true));
+            return query;
+        }
     }
 }

+ 98 - 0
Modules/qdr.app.qlbrc.base/Services/UserService.cs

@@ -0,0 +1,98 @@
+using Quadarax.Application.QLiberace.Base.Repositories;
+using Quadarax.Foundation.Core.Business;
+using Microsoft.Extensions.Logging;
+using Quadarax.Application.QLiberace.Base.Dtos;
+using Quadarax.Foundation.Core.Data.Interface.Domain;
+using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
+using Quadarax.Application.QLiberace.Common;
+using Quadarax.Application.QLiberace.Base.Dtos.Validators;
+using Quadarax.Application.QLiberace.Base.Entities;
+using Quadarax.Application.QLiberace.Base.Mapper;
+using Quadarax.Foundation.Core.Value;
+
+namespace Quadarax.Application.QLiberace.Base.Services
+{
+    public class UserService: AbstractRepositoryService<RepoUser>
+    {
+        #region *** Constructor ***
+        public UserService(RepoUser repository, IContext currentContext, ILoggerFactory logger) : base(repository, currentContext, logger)
+        {
+        }
+        #endregion
+
+        #region *** Public Operations ***
+
+        public ResultValueDto<UserRDto?> CreateUser(UserWDto user)
+        {
+            if (user == null) throw new ArgumentNullException(nameof(user));
+
+            return TryCatchBlock(() =>
+            {
+                ValidateWDto(user);
+
+                var exists = Repository.GetByLoginName(user.LoginName,true);
+                if (exists != null) throw 
+                    ExceptionFactory.CreateException(ExceptionLibrary.ExceptionsCodes.UserAlreadyExistsCode, user.LoginName);
+
+                var userDao = Repository.New();
+                user.CopyToDto(userDao);
+                return new ResultValueDto<UserRDto?>(userDao.Map<User, UserRDto>());
+            });
+        }
+
+        public ResultDto DeleteUser(long userId)
+        {
+            return TryCatchBlock(() =>
+            {
+                var exists = Repository.Get(userId);
+                if (exists != null) throw 
+                    ExceptionFactory.CreateException(ExceptionLibrary.ExceptionsCodes.UserNotFoundCode, "id", userId.ToString());
+
+                Repository.Remove(userId);
+                return new ResultPlain();
+            });
+        }
+
+        public ResultValueDto<UserRDto?> GetUser(string loginName)
+        {
+            if (string.IsNullOrEmpty(loginName)) throw new ArgumentNullException(nameof(loginName));
+
+            return TryCatchBlock(() =>
+            {
+                var result = Repository.GetByLoginName(loginName, true);
+                if (result == null) throw 
+                    ExceptionFactory.CreateException(ExceptionLibrary.ExceptionsCodes.UserNotFoundCode, "loginName", loginName);
+
+                return new ResultValueDto<UserRDto?>(result.Map<User, UserRDto>());
+            });
+        }
+
+        public ResultDto Lock(string loginName, bool isLocked)
+        {
+            if (string.IsNullOrEmpty(loginName)) throw new ArgumentNullException(nameof(loginName));
+
+            return TryCatchBlock(() =>
+            {
+                var result = Repository.GetByLoginName(loginName, true);
+                if (result == null) throw 
+                    ExceptionFactory.CreateException(ExceptionLibrary.ExceptionsCodes.UserNotFoundCode, "loginName", loginName);
+                result.IsLocked = isLocked;
+                Repository.Set(result);
+                return new ResultPlain();
+            });
+        }
+
+        #endregion
+
+        #region *** Private Operations ***
+        private void ValidateWDto(UserWDto user)
+        {
+            if (user == null) throw new ArgumentNullException(nameof(user));
+            var validator = new UserValidator();
+            validator.Validate(user, new ValidatorContext());
+            if (!validator.IsSuccess) throw ExceptionFactory.CreateException(ExceptionLibrary.ExceptionsCodes.ValidationErrorsCode, validator.ToAggregateException());
+        }
+
+        #endregion
+    }
+}

+ 37 - 0
Tests/qdr.app.qlbrc.base.Tests/Validators/UserValidatorTest.cs

@@ -0,0 +1,37 @@
+using qdr.fnd.core.test;
+using Quadarax.Application.QLiberace.Base.Dtos.Validators;
+using Quadarax.Application.QLiberace.Base.Dtos;
+
+namespace Quadarax.Application.QLiberace.Base.Tests.Validators
+{
+    [TestFixture(Category = "Validator")]
+    public class UserValidatorTest : ValidatorTest<UserValidator, UserWDto>
+    {
+        [Test]
+        public void LoginName()
+        {
+            Validator.Validate(Dto, Context);
+            Assert.That(Validator.IsSuccess, Is.True);
+            Assert.That(Validator.Results.Count, Is.EqualTo(0));
+
+            Dto.LoginName = string.Empty;
+            Validator.Validate(Dto, Context);
+            Assert.That(Validator.IsSuccess, Is.False);
+            Assert.That(Validator.Results.Count, Is.GreaterThan(0));
+            Assert.That(Validator.Results[0].Description.Contains("must be filled"), Is.True);
+
+            Dto.LoginName = new string('x', 101);
+            Validator.Validate(Dto, Context);
+            Assert.That(Validator.IsSuccess, Is.False);
+            Assert.That(Validator.Results.Count, Is.GreaterThan(0));
+            Assert.That(Validator.Results[0].Description.Contains("overflow"), Is.True);
+        }
+
+        protected override void OnSetup()
+        {
+            base.OnSetup();
+            Dto.LoginName = "TestCode";
+            Dto.IsLocked = false;
+        }
+    }
+}