Exemplo n.º 1
0
        public async Task SaveEmployeeTest()
        {
            var objA = new EmployeeInsertDto
            {
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString(),
                Email     = $"{Guid.NewGuid()}@email.com",
            };

            using var srv = new TestServer(TestHostBuilder <Startup, UnigrationWebApiTestStartup>());
            var client = srv.CreateClient();

            GenerateAuthHeader(client, GenerateTestToken());

            var resp = await client.PostAsJsonAsync("api/v1/Employees.json", objA);

            _ = resp.EnsureSuccessStatusCode();
            var result = await DeserializeResponseAsync <Employee>(resp);

            Assert.AreEqual(objA.FirstName, result.FirstName);
            Assert.AreEqual("*****@*****.**", result.CreatedBy);

            var ctx = srv.GetDbContext <EmployeesContext>();
            var emp = await ctx.Employees.FirstOrDefaultAsync(t => t.FirstName == result.FirstName);

            Assert.IsNotNull(emp);
            Assert.AreEqual(result.CreatedOnUtc, emp.CreatedOnUtc);
        }
Exemplo n.º 2
0
        public IActionResult InsertEmployee(EmployeeInsertDto input)
        {
            try
            {
                #region Validation
                var validator = new ParamValidator();
                validator.ValidateNull(input.FirstName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام"))
                .ValidateNull(input.LastName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام خانوادگی"))
                .ValidateNull(input.UserName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام کاربری"))
                .ValidateNull(input.Password, General.Messages_.NullInputMessages_.GeneralNullMessage("رمز عبور"))
                .Throw(General.Results_.FieldNullErrorCode());

                if (input.RoleList.Count == 0)
                {
                    throw new BusinessException(XError.BusinessErrors.RoleNotSelected());
                }
                if (_repository.Users.FindByCondition(c => c.Username == input.UserName).Any())
                {
                    throw new BusinessException(XError.BusinessErrors.UserAlreadyExists());
                }
                #endregion

                var employee = new Employee();

                var user = new Users
                {
                    Cdate     = DateTime.Now.Ticks,
                    CuserId   = ClaimPrincipalFactory.GetUserId(User),
                    FullName  = input.FirstName + " " + input.LastName,
                    Hpassword = input.Password,
                    Username  = input.UserName
                };
                input.RoleList.ForEach(c =>
                {
                    var userRole = new UserRole
                    {
                        Cdate   = DateTime.Now.Ticks,
                        CuserId = ClaimPrincipalFactory.GetUserId(User),
                        Role    = c
                    };
                    user.UserRole.Add(userRole);
                });
                employee.User = user;

                _repository.Employee.Create(employee);
                _repository.Save();

                _logger.LogData(MethodBase.GetCurrentMethod(), employee.Id, null, input);
                return(Ok(employee.Id));
            }
            catch (Exception e)
            {
                _logger.LogError(e, MethodBase.GetCurrentMethod(), input);
                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 3
0
        public async Task <ActionResult> Post([FromBody] EmployeeInsertDto value)
        {
            var obj = Employee.FromInsertDto(value);

            ContextCollectionSyncer.SyncCollections(_ctx, value.EmployeeCompetencies, obj.EmployeeCompetencies);
            ContextCollectionSyncer.SyncCollections(_ctx, value.EmployeeCertifications, obj.EmployeeCertifications);
            ContextCollectionSyncer.SyncCollections(_ctx, value.EmployeeHealthItems, obj.EmployeeHealthItems);
            _ = _ctx.Employees.Add(obj);
            if (0 < await _ctx.SaveChangesAsync())
            {
                await _createdPublisher.PublishAsync(obj);
            }
            return(Ok(obj));
        }
Exemplo n.º 4
0
        public IActionResult UpdateEmployee(EmployeeInsertDto input)
        {
            try
            {
                var user = _repository.Employee.FindByCondition(c => c.Id == input.Id).Select(c => c.User)
                           .FirstOrDefault();
                #region Validation
                if (user == null)
                {
                    throw new BusinessException(XError.GetDataErrors.NotFound());
                }

                var validator = new ParamValidator();
                validator.ValidateNull(input.FirstName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام"))
                .ValidateNull(input.LastName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام خانوادگی"))
                .ValidateNull(input.UserName, General.Messages_.NullInputMessages_.GeneralNullMessage("نام کاربری"))
                .ValidateNull(input.Password, General.Messages_.NullInputMessages_.GeneralNullMessage("رمز عبور"))
                .Throw(General.Results_.FieldNullErrorCode());

                if (input.RoleList.Count == 0)
                {
                    throw new BusinessException(XError.BusinessErrors.RoleNotSelected());
                }
                if (_repository.Users.FindByCondition(c => c.Username == input.UserName && c.Id != user.Id).Any())
                {
                    throw new BusinessException(XError.BusinessErrors.UserAlreadyExists());
                }
                #endregion


                user.Mdate     = DateTime.Now.Ticks;
                user.MuserId   = ClaimPrincipalFactory.GetUserId(User);
                user.FullName  = input.FirstName + " " + input.LastName;
                user.Hpassword = input.Password;
                user.Username  = input.UserName;

                var toBeDdeleted = _repository.UserRole.FindByCondition(c => c.UserId == user.Id).ToList();
                _repository.UserRole.DeleteRange(toBeDdeleted);

                input.RoleList.ForEach(c =>
                {
                    var userRole = new UserRole
                    {
                        Cdate   = DateTime.Now.Ticks,
                        CuserId = ClaimPrincipalFactory.GetUserId(User),
                        Role    = c
                    };
                    user.UserRole.Add(userRole);
                });

                _repository.Users.Update(user);
                _repository.Save();

                _logger.LogData(MethodBase.GetCurrentMethod(), General.Results_.SuccessMessage(), null, input);
                return(Ok(General.Results_.SuccessMessage()));
            }
            catch (Exception e)
            {
                _logger.LogError(e, MethodBase.GetCurrentMethod(), input);
                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 5
0
        public async Task SaveEmployeeTest()
        {
            var objA = new EmployeeInsertDto
            {
                FirstName = Guid.NewGuid().ToString(),
                LastName  = Guid.NewGuid().ToString(),
                Email     = $"{Guid.NewGuid()}@email.com",
            };

            objA.EmployeeCertifications.Add(
                new EmployeeCertification
            {
                CertificationId   = Guid.NewGuid(),
                CertificationName = Guid.NewGuid().ToString(),
            });
            objA.EmployeeCertifications.Add(
                new EmployeeCertification
            {
                CertificationId   = Guid.NewGuid(),
                CertificationName = Guid.NewGuid().ToString(),
                ExpiresOnUtc      = DateTime.UtcNow.AddDays(new Random().Next(1, 20)),
            });
            objA.EmployeeCompetencies.Add(
                new EmployeeCompetency
            {
                CompetencyId   = Guid.NewGuid(),
                CompetencyName = Guid.NewGuid().ToString(),
            });
            objA.EmployeeCompetencies.Add(
                new EmployeeCompetency
            {
                CompetencyId   = Guid.NewGuid(),
                CompetencyName = Guid.NewGuid().ToString(),
                ExpiresOnUtc   = DateTime.UtcNow.AddDays(new Random().Next(1, 20)),
                IsEnabled      = true
            });
            objA.EmployeeHealthItems.Add(new EmployeeHealthItem
            {
                HealthItemId   = Guid.NewGuid(),
                HealthItemName = Guid.NewGuid().ToString(),
            });
            objA.EmployeeHealthItems.Add(
                new EmployeeHealthItem
            {
                HealthItemId   = Guid.NewGuid(),
                HealthItemName = Guid.NewGuid().ToString(),
                ExpiresOnUtc   = DateTime.UtcNow.AddDays(new Random().Next(1, 20)),
                IsEnabled      = true
            });
            using var srv = new TestServer(TestHostBuilder <Startup, IntegrationTestStartup>());
            var client = srv.CreateClient();

            GenerateAuthHeader(client, GenerateTestToken());

            var resp = await client.PostAsJsonAsync($"api/v1/{nameof(Employees)}.json", objA);

            _ = resp.EnsureSuccessStatusCode();
            var result = await DeserializeResponseAsync <Employee>(resp);

            Assert.AreEqual(objA.FirstName, result.FirstName);
            Assert.IsTrue(result.IsEnabled);
            Assert.IsNotNull(result.CreatedBy);

            var ctx = srv.GetDbContext <EmployeesContext>();
            var emp = await ctx.Employees.Include(t => t.EmployeeCertifications).FirstOrDefaultAsync(t => t.FirstName == result.FirstName);

            Assert.IsNotNull(emp);
            Assert.AreEqual(result.CreatedOnUtc.ToString(), emp.CreatedOnUtc.ToString());
            Assert.AreEqual(2, emp.EmployeeCertifications.Count);
        }