예제 #1
0
    def evento_campos(self, ovr, ind=1):
        """Retorna campos do evento -ind da ovr

        :param ovr: OVR
        :param ind: índice inverso (1 último, 2 penúltimo, etc)
        :return: evento_user_descricao: Nome do Usuário do Evento,
                tipo_evento_nome: Nome do Tipo de Evento,
                 data_evento: Data de ocorrência do Evento
        """
        tipo_evento_nome = ''
        data_evento = ovr.create_date
        evento_user_descricao = ''
        motivo = ''
        ind_aux = ind
        if len(ovr.historico) >= ind:
            while ovr.historico[len(ovr.historico) - ind].meramente_informativo or \
                    'ição' in ovr.historico[len(ovr.historico) - ind].tipoevento.nome:
                ind += 1
                if ind >= len(ovr.historico):
                    break
            if ind >= len(ovr.historico):
                ind = ind_aux
            evento_atual = ovr.historico[len(ovr.historico) - ind]
            if evento_atual.user_name:
                usuario_evento = get_usuario(self.session,
                                             evento_atual.user_name)
                if usuario_evento:
                    evento_user_descricao = usuario_evento.nome
                else:
                    evento_user_descricao = evento_atual.user_name
            tipo_evento_nome = evento_atual.tipoevento.nome
            data_evento = evento_atual.create_date
            motivo = evento_atual.motivo
        return evento_user_descricao, tipo_evento_nome, data_evento, motivo, ind
예제 #2
0
 def auto_contrafacao():
     session = app.config['dbsession']
     db = app.config['mongo_risco']
     ovr_id = None
     tg_id = request.args.get('tg_id')
     try:
         usuario = get_usuario(session, current_user.name)
         if usuario is None:
             raise Exception('Erro: Usuário não encontrado!')
         if tg_id:
             tg = get_tgovr_one(session, tg_id)
             ovr_id = tg.ovr_id
             ovr_dict = OVRDict(FonteDocx.TG_Ficha).get_dict(
                 db=db, session=session, id=tg.id)
             if ovr_dict:
                 document = gera_auto_contrafacao(ovr_dict, current_user.name)
                 nome = 'Auto de Infração'
                 out_filename = '{}_{}_{}.docx'.format(
                     nome,
                     ovr_id,
                     datetime.strftime(datetime.now(), '%Y-%m-%dT%H-%M-%S')
                 )
                 document.save(os.path.join(
                     get_user_save_path(), out_filename))
                 return redirect('static/%s/%s' % (current_user.name, out_filename))
     except Exception as err:
         logger.error(err, exc_info=True)
         flash('Erro! Detalhes no log da aplicação.')
         flash(str(type(err)))
         flash(str(err))
     return redirect(url_for('autos_contrafacao', ovr_id=ovr_id))
예제 #3
0
 def usuario_name(self, user_name):
     user_descricao = ''
     if user_name:
         usuario = get_usuario(self.session, user_name)
         if usuario:
             user_descricao = usuario.nome
         else:
             user_descricao = user_name
     return user_descricao
예제 #4
0
 def autos_contrafacao():
     session = app.config['dbsession']
     # db = app.config['mongo_risco']
     listafichasresumo = []
     ovr = None
     rvfs = []
     marcas_dict = {}
     supervisor = False
     exibicao_ovr = ExibicaoOVR(session, TipoExibicao.Descritivo, current_user.name)
     titulos = exibicao_ovr.get_titulos()
     evento_form = HistoricoOVRForm()
     title_page = 'Assistente de Contrafação'
     try:
         usuario = get_usuario(session, current_user.name)
         if usuario is None:
             raise Exception('Erro: Usuário não encontrado!')
         flags = get_ids_flags_contrafacao(session)
         supervisor = usuario_tem_perfil_nome(session, current_user.name, 'Supervisor')
         listafichas = get_ovrs_abertas_flags(session, current_user.name, flags)
         print('*************************', len(listafichas))
         for ovr_linha in listafichas:
             resumo = exibicao_ovr.get_linha(ovr_linha)
             listafichasresumo.append(resumo)
         ovr_id = request.args.get('ovr_id')
         if ovr_id:
             ovr = get_ovr(session, ovr_id)
             tiposevento = get_tiposevento_assistente_choice(session, Assistente.Marcas)
             evento_form = HistoricoOVRForm(ovr_id=ovr_id,
                                            tiposeventos=tiposevento,
                                            responsaveis=[usuario.cpf])
             rvfs = lista_rvfovr(session, ovr_id)
             marca_manager = MarcaManager(session)
             for rvf in rvfs:
                 marca_dict = marca_manager.get_marcas_rvf_por_representante(rvf.id)
                 marcas_dict.update(marca_dict)
     except Exception as err:
         logger.error(err, exc_info=True)
         flash('Erro! Detalhes no log da aplicação.')
         flash(str(type(err)))
         flash(str(err))
     return render_template('autos_contrafeitos.html',
                            titulos=titulos,
                            listaovrs=listafichasresumo,
                            marcas_dict=marcas_dict,
                            ovr=ovr,
                            rvfs=rvfs,
                            supervisor=supervisor,
                            evento_form=evento_form,
                            title_page=title_page)
예제 #5
0
 def monta_ovr_dict(self,
                    db,
                    session,
                    id: int,
                    explode=True,
                    rvfs=True,
                    imagens=True) -> dict:
     """Retorna um dicionário com conteúdo do OVR, inclusive imagens."""
     ovr = get_ovr_one(session, id)
     ovr_dict = ovr.dump(explode=explode)
     if rvfs:
         lista_rvfs = session.query(RVF).filter(RVF.ovr_id == id).all()
         rvfs_dicts = [rvf.dump(explode=True) for rvf in lista_rvfs]
         ovr_dict['rvfs'] = rvfs_dicts
         try:
             empresa = get_empresa(session, ovr.cnpj_fiscalizado)
             if empresa:
                 ovr_dict['nome_fiscalizado'] = empresa.nome
         except ValueError:
             ovr_dict['nome_fiscalizado'] = ''
         usuario = get_usuario(session, ovr.cpfauditorresponsavel)
         if usuario:
             ovr_dict['nome_auditorresponsavel'] = usuario.nome
             ovr_dict['auditor_responsavel'] = usuario.nome
         ovr_dict['marcas'] = []
         descricoes = []
         for rvf_dict in rvfs_dicts:
             ovr_dict['marcas'].extend(rvf_dict['marcasencontradas'])
             if rvf_dict['descricao']:
                 descricoes.append(rvf_dict['descricao'])
         ovr_dict['descricao_mercadoria'] = ' '.join(descricoes)
         ovr_dict['marcas'] = ', '.join(ovr_dict['marcas'])
         if imagens:
             lista_imagens = []
             for rvf_dict in rvfs_dicts:
                 # Garantir que as imagens sigam a ordem definida pelo usuário na exbibição
                 imagens_rvf = sorted(rvf_dict['imagens'],
                                      key=lambda x: x['ordem'])
                 for imagem_dict in imagens_rvf:
                     image = mongo_image(db, imagem_dict['imagem'])
                     imagem_dict['content'] = io.BytesIO(image)
                     lista_imagens.append(imagem_dict)
             ovr_dict['imagens'] = lista_imagens
         for processo in ovr.processos:
             ovr_dict['processo_%s' %
                      processo.tipoprocesso.descricao] = processo.numero
     return ovr_dict
예제 #6
0
 def comunicado_contrafacao():
     print(request.url)
     session = app.config['dbsession']
     db = app.config['mongo_risco']
     ovr_id = request.args.get('ovr_id')
     representante_id = request.args.get('representante_id')
     try:
         usuario = get_usuario(session, current_user.name)
         if usuario is None:
             raise Exception('Erro: Usuário não encontrado!')
         if ovr_id:
             try:
                 ovr_dicts = OVRDict(FonteDocx.Marcas).get_dict(
                     db=db, session=session, id=ovr_id)
             except NoResultFound:
                 raise NoResultFound(f'Marcas não encontradas para Ficha {ovr_id}.')
             if len(ovr_dicts) == 0:
                 raise NoResultFound(f'Marcas não encontradas na ovr {ovr_id}.')
             logger.info('Gerando marcas')
             document = None
             representante_id2 = None
             for ovr_dict in ovr_dicts:
                 representante_id2 = ovr_dict.get('representante_id')
                 representante_nome = ovr_dict.get('representante_nome')
                 if representante_id2 and (str(representante_id2) == representante_id):
                     document = gera_comunicado_contrafacao(ovr_dict, current_user.name,
                                                            'termo' in request.url)
                     break
             if representante_id2 and document:
                 nome = 'Comunicado_de_Contrafacao'
                 if 'termo' in request.url:
                     nome = 'Termo de retirada de amostras'
                 out_filename = '{}_{}_{}_{}.docx'.format(
                     nome,
                     ovr_id,
                     representante_nome,
                     datetime.strftime(datetime.now(), '%Y-%m-%dT%H-%M-%S')
                 )
                 document.save(os.path.join(
                     get_user_save_path(), out_filename))
                 return redirect('static/%s/%s' % (current_user.name, out_filename))
     except Exception as err:
         logger.error(err, exc_info=True)
         flash('Erro! Detalhes no log da aplicação.')
         flash(str(type(err)))
         flash(str(err))
     return redirect(url_for('autos_contrafacao', ovr_id=ovr_id))
예제 #7
0
 def monta_rvf_dict(self,
                    db,
                    session,
                    id: int,
                    explode=True,
                    imagens=True) -> dict:
     """Retorna um dicionário com conteúdo do RVF, inclusive imagens."""
     rvf = get_rvf_one(session, id)
     rvf_dump = rvf.dump(explode=explode, imagens=imagens)
     ovr = rvf.ovr
     rvf_dump['rvf_id'] = id
     if ovr.cpfauditorresponsavel:
         usuario = get_usuario(session, ovr.cpfauditorresponsavel)
         if usuario:
             rvf_dump['auditor_responsavel'] = usuario.nome
     if ovr.responsavel:
         rvf_dump['responsavel'] = ovr.responsavel.nome
     if ovr.recinto:
         rvf_dump['recinto'] = ovr.recinto.nome
     if ovr.setor:
         rvf_dump['setor'] = ovr.setor.nome
     exibicao = ExibicaoOVR(session, 1, '')
     if ovr.numerodeclaracao:
         due = get_due(db, ovr.numerodeclaracao)
         due_str = ''
         for k, v in due.items():
             due_str = f'{k}: {v}\n'
         rvf_dump['resumo_due'] = due_str
     if ovr.numeroCEmercante:
         if exibicao.get_mercante_resumo(ovr):
             porto_origem = exibicao.get_mercante_resumo(ovr)[2][24:]
             porto_destino = exibicao.get_mercante_resumo(ovr)[3][31:]
             rvf_dump['porto_origem'] = porto_origem
             rvf_dump['porto_destino'] = porto_destino
         resumo_mercante = exibicao.get_mercante_resumo(ovr)
         resumo_mercante = '\n'.join(resumo_mercante)
         resumo_mercante = re.sub(re.compile('<.*?>'), ' ', resumo_mercante)
         rvf_dump['resumo_mercante'] = resumo_mercante
     imagens_rvf = sorted(rvf_dump['imagens'], key=lambda x: x['ordem'])
     lista_imagens = []
     for imagem_dict in imagens_rvf:
         image = mongo_image(db, imagem_dict['imagem'])
         imagem_dict['content'] = io.BytesIO(image)
         lista_imagens.append(imagem_dict)
     rvf_dump['imagens'] = lista_imagens
     return rvf_dump
예제 #8
0
def index():
    """View retorna index.html ou login se não autenticado."""
    if current_user.is_authenticated:
        session = app.config.get('dbsession')
        datas_objective = ''
        ovrs = get_ovr_responsavel(session, current_user.id)
        liberadas = sum([ovr.fase == 0 for ovr in ovrs])
        ativas = sum([ovr.fase == 1 for ovr in ovrs])
        supensas = sum([ovr.fase == 2 for ovr in ovrs])
        df = pd.DataFrame({
            'Fase': ['Liberada', 'Ativa', 'Suspensa'],
            'Qtde': [liberadas, ativas, supensas],
        })
        fig = make_subplots(rows=2,
                            cols=3,
                            horizontal_spacing=0.1,
                            specs=[[{
                                "type": "pie"
                            }, {
                                "type": "indicator"
                            }, {
                                "type": "indicator"
                            }],
                                   [{
                                       "type": "indicator"
                                   }, {
                                       "type": "indicator"
                                   }, {
                                       "type": "indicator"
                                   }]])
        fichas_pie = go.Pie(labels=df.Fase.values,
                            values=df.Qtde.values,
                            textinfo='label+value',
                            insidetextorientation='radial',
                            title='Resumo das minhas Fichas')
        row = 1
        col = 1
        fig.add_trace(fichas_pie, row=row, col=col)
        usuario = get_usuario(session, current_user.name)
        setor_id = usuario.setor_id
        objective = session.query(OKRObjective).filter(OKRObjective.setor_id == setor_id). \
            order_by(OKRObjective.id.desc()).first()
        if not objective:
            setor = session.query(Setor).filter(Setor.id == setor_id).one()
            if setor.pai_id:
                objective = session.query(OKRObjective).filter(OKRObjective.setor_id == setor.pai_id). \
                    order_by(OKRObjective.id.desc()).first()
        if objective:
            results = executa_okr_results(session, objective)
            for result in results[:5]:
                delta = ((date.today() - objective.inicio.date()) /
                         (objective.fim - objective.inicio)) * result.ameta
                indicator = gauge_plotly(
                    result.result.nome, result.ameta,
                    sum([row['result'] for row in result.resultados]), delta)
                col += 1
                if col > 3:
                    col = 1
                    row += 1
                fig.add_trace(indicator, row=row, col=col)
        fig.update_layout(
            # grid={'rows': 2, 'columns': 3, 'pattern': "independent"},
            margin=dict(r=0, t=0, b=0, l=0), )
        fig.update(layout_showlegend=False)
        graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
        return render_template('index.html',
                               plots=[],
                               objective=objective,
                               graphJSON=graphJSON)
    else:
        return redirect(url_for('commons.login'))
예제 #9
0
    def rvf():
        session = app.config.get('dbsession')
        get_usuario_validando(session, current_user.id)
        tiposapreensao = get_tiposapreensao_choice(session)
        apreensao_form = ApreensaoRVFForm(tiposapreensao=tiposapreensao)
        apreensoes_rvf = []
        infracoes = []
        infracoes_encontradas = []
        marcas = []
        marcas_encontradas = []
        anexos = []
        lacres_verificados = []
        arvf = None
        rvf_form = RVFForm()
        title_page = 'RVF'
        try:
            if request.method == 'POST':
                rvf_form = RVFForm(request.form)
                rvf_form.adata.data = request.form['adata']
                rvf_form.ahora.data = request.form['ahora']
                rvf_form.validate()
                arvf = cadastra_rvf(session,
                                    user_name=current_user.name,
                                    params=dict(rvf_form.data.items()))
                session.refresh(arvf)
                return redirect(url_for('rvf', id=arvf.id))
            # ELSE
            ovr_id = request.args.get('ovr')
            if ovr_id is not None:
                arvf = cadastra_rvf(session, ovr_id=ovr_id,
                                    user_name=current_user.name)
                session.refresh(arvf)
                return redirect(url_for('rvf', id=arvf.id))
            # ELSE
            db = app.config['mongo_risco']
            marcas = get_marcas(session)
            infracoes = get_infracoes(session)
            rvf_id = request.args.get('id')
            title_page = 'RVF ' + rvf_id
            if rvf_id is not None:
                arvf = get_rvf(session, rvf_id)
                print('arvf.inspecaonaoinvasiva', arvf.inspecaonaoinvasiva)
            if arvf is not None:
                rvf_form = RVFForm(**arvf.__dict__)
                if arvf.datahora:
                    rvf_form.adata.data = arvf.datahora.date()
                    rvf_form.ahora.data = arvf.datahora.time()
                rvf_form.id.data = arvf.id
                rvf_form.peso_manifestado.data = get_peso(session,
                                                          rvf_form.numeroCEmercante.data,
                                                          rvf_form.numerolote.data)
                apreensoes_rvf = arvf.apreensoes
                infracoes_encontradas = arvf.infracoesencontradas
                marcas_encontradas = arvf.marcasencontradas
                lacres_verificados = arvf.lacresverificados
                # Temporário - para recuperar imagens 'perdidas' na transição
                ressuscita_anexos_perdidos(db, session, arvf)
                anexos = get_ids_anexos_ordenado(arvf)
                usuario = get_usuario(session, arvf.user_name)
                if usuario:
                    rvf_form.user_descricao.data = usuario.nome

        except Exception as err:
            logger.error(err, exc_info=True)
            flash('Erro! Detalhes no log da aplicação.')
            flash(str(type(err)))
            flash(str(err))
        return render_template('rvf.html',
                               infracoes=infracoes,
                               marcas=marcas,
                               oform=rvf_form,
                               apreensao_form=apreensao_form,
                               apreensoes=apreensoes_rvf,
                               infracoes_encontradas=infracoes_encontradas,
                               marcas_encontradas=marcas_encontradas,
                               lacres_verificados=lacres_verificados,
                               anexos=anexos,
                               title_page=title_page)
예제 #10
0
 def encerramento_ovr():
     session = app.config.get('dbsession')
     ovr_id = request.args.get('ovr_id')
     ovr = get_ovr(session=session, ovr_id=ovr_id)
     operacao = ovr.get_tipooperacao()
     tiposprocesso = get_tipos_processo(session=session)
     processo_form = ProcessoOVRForm(tiposprocesso=tiposprocesso)
     tiposeventos = get_tipos_evento_comfase_choice(session=session)
     historico_form = HistoricoOVRForm(tiposeventos=tiposeventos)
     data_encerramento = datetime.now().strftime('%d/%m/%Y')
     title_page = 'Encerramento'
     fase = 0
     usuario = ''
     auditor = ''
     empresa = ''
     processos = []
     eventos = []
     resultados = []
     lista_de_tgs_items = []
     lista_de_rvfs_apreensoes = []
     total_apreensoes = []
     total_tgs = []
     try:
         lista_de_tgs_items, total_tgs = lista_de_tgs_e_items(session, ovr_id)
         if total_tgs.get('valor_total', 0) != 0:
             print('Tem TGs')
             resultado = session.query(ResultadoOVR). \
                 filter(ResultadoOVR.ovr_id == ovr.id). \
                 filter(ResultadoOVR.tipo_resultado == TipoResultado.Perdimento.value).one_or_none()
             if resultado is None:
                 print('Inclui resultado')
                 resultado = ResultadoOVR()
                 resultado.ovr_id = ovr.id
                 resultado.tipo_resultado = TipoResultado.Perdimento.value
                 resultado.cpf_auditor = ovr.cpfauditorresponsavel
             resultado.valor = total_tgs['valor_total']
             session.add(resultado)
             session.commit()
             print(f'Valor resultado {resultado.valor}')
         lista_de_rvfs_apreensoes, total_apreensoes = lista_de_rvfs_e_apreensoes(session, ovr_id)
         total_apreensoes_geral = 0
         if total_apreensoes:
             total_apreensoes_geral = sum([valor for valor in total_apreensoes.values()])
         if total_apreensoes_geral != 0:
             print('Tem Apreensoes')
             resultado = session.query(ResultadoOVR). \
                 filter(ResultadoOVR.ovr_id == ovr.id). \
                 filter(ResultadoOVR.tipo_resultado == TipoResultado.Apreensao.value).one_or_none()
             if resultado is None:
                 resultado = ResultadoOVR()
                 resultado.ovr_id = ovr.id
                 resultado.tipo_resultado = TipoResultado.Apreensao.value
                 resultado.cpf_auditor = ovr.cpfauditorresponsavel
             resultado.valor = total_apreensoes_geral
             session.add(resultado)
             session.commit()
         session.refresh(ovr)
         fase = ovr.get_fase()
         usuario = get_usuario(session, current_user.name)
         auditor = get_usuario(session, ovr.cpfauditorresponsavel)
         if ovr.cnpj_fiscalizado:
             empresa = get_empresa(session=session, cnpj=ovr.cnpj_fiscalizado)
         else:
             empresa = ''
         processos = ovr.processos
         eventos = ovr.historico
         resultados = ovr.resultados
         if usuario is None:
             raise Exception('Erro: Usuário não encontrado!')
     except Exception as err:
         logger.error(err, exc_info=True)
         flash('Erro! Detalhes no log da aplicação.')
         flash(str(type(err)))
         flash(str(err))
     return render_template('encerramento_ovr.html',
                            ovr=ovr,
                            fase=fase,
                            usuario=usuario,
                            auditor=auditor,
                            empresa=empresa,
                            processos=processos,
                            eventos=eventos,
                            resultados=resultados,
                            processo_form=processo_form,
                            operacao=operacao,
                            historico_form=historico_form,
                            lista_de_tgs_items=lista_de_tgs_items,
                            lista_de_rvfs_apreensoes=lista_de_rvfs_apreensoes,
                            total_apreensoes=total_apreensoes,
                            total_tgs=total_tgs,
                            data_encerramento=data_encerramento,
                            title_page=title_page)