Ejemplo n.º 1
0
def salvar(request, hash):
    from emensageriapro.settings import VERSAO_EMENSAGERIA, VERSAO_LAYOUT_EFDREINF, TP_AMB
    db_slug = 'default'
    try:
        usuario_id = request.user.id
        dict_hash = get_hash_url( hash )
        r2010_evtservtom_id = int(dict_hash['id'])
        if 'tab' not in dict_hash.keys():
            dict_hash['tab'] = ''
        for_print = int(dict_hash['print'])
    except:
        usuario_id = False
        return redirect('login')
    usuario = get_object_or_404(Usuarios.objects.using( db_slug ), excluido = False, id = usuario_id)
    pagina = ConfigPaginas.objects.using( db_slug ).get(excluido = False, endereco='r2010_evtservtom')
    permissao = ConfigPermissoes.objects.using( db_slug ).get(excluido = False, config_paginas=pagina, config_perfis=usuario.config_perfis)
    if r2010_evtservtom_id:
        r2010_evtservtom = get_object_or_404(r2010evtServTom.objects.using( db_slug ), excluido = False, id = r2010_evtservtom_id)
    dict_permissoes = json_to_dict(usuario.config_perfis.permissoes)
    paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas
    modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos

    if r2010_evtservtom_id:
        if r2010_evtservtom.status != 0:
            dict_permissoes['r2010_evtservtom_apagar'] = 0
            dict_permissoes['r2010_evtservtom_editar'] = 0

    if permissao.permite_visualizar:
        mensagem = None
        if r2010_evtservtom_id:
            r2010_evtservtom_form = form_r2010_evtservtom(request.POST or None, instance = r2010_evtservtom, slug = db_slug)
        else:
            r2010_evtservtom_form = form_r2010_evtservtom(request.POST or None, slug = db_slug, initial={'versao': VERSAO_LAYOUT_EFDREINF, 'status': 0, 'processamento_codigo_resposta': 0, 'tpamb': TP_AMB, 'procemi': 1, 'verproc': VERSAO_EMENSAGERIA})
        if request.method == 'POST':
            if r2010_evtservtom_form.is_valid():
                dados = r2010_evtservtom_form.cleaned_data
                import json
                from django.forms.models import model_to_dict
                if r2010_evtservtom_id:
                    if r2010_evtservtom.status == 0:
                        dados['modificado_por_id'] = usuario_id
                        dados['modificado_em'] = datetime.datetime.now()
                        #r2010_evtservtom_campos_multiple_passo1
                        r2010evtServTom.objects.using(db_slug).filter(id=r2010_evtservtom_id).update(**dados)
                        obj = r2010evtServTom.objects.using(db_slug).get(id=r2010_evtservtom_id)
                        #r2010_evtservtom_editar_custom
                        #r2010_evtservtom_campos_multiple_passo2
                        messages.success(request, 'Alterado com sucesso!')
                        gravar_auditoria(json.dumps(model_to_dict(r2010_evtservtom), indent=4, sort_keys=True, default=str),
                                         json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str),
                                         'r2010_evtservtom', r2010_evtservtom_id, usuario_id, 2)
                    else:
                        obj = r2010evtServTom.objects.using(db_slug).get(id=r2010_evtservtom_id)
                        messages.error(request, 'Não é possível salvar o evento, pois o mesmo não está com o status "Cadastrado"!')

                else:

                    dados['criado_por_id'] = usuario_id
                    dados['criado_em'] = datetime.datetime.now()
                    dados['excluido'] = False
                    #r2010_evtservtom_cadastrar_campos_multiple_passo1
                    obj = r2010evtServTom(**dados)
                    obj.save(using = db_slug)
                    #r2010_evtservtom_cadastrar_custom
                    #r2010_evtservtom_cadastrar_campos_multiple_passo2
                    identidade_evento(obj.id, db_slug)
                    messages.success(request, 'Cadastrado com sucesso!')
                    r2010_evtservtom_form = form_r2010_evtservtom(request.POST or None, instance = obj, slug = db_slug)
                    gravar_auditoria('{}',
                                     json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str),
                                     'r2010_evtservtom', obj.id, usuario_id, 1)
                if request.session['retorno_pagina'] not in ('r2010_evtservtom_apagar', 'r2010_evtservtom_salvar', 'r2010_evtservtom'):
                    return redirect(request.session['retorno_pagina'], hash=request.session['retorno_hash'])
                if r2010_evtservtom_id != obj.id:
                    url_hash = base64.urlsafe_b64encode( '{"print": "0", "id": "%s"}' % (obj.id) )
                    return redirect('r2010_evtservtom_salvar', hash=url_hash)

            else:
                messages.error(request, 'Erro ao salvar!')
        r2010_evtservtom_form = disabled_form_fields(r2010_evtservtom_form, permissao.permite_editar)

        if r2010_evtservtom_id:
            if r2010_evtservtom.status != 0:
                r2010_evtservtom_form = disabled_form_fields(r2010_evtservtom_form, False)
        #r2010_evtservtom_campos_multiple_passo3

        for field in r2010_evtservtom_form.fields.keys():
            r2010_evtservtom_form.fields[field].widget.attrs['ng-model'] = 'r2010_evtservtom_'+field
        if int(dict_hash['print']):
            r2010_evtservtom_form = disabled_form_for_print(r2010_evtservtom_form)

        r2010_nfs_form = None
        r2010_nfs_lista = None
        r2010_infoprocretpr_form = None
        r2010_infoprocretpr_lista = None
        r2010_infoprocretad_form = None
        r2010_infoprocretad_lista = None
        if r2010_evtservtom_id:
            r2010_evtservtom = get_object_or_404(r2010evtServTom.objects.using( db_slug ), excluido = False, id = r2010_evtservtom_id)

            r2010_nfs_form = form_r2010_nfs(initial={ 'r2010_evtservtom': r2010_evtservtom }, slug=db_slug)
            r2010_nfs_form.fields['r2010_evtservtom'].widget.attrs['readonly'] = True
            r2010_nfs_lista = r2010nfs.objects.using( db_slug ).filter(excluido = False, r2010_evtservtom_id=r2010_evtservtom.id).all()
            r2010_infoprocretpr_form = form_r2010_infoprocretpr(initial={ 'r2010_evtservtom': r2010_evtservtom }, slug=db_slug)
            r2010_infoprocretpr_form.fields['r2010_evtservtom'].widget.attrs['readonly'] = True
            r2010_infoprocretpr_lista = r2010infoProcRetPr.objects.using( db_slug ).filter(excluido = False, r2010_evtservtom_id=r2010_evtservtom.id).all()
            r2010_infoprocretad_form = form_r2010_infoprocretad(initial={ 'r2010_evtservtom': r2010_evtservtom }, slug=db_slug)
            r2010_infoprocretad_form.fields['r2010_evtservtom'].widget.attrs['readonly'] = True
            r2010_infoprocretad_lista = r2010infoProcRetAd.objects.using( db_slug ).filter(excluido = False, r2010_evtservtom_id=r2010_evtservtom.id).all()
        else:
            r2010_evtservtom = None
        #r2010_evtservtom_salvar_custom_variaveis#
        tabelas_secundarias = []
        #[FUNCOES_ESPECIAIS_SALVAR]
        if 'r2010_evtservtom'[1] == '5':
            evento_totalizador = True
        else:
            evento_totalizador = False
        if not evento_totalizador:
            r2010_evtservtom_form.fields['tpamb'].widget.attrs['disabled'] = True
            r2010_evtservtom_form.fields['tpamb'].widget.attrs['readonly'] = True
            r2010_evtservtom_form.fields['tpamb'].value = TP_AMB
            r2010_evtservtom_form.fields['procemi'].widget.attrs['disabled'] = True
            r2010_evtservtom_form.fields['procemi'].widget.attrs['readonly'] = True
            r2010_evtservtom_form.fields['procemi'].value = 1
            r2010_evtservtom_form.fields['verproc'].widget.attrs['readonly'] = True
            r2010_evtservtom_form.fields['verproc'].value = VERSAO_EMENSAGERIA

        if dict_hash['tab'] or 'r2010_evtservtom' in request.session['retorno_pagina']:
            request.session["retorno_hash"] = hash
            request.session["retorno_pagina"] = 'r2010_evtservtom_salvar'
        controle_alteracoes = Auditoria.objects.using( db_slug ).filter(identidade=r2010_evtservtom_id, tabela='r2010_evtservtom').all()
        context = {
            'evento_totalizador': evento_totalizador,
            'controle_alteracoes': controle_alteracoes,
            'r2010_evtservtom': r2010_evtservtom,
            'r2010_evtservtom_form': r2010_evtservtom_form,
            'mensagem': mensagem,
            'r2010_evtservtom_id': int(r2010_evtservtom_id),
            'usuario': usuario,
  
            'hash': hash,

            'r2010_nfs_form': r2010_nfs_form,
            'r2010_nfs_lista': r2010_nfs_lista,
            'r2010_infoprocretpr_form': r2010_infoprocretpr_form,
            'r2010_infoprocretpr_lista': r2010_infoprocretpr_lista,
            'r2010_infoprocretad_form': r2010_infoprocretad_form,
            'r2010_infoprocretad_lista': r2010_infoprocretad_lista,
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
  
            'permissao': permissao,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
            'for_print': int(dict_hash['print']),
            'tabelas_secundarias': tabelas_secundarias,
            'tab': dict_hash['tab'],
            #r2010_evtservtom_salvar_custom_variaveis_context#
        }

        if for_print in (0,1 ):
            return render(request, 'r2010_evtservtom_salvar.html', context)
        elif for_print == 2:
            from wkhtmltopdf.views import PDFTemplateResponse
            response = PDFTemplateResponse(
                request=request,
                template='r2010_evtservtom_salvar.html',
                filename="r2010_evtservtom.pdf",
                context=context,
                show_content_in_browser=True,
                cmd_options={'margin-top': 10,
                             'margin-bottom': 10,
                             'margin-right': 10,
                             'margin-left': 10,
                             'zoom': 1,
                             'dpi': 72,
                             'orientation': 'Landscape',
                             "viewport-size": "1366 x 513",
                             'javascript-delay': 1000,
                             'footer-center': '[page]/[topage]',
                             "no-stop-slow-scripts": True},
            )
            return response
        elif for_print == 3:
            from django.shortcuts import render_to_response
            response = render_to_response('r2010_evtservtom_salvar.html', context)
            filename = "r2010_evtservtom.xls"
            response['Content-Disposition'] = 'attachment; filename=' + filename
            response['Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8'
            return response
    else:
        context = {
            'usuario': usuario,
  
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
  
            'permissao': permissao,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
        }
        return render(request, 'permissao_negada.html', context)
Ejemplo n.º 2
0
def salvar(request, pk=None, tab='master', output=None):

    from emensageriapro.efdreinf.models import STATUS_EVENTO_CADASTRADO
    from emensageriapro.settings import VERSAO_EMENSAGERIA, VERSAO_LAYOUT_EFDREINF
    TP_AMB = config.EFDREINF_TP_AMB

    if pk:

        r2010_evtservtom = get_object_or_404(r2010evtServTom, id=pk)

    if request.user.has_perm('efdreinf.can_see_r2010evtServTom'):

        if pk:

            r2010_evtservtom_form = form_r2010_evtservtom(
                request.POST or None,
                instance=r2010_evtservtom,
                initial={'ativo': True})

        else:

            r2010_evtservtom_form = form_r2010_evtservtom(
                request.POST or None,
                initial={
                    'versao': VERSAO_LAYOUT_EFDREINF,
                    'status': STATUS_EVENTO_CADASTRADO,
                    'tpamb': TP_AMB,
                    'procemi': 1,
                    'verproc': VERSAO_EMENSAGERIA,
                    'ativo': True
                })

        if request.method == 'POST':

            if r2010_evtservtom_form.is_valid():

                obj = r2010_evtservtom_form.save(request=request)
                messages.success(request, u'Salvo com sucesso!')

                if not pk:

                    from emensageriapro.functions import identidade_evento
                    identidade_evento(obj, 'efdreinf')

                if 'return_page' in request.session and request.session[
                        'return_page'] and 'r2010-evtservtom' not in request.session[
                            'return_page']:

                    return HttpResponseRedirect(request.session['return_page'])

                if pk != obj.id:

                    return redirect('r2010_evtservtom_salvar', pk=obj.id)

            else:
                messages.error(request, u'Erro ao salvar!')

        r2010_evtservtom_form = disabled_form_fields(
            r2010_evtservtom_form,
            request.user.has_perm('efdreinf.change_r2010evtServTom'))

        if pk:

            if r2010_evtservtom.status != 0:

                r2010_evtservtom_form = disabled_form_fields(
                    r2010_evtservtom_form, False)

        for field in r2010_evtservtom_form.fields.keys():

            r2010_evtservtom_form.fields[field].widget.attrs[
                'ng-model'] = 'r2010_evtservtom_' + field

        if output:

            r2010_evtservtom_form = disabled_form_for_print(
                r2010_evtservtom_form)

        r2010_nfs_lista = None
        r2010_nfs_form = None
        r2010_infoprocretpr_lista = None
        r2010_infoprocretpr_form = None
        r2010_infoprocretad_lista = None
        r2010_infoprocretad_form = None

        if pk:

            r2010_evtservtom = get_object_or_404(r2010evtServTom, id=pk)

            r2010_nfs_form = form_r2010_nfs(
                initial={'r2010_evtservtom': r2010_evtservtom})
            r2010_nfs_form.fields['r2010_evtservtom'].widget.attrs[
                'readonly'] = True
            r2010_nfs_lista = r2010nfs.objects.\
                filter(r2010_evtservtom_id=r2010_evtservtom.id).all()
            r2010_infoprocretpr_form = form_r2010_infoprocretpr(
                initial={'r2010_evtservtom': r2010_evtservtom})
            r2010_infoprocretpr_form.fields['r2010_evtservtom'].widget.attrs[
                'readonly'] = True
            r2010_infoprocretpr_lista = r2010infoProcRetPr.objects.\
                filter(r2010_evtservtom_id=r2010_evtservtom.id).all()
            r2010_infoprocretad_form = form_r2010_infoprocretad(
                initial={'r2010_evtservtom': r2010_evtservtom})
            r2010_infoprocretad_form.fields['r2010_evtservtom'].widget.attrs[
                'readonly'] = True
            r2010_infoprocretad_lista = r2010infoProcRetAd.objects.\
                filter(r2010_evtservtom_id=r2010_evtservtom.id).all()

        else:

            r2010_evtservtom = None

        tabelas_secundarias = []

        controle_alteracoes = Auditoria.objects.filter(
            identidade=pk, tabela='r2010_evtservtom').all()

        if not request.POST:
            request.session['return_page'] = request.META.get('HTTP_REFERER')

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'pk': pk,
            'output': output,
            'evento_totalizador': False,
            'controle_alteracoes': controle_alteracoes,
            'r2010_evtservtom': r2010_evtservtom,
            'r2010_evtservtom_form': r2010_evtservtom_form,
            'r2010_nfs_form': r2010_nfs_form,
            'r2010_nfs_lista': r2010_nfs_lista,
            'r2010_infoprocretpr_form': r2010_infoprocretpr_form,
            'r2010_infoprocretpr_lista': r2010_infoprocretpr_lista,
            'r2010_infoprocretad_form': r2010_infoprocretad_form,
            'r2010_infoprocretad_lista': r2010_infoprocretad_lista,
            'data': datetime.datetime.now(),
            'modulos': [
                'efdreinf',
            ],
            'paginas': [
                'r2010_evtservtom',
            ],
            'tabelas_secundarias': tabelas_secundarias,
            'tab': tab,
        }

        if output == 'pdf':

            response = PDFTemplateResponse(
                request=request,
                template='r2010_evtservtom_salvar.html',
                filename="r2010_evtservtom.pdf",
                context=context,
                show_content_in_browser=True,
                cmd_options={
                    'margin-top': 10,
                    'margin-bottom': 10,
                    'margin-right': 10,
                    'margin-left': 10,
                    'zoom': 1,
                    'dpi': 72,
                    'orientation': 'Landscape',
                    "viewport-size": "1366 x 513",
                    'javascript-delay': 1000,
                    'footer-center': '[page]/[topage]',
                    "no-stop-slow-scripts": True
                },
            )

            return response

        elif output == 'xls':

            response = render_to_response('r2010_evtservtom_salvar.html',
                                          context)
            filename = "r2010_evtservtom.xls"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response[
                'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8'

            return response

        else:

            return render(request, 'r2010_evtservtom_salvar.html', context)

    else:

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'pk': pk,
            'tab': tab,
            'output': output,
            'modulos': [
                'efdreinf',
            ],
            'paginas': [
                'r2010_evtservtom',
            ],
            'data': datetime.datetime.now(),
        }

        return render(request, 'permissao_negada.html', context)