Пример #1
0
    public async Task <IActionResult> Put(Guid id, [FromBody] Apontamento obj)
    {
        if (!ModelState.IsValid)
        {
            return(BadRequest(ModelState));
        }

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

        try
        {
            _unitOfWork.ApontamentoRepository.Update(obj);

            await _unitOfWork.SaveChangesAsync();
        }
        catch (Exception)
        {
            if (!await ObjExists(id))
            {
                return(NotFound());
            }
            else
            {
                throw;
            }
        }

        return(NoContent());
    }
Пример #2
0
    public async Task <ActionResult <Apontamento> > Post([FromBody] Apontamento obj)
    {
        if (!ModelState.IsValid)
        {
            return(BadRequest(ModelState));
        }

        try
        {
            obj = await _unitOfWork.ApontamentoRepository.AddAsync(obj);

            await _unitOfWork.SaveChangesAsync();
        }
        catch (Exception)
        {
            if (await ObjExists(obj.Id))
            {
                return(Conflict());
            }
            else
            {
                throw;
            }
        }

        return(CreatedAtRoute("GetApontamento", new { id = obj.Id }, obj));
    }
Пример #3
0
        public async Task <bool> SalvarMarcacao(Apontamento apontamento)
        {
            try
            {
                HttpResponseMessage result;

                var serializedApontamento = JsonConvert.SerializeObject(apontamento);

                var content = new StringContent(serializedApontamento, Encoding.UTF8, "application/json");

                if (apontamento.Id == null)
                {
                    result = await client.PostAsync(client.BaseAddress + "api/cadastrar", content);
                }
                else
                {
                    result = await client.PostAsync(client.BaseAddress + "api/Atualizar", content);
                }

                return(result.IsSuccessStatusCode);
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao salvar marcação", ex);
            }
        }
Пример #4
0
 private void CarregarAtividades(Apontamento apontamento)
 {
     if (apontamento != null)
     {
         txtDescricao.Text       = apontamento.DescricaoAtividade;
         txtCodigoAtividade.Text = apontamento.CodigoAtividade;
     }
 }
Пример #5
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);
    }
}
Пример #6
0
    public async Task <ActionResult <Apontamento> > Get(Guid id)
    {
        Apontamento apontamento = await _unitOfWork.ApontamentoRepository.GetAsync(id);

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

        return(Ok(apontamento));
    }
Пример #7
0
 public Marcacao(Apontamento apontamento)
 {
     this.Id                 = apontamento.Id;
     this.IdUsuario          = apontamento.IdUsuario;
     this.Entrada            = apontamento.Entrada;
     this.SaidaAlmoco        = apontamento.SaidaAlmoco;
     this.RetornoAlmoco      = apontamento.RetornoAlmoco;
     this.Saida              = apontamento.Saida;
     this.DataMarcacao       = apontamento.DataMarcacao;
     this.HorasTotalDia      = apontamento.HorasTotalDia;
     this.DescricaoAtividade = apontamento.DescricaoAtividade;
     this.CodigoAtividade    = apontamento.CodigoAtividade;
 }
Пример #8
0
        private async void EfetuaMarcacaoSaidaAlmoco(string saidaAlmoco)
        {
            Apontamento             = new Apontamento();
            Apontamento.IdUsuario   = IdUsuario;
            Apontamento.SaidaAlmoco = saidaAlmoco;

            Marcacao = new Marcacao(Apontamento);


            if (await _realizaMarcacao.RealizaMarcacao(Marcacao, _marcacaoSaidaAlmoco))
            {
                CarregarMarcacaoSaidaAlmoco(saidaAlmoco);
            }
        }
        public List <Domain.Enty.Apontamento> ObterListBatidaDePontoDiario(string mat, string filial, string Data)
        {
            try
            {
                using (OracleConnection Conexao = new OracleConnection(ConnectionString))
                {
                    List <Apontamento> listApontamento = new List <Apontamento>();
                    Apontamento        apontamento;
                    var sql = $@"Select  LTRIM(RTRIM(P8_HORA)) AS hora from SP8010
                         where P8_MAT = LTRIM(RTRIM('{mat}'))  AND P8_FILIAL = LTRIM(RTRIM('{filial}')) 
                          AND D_E_L_E_T_ <> '*' AND P8_APONTA = 'S' AND P8_DATA = LTRIM(RTRIM('{Data}'))";
                    Conexao.Open();
                    var QueryResult = Conexao.Query <Apontamento>(sql);
                    foreach (Apontamento ApResult in QueryResult)
                    {
                        string valor = "";
                        apontamento = new Apontamento();
                        if (ApResult.hora.Length > 2)
                        {
                            int virgulaIndice = ApResult.hora.IndexOf(',');
                            valor = ApResult.hora.Substring(virgulaIndice);
                        }
                        if (ApResult.hora.Length == 1 | ApResult.hora.Length == 2)
                        {
                            apontamento.apontamento = TimeSpan.Parse("0" + ApResult.hora + ":00");
                        }
                        else if (valor.Length == 2)
                        {
                            string horaMinuto = ApResult.hora + "0"; apontamento.apontamento = TimeSpan.Parse(horaMinuto.Replace(',', ':'));
                        }
                        else
                        {
                            apontamento.apontamento = TimeSpan.Parse(ApResult.hora.Replace(',', ':'));
                            apontamento.horaFim     = TimeSpan.Parse(ApResult.hora.Replace(',', ':'));
                        }

                        listApontamento.Add(apontamento);
                    }

                    return(listApontamento);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }
Пример #10
0
        private async void EfetuaMarcacaoEntrada(string entrada)
        {
            Apontamento           = new Apontamento();
            Apontamento.IdUsuario = IdUsuario;
            Apontamento.Entrada   = entrada;

            Marcacao = new Marcacao(Apontamento);


            if (await _realizaMarcacao.RealizaMarcacao(Marcacao, _marcacaoEntrada))
            {
                CarregarMarcacaoEntrada(entrada);
            }
        }
Пример #11
0
        public HttpResponseMessage SalvarMarcacao(Apontamento apontamento)
        {
            try
            {
                var ID = new ObjectId();
                apontamento.Id = ID;

                _apontamentoRepository.Inserir(apontamento);
                return(Request.CreateResponse(HttpStatusCode.OK, "Marcação Efetuada com sucesso."));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Пример #12
0
    public async Task <IActionResult> Delete(Guid id)
    {
        Apontamento obj = await _unitOfWork.ApontamentoRepository.GetAsync(id);

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

        await _unitOfWork.ApontamentoRepository.RemoveAsync(id);

        await _unitOfWork.SaveChangesAsync();

        return(NoContent());
    }
Пример #13
0
        private async void SalvarAtividades()
        {
            Apontamento                    = new Apontamento();
            Apontamento.IdUsuario          = IdUsuario;
            Apontamento.DescricaoAtividade = txtDescricao.Text;
            Apontamento.CodigoAtividade    = txtCodigoAtividade.Text;

            Marcacao = new Marcacao(Apontamento);

            if (await _realizaMarcacao.RealizaMarcacao(Marcacao, _marcacaoAtividades))
            {
                MetroMessageBox.Show(this, "Atividades Salvas com sucesso.", "Sucesso", MessageBoxButtons.OK);
                LimparCampos();
            }
        }
Пример #14
0
        public async Task <Apontamento> BuscarMarcacaoNoDia(string idUsuario, string dataMarcacao)
        {
            Apontamento         apontamento = null;
            HttpResponseMessage response    = await client
                                              .GetAsync(client.BaseAddress + "api/apontamento/consultar-apontamento/" + idUsuario + "/" + dataMarcacao.FormatarDataEnvio());

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }
            var apontamenroJsonString = await response.Content.ReadAsStringAsync();

            apontamento = JsonConvert.DeserializeObject <Apontamento>(apontamenroJsonString);
            client.CancelPendingRequests();
            return(apontamento);
        }
Пример #15
0
        public async Task <bool> AtualizarMarcacao(Apontamento apontamento)
        {
            try
            {
                var serializedApontamento = JsonConvert.SerializeObject(apontamento);

                var content = new StringContent(serializedApontamento, Encoding.UTF8, "application/json");
                var result  = await client.PostAsync(client.BaseAddress + "api/atualizar", content);

                return(result.IsSuccessStatusCode);
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao salvar marcação", ex);
            }
        }
Пример #16
0
        private async void EfetuaMarcacaoSaida(string saida)
        {
            Apontamento               = new Apontamento();
            Apontamento.IdUsuario     = IdUsuario;
            Apontamento.Saida         = saida;
            Apontamento.HorasTotalDia = RetornaTotalHorasTrabalhada();

            Marcacao = new Marcacao(Apontamento);


            if (await _realizaMarcacao.RealizaMarcacao(Marcacao, _marcacaoSaida))
            {
                CarregarMarcacaoSaida(saida);
            }
            CalcularTotalHorasDia();
        }
    public async Task <OperationResult> Handle(RemoveApontamentoCommand request, CancellationToken cancellationToken = default)
    {
        Apontamento obj = await _unitOfWork.ApontamentoRepository.GetAsync(request.Id);

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

        await _unitOfWork.ApontamentoRepository.RemoveAsync(request.Id);

        bool success = await _unitOfWork.SaveChangesAsync();

        OperationResult result = success ? OperationResult.Success : OperationResult.Failed;

        return(result);
    }
        public ActionResult Salvar(string numeroSerie, string sequencial)
        {
            if (string.IsNullOrEmpty(numeroSerie) || string.IsNullOrEmpty(sequencial))
            {
                return(Json(true, JsonRequestBehavior.AllowGet));
            }

            Apontamento apontamento = _apontamentoService.GetByNumeroSerieAndSequencial(numeroSerie, sequencial);

            if (apontamento != null)
            {
                return(Json(new { erro = true, msg = string.Format("O número de serie '{0}' já está vinculado ao sequencial '{1}'.", numeroSerie, sequencial) }, JsonRequestBehavior.AllowGet));
            }

            apontamento = _apontamentoService.GetByNumeroSerie(numeroSerie);
            if (apontamento != null)
            {
                return(Json(new { erro = true, msg = string.Format("O número de serie '{0}' já existe.", numeroSerie) }, JsonRequestBehavior.AllowGet));
            }

            apontamento = _apontamentoService.GetBySequencial(sequencial);
            if (apontamento != null)
            {
                return(Json(new { erro = true, msg = string.Format("O sequencial '{0}' já existe.", sequencial) }, JsonRequestBehavior.AllowGet));
            }


            apontamento             = new Apontamento();
            apontamento.NumeroSerie = numeroSerie;
            apontamento.Sequencial  = sequencial;
            apontamento.Data        = DateTime.Now;
            apontamento.UsuarioId   = _usuarioService.GetUsuario(User.Identity.Name).Id;

            try
            {
                _apontamentoService.Create(apontamento);
            }
            catch (Exception)
            {
                return(Json(new { erro = true, msg = string.Format("Ocorreu um erro ao salvar.") }, JsonRequestBehavior.AllowGet));
            }

            return(View("Index"));
        }
Пример #19
0
        public async Task <bool> EfetuarMarcacao(Marcacao marcacao)
        {
            string dataMarcacao = DateTime.Now.Date.ToString("dd/MM/yyyy");

            var apontamento = await _apontamentoService.BuscarMarcacaoNoDia(marcacao.IdUsuario, dataMarcacao);

            if (apontamento == null)
            {
                apontamento = new Apontamento
                {
                    IdUsuario    = marcacao.IdUsuario,
                    SaidaAlmoco  = marcacao.SaidaAlmoco,
                    DataMarcacao = dataMarcacao
                };
            }

            apontamento.SaidaAlmoco = marcacao.SaidaAlmoco;

            return(await _apontamentoService.SalvarMarcacao(apontamento));
        }
Пример #20
0
        public async Task <bool> EfetuarMarcacao(Marcacao marcacao)
        {
            string dataMarcacao = DateTime.Now.Date.ToString("dd/MM/yyyy");

            var apontamento = await _apontamentoService.BuscarMarcacaoNoDia(marcacao.IdUsuario, dataMarcacao);

            if (apontamento == null)
            {
                apontamento = new Apontamento
                {
                    IdUsuario          = marcacao.IdUsuario,
                    DataMarcacao       = dataMarcacao,
                    DescricaoAtividade = marcacao.DescricaoAtividade,
                    CodigoAtividade    = marcacao.CodigoAtividade
                };
            }
            apontamento.DescricaoAtividade = marcacao.DescricaoAtividade;
            apontamento.CodigoAtividade    = marcacao.CodigoAtividade;

            return(await _apontamentoService.SalvarMarcacao(apontamento));
        }
Пример #21
0
        public HttpResponseMessage AtualizarMarcacao(Apontamento apontamento)
        {
            try
            {
                var apontamentoConsulta = _apontamentoRepository
                                          .Consultar(c => c.IdUsuario == apontamento.IdUsuario && c.DataMarcacao == apontamento.DataMarcacao);

                if (apontamentoConsulta == null)
                {
                    throw new Exception("Erro ao atualizar Marcação");
                }

                apontamento.Id = apontamentoConsulta.Id;

                _apontamentoRepository.Atualizar(apontamento);

                return(Request.CreateResponse(HttpStatusCode.OK, "Marcação alterada com sucesso."));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Пример #22
0
        public List <Domain.Enty.Apontamento> ObterListBatidaDePontoDiario(string mat, string filial, string Data)
        {
            try
            {
                using (OracleConnection Conexao = new OracleConnection(ConnectionString))
                {
                    List <Apontamento> listApontamento = new List <Apontamento>();
                    Apontamento        apontamento;

                    var sql = $@"SELECT LTRIM(RTRIM(TO_CHAR(round(ABATFUN.BATIDA/60,2)))) as hora
                                  FROM ABATFUN 
                                 WHERE ABATFUN.CODCOLIGADA=LTRIM(RTRIM('{filial}'))
                                 AND ABATFUN.CHAPA=LTRIM(RTRIM('{mat}')) 
                                 AND ABATFUN.DATA =LTRIM(RTRIM('{Data.ToDateProtheusReverseformate()}'))";
                    Conexao.Open();
                    var QueryResult = Conexao.Query <Apontamento>(sql);
                    foreach (Apontamento ApResult in QueryResult)
                    {
                        string valor = "";
                        apontamento = new Apontamento();
                        if (ApResult.hora.Length > 2)
                        {
                            int virgulaIndice = ApResult.hora.IndexOf(',');
                            valor = ApResult.hora.Substring(virgulaIndice);
                        }
                        if (ApResult.hora.Length == 1 | ApResult.hora.Length == 2)
                        {
                            apontamento.apontamento = TimeSpan.Parse("0" + ApResult.hora + ":00");
                        }
                        else if (ApResult.hora.Length >= 3)
                        {
                            string  hora          = "";
                            int     virgulaIndice = ApResult.hora.IndexOf(',');
                            var     valorMinuto   = ApResult.hora.Substring(virgulaIndice + 1);
                            decimal minutos       = Convert.ToDecimal("0," + valorMinuto) * 60;

                            if (ApResult.hora.Substring(0, virgulaIndice).Length == 2)
                            {
                                hora = ApResult.hora.Substring(0, 2);
                            }
                            else
                            {
                                hora = ApResult.hora.Substring(0, 1);
                            }

                            decimal minutoRound = Math.Round(minutos);

                            string horaMinuto = hora + Convert.ToString(":" + Convert.ToString(minutoRound));
                            apontamento.apontamento = TimeSpan.Parse(horaMinuto);
                        }
                        else
                        {
                            apontamento.apontamento = TimeSpan.Parse(ApResult.hora.Replace(',', ':'));
                            apontamento.horaFim     = TimeSpan.Parse(ApResult.hora.Replace(',', ':'));
                        }

                        listApontamento.Add(apontamento);
                    }

                    return(listApontamento);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }
Пример #23
0
        private List <Apontamento> ListaApontamentoPorLancamentoGerencia(List <ViewModelLancamento> listlancamentoViewModel, string matriculaColaborador, string filial, string codMarcacao)
        {
            List <Apontamento> listaApontamento = new List <Apontamento>();
            string             datalancamento   = "0";

            foreach (ViewModelLancamento lancamento in listlancamentoViewModel.OrderBy(x => x.DateLancamento))
            {
                if (datalancamento != lancamento.DateLancamento)
                {
                    var listApontamento = _protheusService.ObterBatidasDePonto(matriculaColaborador, filial, lancamento.DateLancamento);
                    datalancamento = lancamento.DateLancamento;
                    if (listApontamento.Count > 0)
                    {
                        foreach (Apontamento apontamentoResult in listApontamento)
                        {
                            Apontamento       novo = new Apontamento();
                            List <Lancamento> listaLancamentoPorApontamento = new List <Lancamento>();
                            novo.dataApontamento = datalancamento.ToDateProtheusReverseformate();
                            novo.apontamento     = apontamentoResult.apontamento;
                            foreach (ViewModelLancamento listaLacamento in listlancamentoViewModel.OrderBy(x => x.DateLancamento))
                            {
                                if (novo.dataApontamento == listaLacamento.DateLancamento.ToDateProtheusReverseformate())
                                {
                                    if (!listaLancamentoPorApontamento.Contains(_mapper.Map <Lancamento>(listaLacamento), new ComparerDados()))
                                    {
                                        listaLancamentoPorApontamento.Add(_mapper.Map <Lancamento>(listaLacamento));
                                    }
                                }
                            }
                            novo.listLancamento = listaLancamentoPorApontamento;
                            listaApontamento.Add(novo);
                        }
                    }
                    else
                    {
                        Apontamento       novo = new Apontamento();
                        List <Lancamento> listaLancamentoPorApontamento = new List <Lancamento>();
                        novo.dataApontamento = datalancamento.ToDateProtheusReverseformate();
                        foreach (ViewModelLancamento listaLacamento in listlancamentoViewModel.OrderBy(x => x.DateLancamento))
                        {
                            if (novo.dataApontamento == listaLacamento.DateLancamento.ToDateProtheusReverseformate())
                            {
                                if (!listaLancamentoPorApontamento.Contains(_mapper.Map <Lancamento>(listaLacamento), new ComparerDados()))
                                {
                                    listaLancamentoPorApontamento.Add(_mapper.Map <Lancamento>(listaLacamento));
                                }
                            }
                        }
                        novo.listLancamento = listaLancamentoPorApontamento;
                        listaApontamento.Add(novo);
                    }
                }
            }

            var listlancamento        = _mapper.Map <List <Lancamento> >(listlancamentoViewModel);
            var marcacao              = _marcacao.ObterMarcacao(codMarcacao);
            var jornada               = _jornadaTrbServiceRepository.ObterJornadaPorCodigo(marcacao.codigojornada);
            var listDiasSemLancamento = _lancamentoNegocio.ObterDiasSemLancamento(listlancamento.Distinct(new LancamentoComparer()).ToList(), marcacao, User.GetDados("Filial"), jornada);

            foreach (Fechamento fachamento in listDiasSemLancamento.OrderBy(x => x.DataLancamento))
            {
                var listApontamento = _protheusService.ObterBatidasDePonto(matriculaColaborador, filial, fachamento.DataLancamento);
                if (listApontamento.Count > 0)
                {
                    foreach (Apontamento apontamentoResult in listApontamento)
                    {
                        Apontamento       novo = new Apontamento();
                        List <Lancamento> listaLancamentoPorApontamento = new List <Lancamento>();
                        novo.dataApontamento = fachamento.DataLancamento.ToDateProtheusReverseformate();
                        novo.apontamento     = apontamentoResult.apontamento;
                        listaApontamento.Add(novo);
                    }
                }
                else
                {
                    Apontamento       novo = new Apontamento();
                    List <Lancamento> listaLancamentoPorApontamento = new List <Lancamento>();
                    novo.dataApontamento = fachamento.DataLancamento.ToDateProtheusReverseformate();
                    listaApontamento.Add(novo);
                }
            }

            return(listaApontamento);
        }
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    Dictionary <string, string> listaRetorno = new Dictionary <string, string>();

                    string readFileName = Path.GetFileName(file.FileName);
                    string readFilePath = Path.Combine(Server.MapPath("~/Temp"), readFileName);
                    file.SaveAs(readFilePath);

                    var readFileTemplate = new FileInfo(readFilePath);
                    var readFilePck      = new ExcelPackage(readFileTemplate, true);

                    int linha = 1;
                    //int coluna = 1;
                    try
                    {
                        var readFileWorksheet = readFilePck.Workbook.Worksheets[1];

                        List <string> listFromPlanilha = new List <string>();
                        while (!string.IsNullOrEmpty(readFileWorksheet.Cells[linha, 1].Value + ""))
                        {
                            listFromPlanilha.Add(readFileWorksheet.Cells[linha, 1].Value.ToString());
                            linha++;
                        }

                        var listFromTabela = _apontamentoService.GetAll();

                        foreach (string item in listFromPlanilha)
                        {
                            Apontamento apontamento = listFromTabela.Where(o => o.NumeroSerie == item).FirstOrDefault();
                            listaRetorno.Add(item, apontamento == null ? "Número de Série desconhecido. Sequencial não relacionado ao serial pesquisado." : apontamento.Sequencial);
                        }

                        //string download = "RelatorioSerialXSequencial_" + DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss.ffff") + ".xlsx";
                        //string writeFileName = Server.MapPath("~/Temp") + "\\" + download;
                        //string writeFileTemplate = Server.MapPath("~/Templates/RelatorioSerialXSequencial.xlsx");

                        //System.IO.File.Copy(writeFileTemplate, writeFileName);
                        //System.IO.File.SetAttributes(writeFileName, FileAttributes.Normal);

                        //ExcelPackage package = new ExcelPackage(new FileInfo(writeFileName));
                        //ExcelWorksheet writeFileWorksheet = package.Workbook.Worksheets["SerialXSequencial"];

                        //linha = 2;
                        //foreach (var item in listaRetorno)
                        //{
                        //    coluna = 1;
                        //    writeFileWorksheet.Cells[linha, coluna++].Value = item.Key;
                        //    writeFileWorksheet.Cells[linha, coluna++].Value = item.Value;
                        //    linha++;
                        //}

                        //return File(package.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", download);

                        System.GC.Collect();

                        StringBuilder builder = new StringBuilder();
                        builder.Append("Numero de Serie;Sequencial\n");

                        List <string> rows = new List <string>();
                        foreach (var item in listaRetorno)
                        {
                            rows.Add(item.Key + ";" + item.Value);
                        }

                        builder.Append(string.Join("\n", rows.ToArray()));

                        Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
                        Response.Clear();
                        Response.ContentType = "text/csv";
                        Response.AddHeader("Content-Disposition", "attachment;filename=RelatorioSerialXSequencial_" + DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss.ffff") + ".csv");
                        Response.Write(builder.ToString());
                        Response.End();

                        System.GC.Collect();
                    }
                    catch (Exception ex)
                    {
                        TempData["MensagemErro"] = "Ocorreu um erro na geração ou na importação do arquivo. " + ex.InnerException;
                    }
                    System.IO.File.Delete(readFilePath);
                }
                else
                {
                    TempData["MensagemErro"] = "O arquivo está vazio.";
                }
                return(RedirectToAction("ComCargaPlanilha", "Relatorio"));
            }
            catch (Exception)
            {
                TempData["MensagemErro"] = "Selecione um arquivo válido.";
                return(RedirectToAction("ComCargaPlanilha", "Relatorio"));
            }
        }
Пример #25
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"));
        }