public async Task <CommandResult <TEntity> > InnerAddAsync(TEntity entity, bool saveChanges = true)
        {
            TEntity result = await EntityRepository.AddAsync(entity, saveChanges);

            return(new CommandResult <TEntity>()
            {
                Entity = result, Result = CommandState.Success
            });
        }
Example #2
0
        public async Task <EntityResponse> Alugar(CalcularLocacaoInput input, IGeraPdf pdfWriter, string pathPDF)
        {
            if (input.UsuarioId == 0)
            {
                return(new EntityResponse("Usuário não identificado"));
            }

            if (input.OperadorId == 0)
            {
                return(new EntityResponse("Operador não identificado"));
            }

            var agendamentos = await _agendamentoRepository.Filter(ag => ag.VeiculoId == input.VeiculoId && ag.DataHoraEntregaRealizada == null);

            if (agendamentos.Count() > 0)
            {
                return(new EntityResponse("Veículo não está disponível"));
            }

            var simularValor = await Simular(input);

            if (!simularValor.Success)
            {
                return(new EntityResponse(simularValor.Message));
            }

            var simulado    = simularValor.Entity;
            var agendamento = new Agendamento()
            {
                DataAgendamento         = DateTime.Now,
                DataHoraColetaPrevista  = DateTime.Parse(input.DataRetirada),
                DataHoraEntregaPrevista = DateTime.Parse(input.DataDevolucao),
                ValorHora    = simulado.Veiculo.ValorHora,
                HorasLocacao = simulado.TotalHoras,
                SubTotal     = simulado.Total,
                VeiculoId    = simulado.Veiculo.Id,
                UsuarioId    = input.UsuarioId,
                OperadorId   = input.OperadorId
            };

            try
            {
                await _agendamentoRepository.AddAsync(agendamento);

                await _unitOfWork.CompleteAsync();

                var veiculo = await _veiculoRepository.Filter(x => x.Id == input.VeiculoId, v => v.Marca, v => v.Modelo, v => v.Categoria);

                new PdfService(pdfWriter).ContratoAluguelPdf(agendamento, veiculo.First(), pathPDF);

                return(new EntityResponse((IEntity)agendamento));
            }
            catch (Exception e)
            {
                return(new EntityResponse($"Um erro ocorreu ao salvar um agendamento: {e.Message}"));
            }
        }
Example #3
0
        public async Task AddAsync_SessionNotReadOnly_SessionMethodCalled()
        {
            var session    = new Mock <ISession>();
            var repository = new EntityRepository <TestEntity>(session.Object);
            var entity     = new TestEntity();

            await repository.AddAsync(entity);

            session.Verify(x => x.SaveOrUpdateAsync(entity, default), Times.Once);
        }
        public async Task AddAsync_SessionNotReadOnly_SessionMethodCalled()
        {
            var session    = new Mock <ISession>();
            var repository = new EntityRepository <TestCommand>(session.Object);
            var command    = new TestCommand();

            await repository.AddAsync(command);

            session.Verify(x => x.SaveOrUpdateAsync(command, default(CancellationToken)), Times.Once);
        }
Example #5
0
        public void AddAsync_SessionReadOnly_ExceptionThrown()
        {
            var session = new Mock <ISession>();

            session.Setup(x => x.DefaultReadOnly)
            .Returns(true);
            var repository = new EntityRepository <TestEntity>(session.Object);
            var entity     = new TestEntity();

            Assert.ThrowsAsync <EntityRepositoryException>(async() => await repository.AddAsync(entity, default),
                                                           "The Repository is read-only");
        }
        public void AddAsync_SessionReadOnly_ExceptionThrown()
        {
            var session = new Mock <ISession>();

            session.Setup(x => x.DefaultReadOnly)
            .Returns(true);
            var repository = new EntityRepository <TestCommand>(session.Object);
            var command    = new TestCommand();

            Assert.ThrowsAsync <EntityRepositoryException>(async() => await repository.AddAsync(command, default(CancellationToken)),
                                                           "The Repository is read-only");
        }
Example #7
0
        public async Task <EntityResponse> CreateAsync(T entity)
        {
            try
            {
                await _entityRepository.AddAsync(entity);

                await _unitOfWork.CompleteAsync();

                return(new EntityResponse((IEntity)entity));
            }
            catch (Exception e)
            {
                return(new EntityResponse($"Um erro ocorreu ao salvar a {entity.GetType().Name}: {e.Message}"));
            }
        }
        public async Task ShouldAddIdToKeeperAtSaveChanges()
        {
            var work = new UnitOfWorkFactory <UnitOfWork>(_dbContext, _idsKeeper);
            var repo = new EntityRepository(_dbContext, _idsKeeper);

            var newCustomer = Bogus.CustomerFaker.Generate(1).Single();
            var unitOfWork  = work.Transact();

            {
                await repo.AddAsync(newCustomer);

                await unitOfWork.SaveAsync();
            }

            Assert.That(_idsKeeper.Get <Customer>().Contains(newCustomer.Id), Is.True);
        }
        public async Task AddShouldInsertAndDeleteRelatedEntities()
        {
            var work     = new UnitOfWorkFactory <UnitOfWork>(_dbContext, _idsKeeper);
            var repo     = new EntityRepository(_dbContext, _idsKeeper);
            var customer = Bogus.CustomerFaker.Generate(1).Single();

            var unitOfWork = work.Transact();
            {
                await repo.AddAsync(customer);

                await unitOfWork.SaveAsync();
            }
            var address = await repo.GetAsync <Address>(customer.ShippingAddress.Id);

            Assert.That(address, Is.Not.Null);
            var contact = await repo.GetAsync <Contact>(customer.PrimaryContact.Id);

            Assert.That(contact, Is.Not.Null);

            unitOfWork = work.Transact();
            {
                await repo.RemoveAsync(customer);

                await unitOfWork.SaveAsync();
            }

            var customerInDb = await repo.GetAsync <Customer>(customer.Id);

            Assert.That(customerInDb, Is.Null);
            address = await repo.GetAsync <Address>(customer.ShippingAddress.Id);

            Assert.That(address, Is.Null);
            contact = await repo.GetAsync <Contact>(customer.PrimaryContact.Id);

            Assert.That(contact, Is.Null);
        }
Example #10
0
        public async Task <EntityResponse> Devolver(DevolucaoInput resource, IGeraPdf pdfWriter, string pathPDF)
        {
            var agendamento = await _agendamentoRepository.FindByIdAsync(resource.AgendamentoId);

            if (agendamento == null)
            {
                return(new EntityResponse("Agendamento não encontrado"));
            }

            if (resource.OperadorId == 0)
            {
                return(new EntityResponse("Operador Obrigatório"));
            }

            var checklist = _mapper.Map <DevolucaoInput, Checklist>(resource);

            agendamento.DataHoraEntregaRealizada = DateTime.Now;

            double adicional = 0;

            if (!resource.CarroLimpo)
            {
                adicional += agendamento.SubTotal * 0.30;
            }

            if (!resource.TanqueCheio)
            {
                adicional += agendamento.SubTotal * 0.30;
            }

            if (resource.Amassados)
            {
                adicional += agendamento.SubTotal * 0.30;
            }

            if (resource.Arranhoes)
            {
                adicional += agendamento.SubTotal * 0.30;
            }

            agendamento.CustosAdicional   = adicional;
            agendamento.ValorTotal        = agendamento.SubTotal + adicional;
            agendamento.RealizadaVistoria = true;

            try
            {
                await _checklistRepository.AddAsync(checklist);

                await _unitOfWork.CompleteAsync();

                agendamento.ChecklistId = checklist.Id;
                _agendamentoRepository.Update(agendamento);
                await _unitOfWork.CompleteAsync();

                var veiculo = await _veiculoRepository.Filter(x => x.Id == agendamento.VeiculoId, v => v.Marca, v => v.Modelo, v => v.Categoria);

                new PdfService(pdfWriter).ContratoPagamentoPdf(agendamento, veiculo.First(), pathPDF);

                return(new EntityResponse(agendamento));
            }
            catch (Exception e)
            {
                return(new EntityResponse($"Um erro ocorreu ao atualizar um agendamento: {e.Message}"));
            }
        }