Example #1
0
    public async Task <ApontamentoViewModel> AddAsync(ApontamentoViewModel viewModel)
    {
        ApontamentoViewModel result = _mapper.Map <ApontamentoViewModel>(await _unitOfWork.ApontamentoRepository.AddAsync(_mapper.Map <Apontamento>(viewModel)));
        await _unitOfWork.SaveChangesAsync();

        return(result);
    }
        public ActionResult <ApontamentoViewModel> Post([FromBody] ApontamentoViewModel obj)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                _apontamentoAppService.Incluir(obj);
            }
            catch (DbUpdateException)
            {
                if (ObjExists(obj.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction(nameof(Get), new { id = obj.Id }, obj));
        }
        public IActionResult Put(Guid id, [FromBody] ApontamentoViewModel obj)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != obj.Id)
            {
                return(BadRequest());
            }

            try
            {
                _apontamentoAppService.Alterar(obj);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ObjExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #4
0
    public async Task UpdateApontamentoCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();
        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();
        await unitOfWork.ProjetoRepository.AddAsync(MockEntityHelper.GetNewProjeto(sistemaId, projetoId));

        Guid workflowId = Guid.NewGuid();
        await unitOfWork.WorkflowRepository.AddAsync(MockEntityHelper.GetNewWorkflow(workflowId));

        Guid recursoId = Guid.NewGuid();
        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        Guid tipoTarefaId = Guid.NewGuid();
        await unitOfWork.TipoTarefaRepository.AddAsync(MockEntityHelper.GetNewTipoTarefa(tipoTarefaId));

        Guid tarefaId = Guid.NewGuid();
        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId, tarefaId));

        Guid        apontamentoId = Guid.NewGuid();
        DateTime    dataInclusao  = DateTime.Now;
        Apontamento apontamento   = MockEntityHelper.GetNewApontamento(tarefaId, recursoId, apontamentoId);

        await unitOfWork.ApontamentoRepository.AddAsync(apontamento);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.ApontamentoRepository.Detatch(apontamento);

        UpdateApontamentoCommand request = new()
        {
            Apontamento = MockViewModelHelper.GetNewApontamento(tarefaId, recursoId, apontamentoId, dataInclusao)
        };

        GetApontamentoQuery request2 = new()
        {
            Id = apontamentoId
        };

        // Act
        ApontamentoHandler handler  = new(unitOfWork, mapper);
        OperationResult    response = await handler.Handle(request, CancellationToken.None);

        ApontamentoViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 != null);
        Assert.True(response2.Id == apontamentoId);
        Assert.True(response2.DataInclusao.Ticks == dataInclusao.Ticks);
    }
}
        public ActionResult <ApontamentoViewModel> Get(Guid id)
        {
            ApontamentoViewModel apontamento = _apontamentoAppService.Consultar(id);

            if (apontamento == null)
            {
                return(NotFound());
            }

            return(Ok(apontamento));
        }
        public IActionResult Delete(Guid id)
        {
            ApontamentoViewModel obj = _apontamentoAppService.Consultar(id);

            if (obj == null)
            {
                return(NotFound());
            }

            _apontamentoAppService.Remover(id);

            return(NoContent());
        }
Example #7
0
    public async Task <IActionResult> OnGetAsync(Guid id)
    {
        try
        {
            Apontamento = await _cpnucleoApiService.GetAsync <ApontamentoViewModel>("apontamento", Token, id);

            return(Page());
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
            return(Page());
        }
    }
Example #8
0
        public async Task <IActionResult> OnGetAsync(Guid id)
        {
            try
            {
                Apontamento = await _apontamentoApiService.ConsultarAsync(Token, id);

                return(Page());
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(Page());
            }
        }
Example #9
0
        public void Test_OnPost(string descricao, int qtdHoras, int percentualConcluido)
        {
            // Arrange
            Guid idRecurso = Guid.NewGuid();
            Guid idTarefa  = Guid.NewGuid();

            DateTime dataApontamento = DateTime.Now;

            ApontamentoViewModel apontamentoMock = new ApontamentoViewModel {
                Descricao = descricao, DataApontamento = dataApontamento, QtdHoras = qtdHoras, PercentualConcluido = percentualConcluido, IdTarefa = idTarefa
            };

            string retorno = "e91df56a-09b1-4f14-abf4-5b098f4e404b";
            List <ApontamentoViewModel> listaMock = new List <ApontamentoViewModel> {
            };
            List <RecursoTarefaViewModel> listaRecursoTarefaMock = new List <RecursoTarefaViewModel> {
            };

            ListarModel pageModel = new ListarModel(_claimsManager.Object, _apontamentoAppService.Object, _recursoTarefaAppService.Object)
            {
                PageContext = PageContextManager.CreatePageContext()
            };

            _claimsManager.Setup(x => x.ReadClaimsPrincipal(pageModel.HttpContext.User, ClaimTypes.PrimarySid)).Returns(retorno);
            _apontamentoAppService.Setup(x => x.ListarPorRecurso(idRecurso)).Returns(listaMock);
            _recursoTarefaAppService.Setup(x => x.ListarPorRecurso(idRecurso)).Returns(listaRecursoTarefaMock);

            PageModelTester <ListarModel> pageTester = new PageModelTester <ListarModel>(pageModel);

            // Act
            pageTester
            .Action(x => x.OnPost)

            // Assert
            .WhenModelStateIsValidEquals(false)
            .TestPage();

            // Act
            pageTester
            .Action(x => x.OnPost)

            // Assert
            .WhenModelStateIsValidEquals(true)
            .TestRedirectToPage("Listar");

            // Assert
            Validation.For(apontamentoMock).ShouldReturn.NoErrors();
        }
Example #10
0
    public async Task GetApontamentoQuery_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();
        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();
        await unitOfWork.ProjetoRepository.AddAsync(MockEntityHelper.GetNewProjeto(sistemaId, projetoId));

        Guid workflowId = Guid.NewGuid();
        await unitOfWork.WorkflowRepository.AddAsync(MockEntityHelper.GetNewWorkflow(workflowId));

        Guid recursoId = Guid.NewGuid();
        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        Guid tipoTarefaId = Guid.NewGuid();
        await unitOfWork.TipoTarefaRepository.AddAsync(MockEntityHelper.GetNewTipoTarefa(tipoTarefaId));

        Guid tarefaId = Guid.NewGuid();
        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId, tarefaId));

        Guid apontamentoId = Guid.NewGuid();
        await unitOfWork.ApontamentoRepository.AddAsync(MockEntityHelper.GetNewApontamento(tarefaId, recursoId, apontamentoId));

        await unitOfWork.SaveChangesAsync();

        GetApontamentoQuery request = new()
        {
            Id = apontamentoId
        };

        // Act
        ApontamentoHandler   handler  = new(unitOfWork, mapper);
        ApontamentoViewModel response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response != null);
        Assert.True(response.Id != Guid.Empty);
        Assert.True(response.DataInclusao.Ticks != 0);
    }
Example #11
0
        public void Test_OnGet()
        {
            // Arrange
            Guid id = Guid.NewGuid();

            ApontamentoViewModel apontamentoMock = new ApontamentoViewModel {
            };

            _apontamentoAppService.Setup(x => x.Consultar(id)).Returns(apontamentoMock);

            RemoverModel pageModel = new RemoverModel(_apontamentoAppService.Object);
            PageModelTester <RemoverModel> pageTester = new PageModelTester <RemoverModel>(pageModel);

            // Act
            pageTester
            .Action(x => () => x.OnGet(id))

            // Assert
            .TestPage();
        }
Example #12
0
    public async Task <IActionResult> OnPostAsync()
    {
        try
        {
            if (!ModelState.IsValid)
            {
                Apontamento = await _cpnucleoApiService.GetAsync <ApontamentoViewModel>("apontamento", Token, Apontamento.Id);

                return(Page());
            }

            await _cpnucleoApiService.DeleteAsync("apontamento", Token, Apontamento.Id);

            return(RedirectToPage("Listar"));
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
            return(Page());
        }
    }
Example #13
0
        public async Task <IActionResult> OnGetAsync(Guid id)
        {
            Apontamento = await _apontamentoGrpcService.ConsultarAsync(id);

            return(Page());
        }
Example #14
0
 public async Task UpdateAsync(ApontamentoViewModel viewModel)
 {
     _unitOfWork.ApontamentoRepository.Update(_mapper.Map <Apontamento>(viewModel));
     await _unitOfWork.SaveChangesAsync();
 }
Example #15
0
        public async Task <IActionResult> Post([FromBody] ApontamentoViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //primeiro buscamos pelo apontamento inicial
            Apontamento apontamentoInicial = _dbContext.Apontamentos
                                             .OrderBy(a => a.DtAtualizacao)
                                             .Include(a => a.Veiculo)
                                             .Include(a => a.Apontamentos)
                                             .LastOrDefault(a => a.Tipo == TIPO_APONTAMENTO.INICIAL && a.VeiculoId == model.VeiculoId);

            //de acordo com o tipo de atividade precisamos fazer uma validação especifica sobre o objeto a ser gravado no banco
            var tipoApontamento = Enum.Parse <TIPO_APONTAMENTO>(model.Tipo);

            //somente apontamentos iniciais podem ter referencia nula para apontamento pai,
            if ((apontamentoInicial == null || apontamentoInicial.Apontamentos.Any(a => a.Tipo == TIPO_APONTAMENTO.KM_FINAL)) && tipoApontamento != TIPO_APONTAMENTO.INICIAL)
            {
                return(BadRequest(Errors.AddErrorToModelState("apontamento_failure", "Não existe uma atividade inicial em aberta para o veículo ", ModelState)));
            }

            //verifica se já existe um apontamento inicial em aberto, no caso sem o apontamento de km final
            //ou então um filho do apontamento inicial com o mesmo tipo do apontamento a ser criado.
            if (apontamentoInicial != null &&
                ((tipoApontamento == TIPO_APONTAMENTO.INICIAL && !apontamentoInicial.Apontamentos.Any(a => a.Tipo == TIPO_APONTAMENTO.KM_FINAL))
                 ||
                 apontamentoInicial.Apontamentos.Any(a => a.Tipo == tipoApontamento)))
            {
                return(BadRequest(Errors.AddErrorToModelState("apontamento_failure", "Já existe uma atividade [" + tipoApontamento.ToString() + "] em aberta para o veículo " + apontamentoInicial.Veiculo.Identificador, ModelState)));
            }

            //se não for um apontamento inicial devemos copiar os dados do pai para o filho
            if (apontamentoInicial != null && tipoApontamento != TIPO_APONTAMENTO.INICIAL)
            {
                model.Setor       = apontamentoInicial.Setor.ToString();
                model.VeiculoId   = apontamentoInicial.VeiculoId;
                model.MotoristaId = apontamentoInicial.MotoristaId;
                model.Coletor1Id  = apontamentoInicial.Coletor1Id;
                model.Coletor2Id  = apontamentoInicial.Coletor2Id;
                model.Coletor3Id  = apontamentoInicial.Coletor3Id;
            }

            //Convertemos nosso viewmodel para a entidade do colaborador
            var apontamento = new Apontamento()
            {
                DtAtualizacao        = DateTime.Now,
                AditionalInformation = model.AditionalInformation,
                Setor                = Enum.Parse <SETOR>(model.Setor),
                Tipo                 = tipoApontamento,
                VeiculoId            = model.VeiculoId,
                MotoristaId          = model.MotoristaId,
                Coletor1Id           = model.Coletor1Id,
                Coletor2Id           = model.Coletor2Id <= 0 ? null : (int?)model.Coletor2Id,
                Coletor3Id           = model.Coletor3Id <= 0 ? null : (int?)model.Coletor3Id,
                ApontamentoInicialId = tipoApontamento == TIPO_APONTAMENTO.INICIAL ? null : (int?)apontamentoInicial.Id
            };

            //adiciona o objeto do contexto do banco e faz o comite das modificações para o banco de dados
            _dbContext.Apontamentos.Add(apontamento);
            await _dbContext.SaveChangesAsync();

            return(new OkObjectResult("Apontamento criado"));
        }
Example #16
0
        public IActionResult OnGet(Guid id)
        {
            Apontamento = _apontamentoAppService.Consultar(id);

            return(Page());
        }
    public async Task <ApontamentoViewModel> Handle(GetApontamentoQuery request, CancellationToken cancellationToken = default)
    {
        ApontamentoViewModel result = _mapper.Map <ApontamentoViewModel>(await _unitOfWork.ApontamentoRepository.GetAsync(request.Id));

        return(result);
    }
Example #18
0
        public async Task <bool> AlterarAsync(ApontamentoViewModel obj)
        {
            BaseReply reply = await _client.AlterarAsync(_mapper.Map <ApontamentoModel>(obj));

            return(reply.Sucesso);
        }