Ejemplo n.º 1
0
        public ProviderDto GetById(ProviderDto input)
        {
            var         getProvider = _providerManager.GetProviderByID(input.Id);
            ProviderDto provider    = Mapper.Map <Provider, ProviderDto>(getProvider);

            return(provider);
        }
Ejemplo n.º 2
0
        // Actualizar elemento
        public Provider Update(ProviderDto providerParam, string id)
        {
            // Buscamos elemento a modificar
            var provider = _context.Provider.Find(providerParam.idProvider);

            // verificamos q existe
            if (provider == null)
            {
                throw new AppException("Proveedor no existe.");
            }

            // Verificamos si los datos ya existen
            if (providerParam.nameProvider != provider.nameProvider)
            {
                // providerName has changed so check if the new providerName is already taken
                if (_context.Provider.Any(x => x.nameProvider == providerParam.nameProvider))
                {
                    throw new AppException("El proveedor " + providerParam.nameProvider + " ya existe");
                }
            }
            // actualizamos dato
            provider.update(providerParam, _context);
            provider.auditUpdate(id);
            // Guardar cambios
            _context.Provider.Update(provider);
            _context.SaveChanges();
            return(provider);
        }
Ejemplo n.º 3
0
        public async Task CreateProviderAsync(ProviderDto provider, Phone phone, Address address)
        {
            try
            {
                var dbPhone = await CreatePhone(phone);
                var addressId = await CreateAddress(address);
                var user = await DbContext.GetUserByEmailAsync(provider.Email);
                var dbProvider = new Provider
                {
                    DateOfBirth = provider.DateOfBirth,
                    Specialty = provider.Specialty,
                    Sex = provider.Sex,
                    LicenseNumber = provider.LicenseNumber,
                    AddressId = addressId,
                    Address = address,
                    Phone = new List<Phone> { dbPhone },
                    User = user,
                    UserId = user?.Id,
                };

                await DbContext.CreateProviderAsync(dbProvider);
            }
            catch (DbEntityValidationException ex)
            {

            }
        }
Ejemplo n.º 4
0
        public IActionResult FindByName([FromQuery] string Name)
        {
            bool uowStatus = false;

            try
            {
                Provider     provider     = new Provider();
                Notification notification = provider.ValidateFindByName(Name);

                if (notification.HasErrors())
                {
                    throw new ArgumentException(notification.ErrorMessage());
                }

                Specification <Provider> specification = GetFindByName(Name);
                uowStatus = _unitOfWork.BeginTransaction();
                provider  = _providerRepository.FindByAnySpecificField(specification);
                _unitOfWork.Commit(uowStatus);
                ProviderDto providerDto = _providerAssembler.FromProviderToProviderDto(provider);
                return(StatusCode(StatusCodes.Status200OK, providerDto));
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(_responseHandler.getAppCustomErrorResponse(ex.Message)));
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback(uowStatus);
                Console.WriteLine(ex.StackTrace);
                return(StatusCode(StatusCodes.Status500InternalServerError, this._responseHandler.getAppExceptionResponse()));
            }
        }
Ejemplo n.º 5
0
        public async Task Provider_Employee_Can_Not_Have_Type_Identification_Nit()
        {
            var providerRepoMock = new Mock <IProviderRepositorio>();

            var service = new ServiceCollection();

            service.AddTransient(_ => providerRepoMock.Object);
            service.ConfigureAdministrationService(new DbSettings());
            var provider        = service.BuildServiceProvider();
            var providerService = provider.GetRequiredService <IProviderService>();

            var response = new ProviderDto
            {
                IdProvider     = Guid.Parse("3dcf7212-0984-4f61-b2b3-8f1c12120fec"),
                CompanyName    = "SYP",
                FirstName      = "Lenny",
                SecondName     = "Alexander",
                FirstLastName  = "Trejos",
                SecondLastName = "Bermúdez",
                TypeDocument   = Type_Document.Nit,
                TypePerson     = TypeOfPerson.Natural,
                DateOfBirth    = DateTimeOffset.Parse("28-05-1991"),
                SignUpDate     = DateTimeOffset.Parse("12-02-2021"),
            };

            await Assert.ThrowsAsync <ProviderEmployeeHaveNotNit>(() => providerService.AddProvider(response)).ConfigureAwait(false);
        }
Ejemplo n.º 6
0
        public ProviderDto Add(ProviderDto dto)
        {
            var entity = new Provider();

            if (dto.Id == 0)
            {
                entity = new Provider();
                this.uow.Providers.Add(entity);
            }
            else
            {
                entity         = uow.Providers.GetAll().Where(x => x.Id == dto.Id).Include(x => x.Bundles).Single();
                entity.Bundles = new List <Bundle>();
            }

            entity.Name = dto.Name;
            foreach (var bundle in dto.Bundles)
            {
                if (bundle.Checked == true)
                {
                    entity.Bundles.Add(uow.Bundles.GetById(bundle.Id));
                }
            }

            this.uow.SaveChanges();
            return(new ProviderDto(entity));
        }
Ejemplo n.º 7
0
        public void UpdateProvider_Successfult_Test()
        {
            var providerRepoMock = new Mock <IProviderRepository>();

            providerRepoMock
            .Setup(x => x.SearchMatching(It.IsAny <Expression <Func <ProviderEntity, bool> > >()))
            .Returns(new List <ProviderEntity> {
                new ProviderEntity
                {
                    ProviderId = Guid.NewGuid()
                }
            });
            providerRepoMock
            .Setup(x => x.Update(It.IsAny <ProviderEntity>()))
            .Returns(() =>
            {
                return(true);
            });
            var service = new ServiceCollection();

            service.AddTransient(_ => providerRepoMock.Object);
            service.ConfigurePeopleManagementService(new DbSettings());
            var provider    = service.BuildServiceProvider();
            var providerSvc = provider.GetRequiredService <IProviderService>();

            var newProvider = new ProviderDto
            {
                ProviderId = Guid.NewGuid(),
                PersonName = "NAME FAKE"
            };
            var response = providerSvc.UpdateProvider(newProvider);

            Assert.NotEqual(default, response);
Ejemplo n.º 8
0
        public async Task Searching_Provider_By_Id()
        {
            var providerRepoMock = new Mock <IProviderRepositorio>();

            providerRepoMock
            .Setup(id => id.SearchMatching(It.IsAny <Expression <Func <ProviderEntity, bool> > >()))
            .Returns(new List <ProviderEntity>()
            {
                new ProviderEntity {
                    IdProvider = Guid.Parse("ee98a9db-1443-4491-b470-cca353138808")
                }
            });

            var service = new ServiceCollection();

            service.AddTransient(_ => providerRepoMock.Object);
            service.ConfigureAdministrationService(new DbSettings());
            var provider        = service.BuildServiceProvider();
            var providerService = provider.GetRequiredService <IProviderService>();

            var providers = new ProviderDto
            {
                IdProvider = Guid.Parse("ee98a9db-1443-4491-b470-cca353138808")
            };

            var response = await providerService.SearchByIdProvider(providers).ConfigureAwait(false);
        }
        public async Task <IActionResult> RegisterProvider(RegisterViewModelProvider model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    Email = model.Email, UserName = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await EmailSend(model, user);

                    var provider = new ProviderDto()
                    {
                        UserId = user.Id
                    };
                    await AddProviderToDataBase(user, provider);

                    return(Content("Для завершения регистрации проверьте электронную почту и перейдите по ссылке, указанной в письме"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View("LoginModel"));
        }
Ejemplo n.º 10
0
        public async Task FailDeleteProviderNoExisting()
        {
            var service = new ServiceCollection();

            service.ConfigurePersons(new DbSettings
            {
                ConnectionString = "Server = DESKTOP-QHO5U57\\MYSQLFORBLAZOR; Database=PersonsContactInfo;Trusted_Connection=True;"
            });

            var provider = service.BuildServiceProvider();

            var ProvicerService = provider.GetRequiredService <IProviderService>();

            var ProviderToDelete = new ProviderDto
            {
                IdProvider             = ProviderIdentification,
                CompanyName            = "Coopservir",
                ContactNumber          = 3216588478,
                DateOfBirth            = new DateTimeOffset(new DateTime(1867, 1, 1), TimeSpan.Zero),
                FirstName              = "Andres",
                SecondName             = "Manuel",
                FirstLastName          = "Castro",
                SecondLastName         = "Lopez",
                SignUpDate             = DateTimeOffset.Now,
                IdNumber               = IdNumber,
                KindOfIdentificationId = Guid.NewGuid(),
                KindOfPerson           = "Juridica",
            };

            await Assert.ThrowsAsync <NoExistingProviderException>(() => ProvicerService.DeleteProvider(ProviderToDelete));
        }
Ejemplo n.º 11
0
        public void DeleteProvider_Successfult_Test()
        {
            var providerRepoMock = new Mock <IProviderRepository>();

            providerRepoMock
            .Setup(e => e.SearchMatching(It.IsAny <Expression <Func <ProviderEntity, bool> > >()))
            .Returns(new List <ProviderEntity> {
                new ProviderEntity
                {
                    ProviderId = Guid.NewGuid()
                }
            });

            providerRepoMock
            .Setup(e => e.Delete(It.IsAny <ProviderEntity>()))
            .Returns(() =>
            {
                return(true);
            });

            var service = new ServiceCollection();

            service.AddTransient(_ => providerRepoMock.Object);
            service.ConfigurePeopleManagementService(new DbSettings());
            var provider    = service.BuildServiceProvider();
            var providerSvc = provider.GetRequiredService <IProviderService>();

            var newProvider = new ProviderDto
            {
                ProviderId = Guid.Parse("31826538-6b06-4021-95c2-27fb184ac4fe")
            };

            var responseDelete = providerSvc.DeleteProvider(newProvider);

            Assert.NotEqual(default, responseDelete);
Ejemplo n.º 12
0
 public static void ValidateDataNotNull(ProviderDto request)
 {
     if (request == null)
     {
         throw new ArgumentNullException();
     }
 }
        public async Task AddAsync(ProviderDto provider)
        {
            var dataModel = _mapper.Map <Provider>(provider);
            await _repository.AddAsync(dataModel);

            await _repository.SaveChangesAsync();
        }
        public async Task <IActionResult> UpdateProvider(int id, [FromBody] ProviderDto provider)
        {
            try
            {
                if (provider.Id != id)
                {
                    ModelState.AddModelError(
                        "Identifier",
                        "Request body not apropiate for ID");
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                if (await _providerService.GetByIdAsync(id) == null)
                {
                    return(NotFound());
                }

                await _providerService.UpdateAsync(provider);

                return(NoContent());
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to succeed the operation!"));
            }
        }
Ejemplo n.º 15
0
        public bool UpdateProvider(ProviderDto request)
        {
            if (request.ProviderId == default)
            {
                throw new IdCannotNullOrEmptyException();
            }
            var ProviderIdExist = _repoProvider
                                  .SearchMatching <ProviderEntity>(p => p.ProviderId == request.ProviderId);

            if (!ProviderIdExist.Any())
            {
                throw new DontExistIdException();
            }
            var entityUpdate = ProviderIdExist.FirstOrDefault();

            entityUpdate.DocumentTypeId       = request.DocumentTypeId;
            entityUpdate.IdentificationNumber = request.IdentificationNumber;
            entityUpdate.PersonType           = request.PersonType;
            entityUpdate.PersonName           = request.PersonName;
            entityUpdate.PersonBusinessName   = request.PersonBusinessName;
            entityUpdate.PersonLastName       = request.PersonLastName;
            entityUpdate.PersonDateOfBirth    = request.PersonDateOfBirth;
            entityUpdate.CreationDate         = request.CreationDate;
            entityUpdate.PersonPhoneNumber    = request.PersonPhoneNumber;
            entityUpdate.PersonEmail          = request.PersonEmail;
            return(_repoProvider.Update(entityUpdate));
        }
Ejemplo n.º 16
0
        public void AceptanceCriteriesForInsert(ProviderDto provider)
        {
            var NitEntity = _kindOfIdRepo.GetOne <KindOfIdentificationEntity>(x => x.IdentificationName == "Nit").Result;

            var ExistingSameKindIdAndIdNumber   = _providerRepo.SearchMatching <ProviderEntity>(x => x.IdNumber == provider.IdNumber && x.KindOfIdentificationId == provider.KindOfIdentificationId).Result.Any();
            var ExistingSameNameAndKindOfPerson = _providerRepo.SearchMatching <ProviderEntity>(x => x.KindOfPerson == provider.KindOfPerson && x.FirstName + x.SecondName + x.FirstLastName + x.SecondLastName == provider.FirstName + provider.SecondName + provider.FirstLastName + provider.SecondLastName).Result.Any();

            if (ExistingSameKindIdAndIdNumber)
            {
                throw new PersonWithSameParametersExistingException("Ya existe una persona con el mismo numero y tipo de identificación");
            }
            if (ExistingSameNameAndKindOfPerson)
            {
                throw new PersonWithSameParametersExistingException("Ya existe una persona con el mismo nombre y razon social");
            }
            if (provider.SignUpDate == default)
            {
                throw new SignUpDateMissingException("Por favor ingrese la fecha de creación");
            }
            if (provider.DateOfBirth == default)
            {
                throw new DateOfBirthMissingException("Por favor ingrese la fecha de nacimiento");
            }
            if (provider.KindOfIdentificationId == NitEntity.KindOfIdentificationId)
            {
                throw new EmployeeWithNitException("El tipo de identificacion de una persona no puede ser Nit");
            }
        }
Ejemplo n.º 17
0
        public IActionResult Put([Required] string id, [FromBody] ProviderDto dto)
        {
            // We map the new Provider
            var serviceInput = _mapper.Map <Provider>(dto);

            // We try to Update the given entity
            return(Ok(_mapper.Map <ProviderDto>(_service.UpdateEntity(id, serviceInput))));
        }
        /// <summary>
        /// Добавление данных юридического лица в базу данных
        /// </summary>
        /// <param name="user"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        private async Task AddProviderToDataBase(User user, ProviderDto provider)
        {
            await _providersService.AddAsync(provider);

            await _userManager.AddToRoleAsync(user, "Provider");

            await _signInManager.SignInAsync(user, false);
        }
Ejemplo n.º 19
0
        public IActionResult Post([FromBody] ProviderDto dto)
        {
            var serviceInput = _mapper.Map <Provider>(dto);

            var result = _service.CreateEntity(serviceInput);

            return(CreatedAtAction(nameof(SearchById), new { id = result.Id }, null));
        }
Ejemplo n.º 20
0
        public Task <ProviderDto> SearchByIdProvider(ProviderDto request)
        {
            ValidateDataNotNull(request);
            var searchByIdProvider = _providerRepo
                                     .SearchMatching <ProviderEntity>(id => id.IdProvider == request.IdProvider).FirstOrDefault();

            return(Task.FromResult(_mapper.Map <ProviderDto>(searchByIdProvider)));
        }
Ejemplo n.º 21
0
        public async Task SuccesfullProviderUpdate()
        {
            var service = new ServiceCollection();

            service.ConfigurePersons(new DbSettings
            {
                ConnectionString = "Server = DESKTOP-QHO5U57\\MYSQLFORBLAZOR; Database=PersonsContactInfo;Trusted_Connection=True;"
            });

            var serviceKindOfId = new ServiceCollection();

            serviceKindOfId.ConfigureKindOfIdentification(new DbSettings
            {
                ConnectionString = "Server = DESKTOP-QHO5U57\\MYSQLFORBLAZOR; Database=PersonsContactInfo;Trusted_Connection=True;"
            });


            var provider    = service.BuildServiceProvider();
            var KoiProvider = serviceKindOfId.BuildServiceProvider();

            var providerService = provider.GetRequiredService <IProviderService>();
            var KindOfIdService = KoiProvider.GetRequiredService <IKindOfIdentificationService>();

            var KindOfId = "Cedula";
            var Cedula   = await KindOfIdService.GetOne(new KindOfIdentificationDto { IdentificationName = KindOfId });

            var IdProviderToEdit = Guid.NewGuid();

            var AddedProvider = new ProviderDto
            {
                CompanyName            = "Koala",
                ContactNumber          = 3219655215,
                IdProvider             = IdProviderToEdit,
                KindOfPerson           = "Juridica",
                DateOfBirth            = new DateTimeOffset(new DateTime(1867, 1, 1), TimeSpan.Zero),
                FirstName              = "Sandra",
                SecondName             = "Alkista",
                FirstLastName          = "Lanzini",
                SecondLastName         = "Lopez",
                SignUpDate             = DateTimeOffset.Now,
                IdNumber               = IdNumber,
                KindOfIdentificationId = Cedula.KindOfIdentificationId,
            };

            await providerService.InsertProvider(AddedProvider);

            var response = await providerService.UpdateProvider(new ProviderDto
            {
                IdProvider   = IdProviderToEdit,
                KindOfPerson = "Natural",
                SignUpDate   = DateTimeOffset.Now,
                DateOfBirth  = DateTimeOffset.Now
            });

            Assert.True(response);

            await providerService.DeleteProvider(AddedProvider);
        }
        public async Task <ProviderDto> ProviderManagementInsert(ProviderDto requestDto)
        {
            var result = await _providerService.AddProvider(requestDto).ConfigureAwait(false);

            return(new ProviderDto
            {
                StatusCode = result != default ? HttpStatusCode.OK : HttpStatusCode.Unauthorized,
                StatusDescription = result != default ? "Ok" : "Error",
            });
Ejemplo n.º 23
0
        public static int Insert(ProviderDto dto)
        {
            int id = ProviderDao.Insert(dto);

            dto.ProviderId = id;
            allNotDeletedProviders.Add(dto);
            allNotDeletedProviders = allNotDeletedProviders.OrderByDescending(n => n.ProviderId).ToList();
            return(id);
        }
Ejemplo n.º 24
0
 public bool DeleteProvider(ProviderDto request)
 {
     if (request.ProviderId == default)
     {
         throw new IdCannotNullOrEmptyException();
     }
     ValidateProviderIdExist(request);
     return(_repoProvider.Delete(_mapper.Map <ProviderEntity>(request)));
 }
Ejemplo n.º 25
0
        public void ValidateIfExistTheSameIdentification(ProviderDto request, IEnumerable <ProviderEntity> people)
        {
            var validateByIdentificactionNumber = people.Where(x =>
                                                               x.IdentificationNumber == request.IdentificationNumber && x.DocumentTypeId == request.DocumentTypeId);

            if (validateByIdentificactionNumber.Any())
            {
                throw new AlreadyExistException($"ya existe alguien el mismo numero de indentificación y tipo de documento: {request.IdentificationNumber}");
            }
        }
Ejemplo n.º 26
0
        public void GoodsDtoTransformerTest()
        {
            var domain   = new Goods(1, "1", 2, 3, 4, 5m);
            var provider = new ProviderDto(12, "name", "adress", "phone");
            var category = new GoodsCategoryDto(54, "category");
            var gclass   = new GoodsClassDto(76543, "class");
            var result   = GoodsTransformer.FromGoodsToGoodsDto(domain, provider, category, gclass);

            Assert.AreEqual(category.Title, result.GoodsCategory.Title);
        }
Ejemplo n.º 27
0
        private void ValidateProviderIdExist(ProviderDto request)
        {
            var ProviderIdExist = _repoProvider
                                  .SearchMatching <ProviderEntity>(p => p.ProviderId == request.ProviderId).Any();

            if (!ProviderIdExist)
            {
                throw new DontExistIdException();
            }
        }
Ejemplo n.º 28
0
        public void ValidateIfExistSameName(ProviderDto request, IEnumerable <ProviderEntity> people)
        {
            var providersByName = people
                                  .Where(e => e.PersonName == request.PersonName && e.PersonBusinessName == request.PersonBusinessName);

            if (providersByName.Any())
            {
                throw new AlreadyExistException($"ya existe alguien con el nombre : {request.PersonName} y razon social:{request.PersonBusinessName}");
            }
        }
Ejemplo n.º 29
0
        public async Task UpdateAsync(ProviderDto provider)
        {
            var entity = await _uow.ProviderRepository.SingleOrDefaultAsync(x => x.Id == provider.Id);

            var catalogue = await _uow.CatalogueRepository.SingleOrDefaultAsync(x => x.Id == provider.Catalogue.Id);

            entity.Name           = provider.Name;
            catalogue.Description = provider.Catalogue.Description;

            await _uow.CommitAsync();
        }
Ejemplo n.º 30
0
        public async Task <IActionResult> Post([FromBody] ProviderCreatingDto newProvider)
        {
            if (newProvider == null)
            {
                return(BadRequest());
            }

            ProviderDto result = await AddOrUpdateProvider(newProvider);

            return(Ok(result));
        }
Ejemplo n.º 31
0
 public IActionResult CreateProvider([FromBody] ProviderDto dto)
 {
     try
     {
         return(Ok(_providerServices.CreateProvider(dto)));
     }
     catch (ArgumentException e)
     {
         return(BadRequest(e.Message));
     }
 }