Esempio n. 1
0
    def getPhoto(self, campo, request, data):
        if campo in request.keys():
            if request.get(campo, None):
                return ''
            else:
                id_form = int(request.get('forms_id', '0'))
                id_instance = int(request.get('id_instance', '0'))
                field = campo
                result = ModelsFormValues(
                ).get_FormValues_byForm_and_Instance_and_Field(
                    id_form, id_instance, field)
                if result:
                    return '../form-image?id=%s' % result.id

        elif campo in data.keys():
            id_form = int(request.get('forms_id', '0'))
            id_instance = int(request.get('id_instance', '0'))
            field = campo
            result = ModelsFormValues(
            ).get_FormValues_byForm_and_Instance_and_Field(
                id_form, id_instance, field)
            if result:
                return '../form-image?id=%s' % result.id

            else:
                return ''
        else:
            return ''
Esempio n. 2
0
    def update(self):
        id_form = int(self.context.forms_id)
        form = self.request.form
        self.errors = {}
        self.dados = []
        self.configuracao = ModelsConfigImport().get_Config_byIdForm(int(id_form))

        FIELD_BLACKLIST = ['form.config.save','form.importar',]
        configura = form.get('form.config.save',False)
        importacao = form.get('form.importar',False)

        if configura:

            for field in form.keys():
                if not field in FIELD_BLACKLIST:
                    D = {}
                    D['forms_id'] = id_form
                    D['fields'] = self.Convert_utf8(field)
                    D['campo_csv'] = self.Convert_utf8(form.get(field,0))

                    if self.configuracao:
                        ModelsConfigImport().update_ConfigImport(D['forms_id'],D['fields'],D['campo_csv'])

                    else:
                        ModelsConfigImport().set_ConfigImport(**D)

                    if 'form.config.save' in form.keys():
                        form.pop('form.config.save')

        elif importacao:
            if 'arquivo' in form.keys():
                file = form.get('arquivo').read().splitlines()

                for linha in file[1:]:
                    colunas = linha.split(';')
                    dados = {}

                    for campo in self.configuracao:
                        dados[self.Convert_utf8(campo.fields)] = self.Convert_utf8(colunas[int(campo.campo_csv)-1])

                    chave_form = self.context.campo_chave
                    result = ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(id_form,chave_form,dados[chave_form])

                    if result.count():
                        result = result[0]
                        id_instance = result.instance_id
                        for i in dados:
                            ModelsFormValues().update_form_value(id_form,id_instance,dados[i],i)

                    else:
                        id_instance = ModelsFormInstance().set_FormInstance(id_form)
                        for i in dados:
                            valor = dados[i]
                            if valor:
                                ModelsFormValues().set_form_value(id_form,id_instance,valor,i)

                    self.dados.append(dados)
Esempio n. 3
0
 def get_values_filter(self):
     filter = ModelsFormFields().get_Fields_ByField(self.context.campo_filtro, int(self.context.forms_id))
     if filter:
         self.filter = [filter.title, filter.name_field]
         
         if self.filter:
             result = ModelsFormValues().get_FormValues_byForm_and_Field(int(self.context.forms_id),self.filter[1])
             if result.count() > 0:
                 L = []
                 for i in result:
                     if i.value not in L:
                         L.append(i.value)
             return L
Esempio n. 4
0
    def convertSelect(self, valor, tipo, id):
        if tipo == 'list':
            txt = ''
            for i in self.decodePickle(valor):
                if txt:
                    txt += ', ' + i
                else:
                    txt += i

            return txt
        elif tipo == 'choice':
            campo = ModelsFormFields().get_Fields_byIdField(id)
            if campo:
                items = campo.list_values.splitlines()
                D = []
                for i in items:
                    L = i.split(' | ')

                    if len(L) >= 2:
                        if L[0] == valor:
                            return L[1]

            return valor
        elif tipo == 'date':
            data = self.decodePickle(valor)
            try:
                return data.strftime('%d/%m/%Y')
            except:
                return ''

        elif tipo == 'foreign_key':
            campo = ModelsFormFields().get_Fields_byIdField(id)

            if campo:
                form_ref = campo.ref_form

                form_ref_id = form_ref.id
                label = form_ref.campo_label
                key = form_ref.campo_chave

                dados = ModelsFormValues().get_FormValues_byForm_and_Field(
                    form_ref_id, key)
                for item in dados:
                    if item.value == valor:
                        dados_label = ModelsFormValues(
                        ).get_FormValues_byForm_and_Instance_and_Field(
                            form_ref_id, item.instance_id, label)

                        return dados_label.value

        return valor
Esempio n. 5
0
def ExcludFormDataBase(context, event):
    basestore = BaseStore()
    id_form = int(context.forms_id)

    record_values = ModelsFormValues().get_FormValues_byForm(id_form)
    if record_values:
        for record in record_values:
            basestore.store.remove(record)
            basestore.store.flush()

    record_instances = ModelsFormInstance().get_Instance(id_form)
    if record_instances:
        for record in record_instances:
            basestore.store.remove(record)
            basestore.store.flush()

    record_parameters = ModelsParametersForm().get_ParametersForm_byFormId(
        id_form)
    if record_parameters:
        for record in record_parameters:
            basestore.store.remove(record)
            basestore.store.flush()

    record_fields = ModelsFormFields().get_Fields_ByIdForm(id_form)
    if record_fields:
        for record in record_fields:
            basestore.store.remove(record)
            basestore.store.flush()

    record_form = ModelsForm().get_Forns_byId(id_form)
    if record_form:
        basestore.store.remove(record_form)
        basestore.store.flush()
Esempio n. 6
0
    def get_value_field(self, instance_id, name_field):
        if not isinstance(instance_id, int):
            instance_id = int(instance_id)

        if not isinstance(name_field, unicode):
            name_field = unicode(name_field)            

        return ModelsFormValues().get_FormValues_byForm_and_Instance_and_Field(self.form_id,instance_id,name_field)
Esempio n. 7
0
    def get_FormValues(self, getall=True):
        id_form = int(self.context.forms_id)
        form = self.request.form

        if 'data_inicial' in form.keys():
            data_inicial = self.str2datetime(
                form.get('data_inicial')) + timedelta(days=0)
        else:
            data_inicial = self.str2datetime(self.get_data_inicial())

        if 'data_final' in form.keys():
            data_final = self.str2datetime(
                form.get('data_final')) - timedelta(days=-1)
        else:
            data_final = self.str2datetime(self.get_data_final())

        self.data_instance = ModelsFormInstance().store.find(
            ModelsFormInstance,
            ModelsFormInstance.forms_id == id_form,
            ModelsFormInstance.date_creation >= data_inicial,
            ModelsFormInstance.date_creation <= data_final,
        ).order_by(Desc(ModelsFormInstance.date_creation))

        self.ids_instances = [int(i.instance_id) for i in self.data_instance]

        L_value = []
        self.data_values = ModelsFormValues().store.find(
            ModelsFormValues, ModelsFormValues.forms_id == id_form,
            ModelsFormValues.date_creation >= data_inicial,
            ModelsFormValues.date_creation <= data_final,
            ModelsFormValues.instance_id.is_in(self.ids_instances))

        for item in self.data_instance:
            data = self.data_values.find(
                ModelsFormValues.instance_id == int(item.instance_id))
            if data.count() > 0:
                L_value.append(data)

        L = []
        for item in L_value:
            if self.checkItem(item, form):
                L.append(item)
        return L
Esempio n. 8
0
 def list_registro(self):
     form = self.request.form
     if 'id_instance' in form.keys():  #'forms_id' in form.keys() and
         #forms_id = int(form.get('forms_id',''))
         id_form = int(self.context.forms_id)
         id_instance = int(form.get('id_instance', ''))
         return ModelsFormValues().get_FormValues_byForm_and_Instance(
             id_form, id_instance)
     else:
         return None
    def update(self):
        form = self.request.form
        instance = 0

        formulario = form.get('form','0')
        field = form.get('field','')
        self.name_field = field
        value = form.get('value','')

        self.formulario = formulario
        self.campos = ModelsFormFields().get_Fields_ByIdForm(int(formulario))

        campo_busca = ModelsFormValues().store.find(ModelsFormValues, ModelsFormValues.fields==unicode(field),
                                                                      ModelsFormValues.forms_id==int(formulario),
                                                                      ModelsFormValues.value==unicode(value)
                                                    )
        if campo_busca.count():
            instance = campo_busca[0].instance_id

        self.valores = ModelsFormValues().get_FormValues_byForm_and_Instance(int(formulario),instance)
    def update(self):
        form = self.request.form
        instance = 0

        formulario = form.get('form', '0')
        field = form.get('field', '')
        self.name_field = field
        value = form.get('value', '')

        self.formulario = formulario
        self.campos = ModelsFormFields().get_Fields_ByIdForm(int(formulario))

        campo_busca = ModelsFormValues().store.find(
            ModelsFormValues, ModelsFormValues.fields == unicode(field),
            ModelsFormValues.forms_id == int(formulario),
            ModelsFormValues.value == unicode(value))
        if campo_busca.count():
            instance = campo_busca[0].instance_id

        self.valores = ModelsFormValues().get_FormValues_byForm_and_Instance(
            int(formulario), instance)
Esempio n. 11
0
    def update(self):
        #Checagem de permição na view
        if not self.context.is_active_workflow:
            self.request.response.redirect('%s/' % self.context.absolute_url())


        pedidos_nivel2 = []
        self.pedidos = self.rs_to_list(ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(self.form_id,u'status',[u'open', u'em_andamento',u'cliente']))
         
        member =  self.context.restrictedTraverse('@@plone_portal_state').member()
        if member:
            username = member.getUserName()
            if not isinstance(username, unicode):
                username = unicode(username)  
            
            pedidos_nivel2 = ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(self.form_id, u'nivel',username) 

        self.pedidos_nivel2 = self.rs_to_list(pedidos_nivel2)

        self.pedidos_aprovado = self.rs_to_list(ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(self.form_id,u'status',u'aprovado'))
        self.pedidos_reprovado = self.rs_to_list(ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(self.form_id,u'status',u'reprovado'))
Esempio n. 12
0
def ExcludConteudoDataBase(context, event):
    basestore = BaseStore()
    id_form = int(context.forms_id)
    id_instance = int(context.instance_id)

    record_values = ModelsFormValues().get_FormValues_byForm_and_Instance(
        id_form, id_instance)
    if record_values:
        for record in record_values:
            basestore.store.remove(record)
            basestore.store.flush()

    ModelsFormInstance().del_Instance(id_form, id_instance)
Esempio n. 13
0
    def getFile(self, campo, request, data):
        if campo in request.keys():
            if request.get(campo, None):
                return ''
            else:
                if hasattr(self, 'context'):
                    default_form_id = self.context.forms_id
                else:
                    default_form_id = 0
                id_form = int(request.get('forms_id', default_form_id))
                id_instance = int(request.get('id_instance', '0'))
                field = campo
                result = ModelsFormValues(
                ).get_FormValues_byForm_and_Instance_and_Field(
                    id_form, id_instance, field)
                if result:
                    return '../form-file?id=%s' % result.id

        elif campo in data.keys():
            if hasattr(self, 'context'):
                default_form_id = self.context.forms_id
            else:
                default_form_id = 0
            id_form = int(request.get('forms_id', default_form_id))
            id_instance = int(request.get('id_instance', '0'))
            field = campo
            result = ModelsFormValues(
            ).get_FormValues_byForm_and_Instance_and_Field(
                id_form, id_instance, field)
            if result:
                return '../form-file?id=%s' % result.id

            else:
                return ''
        else:
            return ''
Esempio n. 14
0
    def check_exclud_fields(self):
        id_form = int(self.context.forms_id)
        id_fields = int(self.request.form.get('id_fields', '0'))

        field = ModelsFormFields().get_Fields_byIdField(id_fields)
        if field:
            check = ModelsFormValues().get_FormValues_byForm_and_Field(
                id_form, field.name_field)

            if check:
                return False
            else:
                if field.ref_mult.count():
                    return False
                else:
                    return True
        return True
Esempio n. 15
0
    def update(self,form_id=None):
        pedidos = []

        if not form_id:
            form_id = self.form_id
        else:
            setattr(self, 'form_id', form_id)

        member =  self.context.restrictedTraverse('@@plone_portal_state').member()
        if member:
            username = member.getUserName()
            if not isinstance(username, unicode):
                username = unicode(username)  

            pedidos = self.rs_to_list(ModelsFormValues().get_FormValues_byForm_and_Field_and_Value(form_id,u'username',username))


        self.meus_pedidos = pedidos
Esempio n. 16
0
    def update(self):
        form = self.request.form
        if 'id' in form.keys():
            id = form.get('id', '0')
            if id != 'None':
                campo_image = ModelsFormValues().get_Values_byID(int(id))
                valor = campo_image.value
                valor_blob = campo_image.value_blob
                if valor:
                    x = self.decodePickle(valor)
                else:
                    x = self.decodePickle(valor_blob)

                filename = x['filename']
                self.request.response.setHeader("Content-Type", "type/file", 0)
                self.request.response.setHeader(
                    'Content-Disposition',
                    'attachment; filename=%s' % (filename))
                self.request.response.write(x['data'])
Esempio n. 17
0
    def get_FormValues(self,getall=True):
        id_form = int(self.context.forms_id)
        form = self.request.form

        if 'data_inicial' in form.keys():
            data_inicial = self.str2datetime(form.get('data_inicial')) + timedelta(days=0)
        else:
            data_inicial = self.str2datetime(self.get_data_inicial())


        if 'data_final' in form.keys():
            data_final = self.str2datetime(form.get('data_final')) - timedelta(days=-1)
        else:
            data_final = self.str2datetime(self.get_data_final())

        self.data_instance = ModelsFormInstance().store.find(
            ModelsFormInstance, ModelsFormInstance.forms_id==id_form,
            ModelsFormInstance.date_creation>=data_inicial,
            ModelsFormInstance.date_creation<=data_final,
        ).order_by(Desc(ModelsFormInstance.date_creation))

        self.ids_instances = [int(i.instance_id) for i in self.data_instance]

        L_value = []
        self.data_values = ModelsFormValues().store.find(
            ModelsFormValues, 
            ModelsFormValues.forms_id == id_form,
            ModelsFormValues.date_creation >= data_inicial,
            ModelsFormValues.date_creation <= data_final,
            ModelsFormValues.instance_id.is_in(self.ids_instances))

        for item in self.data_instance: 
            data = self.data_values.find(ModelsFormValues.instance_id == int(item.instance_id))
            if data.count() > 0:
                L_value.append(data)

        L = []
        for item in L_value:
            if self.checkItem(item, form):
                L.append(item)
        return L
Esempio n. 18
0
    def update(self):
        form = self.request.form
        if 'id' in form.keys():
            id = form.get('id', '0')
            if id != 'None':
                campo_image = ModelsFormValues().get_Values_byID(int(id))
                valor = campo_image.value
                valor_blob = campo_image.value_blob

                if valor:
                    x = self.decodePickle(valor)
                else:
                    x = self.decodePickle(valor_blob)

                self.request.response.setHeader("Content-Type", "image/jpeg",
                                                0)

                try:
                    #medoto adicionado na versão 1.1 do vindula
                    self.request.response.write(x['data'])
                except:
                    # medo usutilizado ate a versão antiga do content core
                    self.request.response.write(x)
Esempio n. 19
0
    def geraHTMLContent(self,id,tipo,valor,full_text=False):
        if tipo == 'list':
            txt = ''
            for i in self.decodePickle(valor):
                txt += i +', '

            return txt

        elif tipo == 'img':

            if id:
                return '<img width="100px" src="../form-image?id=%s">' % id
            else:
                return ''

        elif tipo == 'file':
            if id:
                arquivo = self.decodePickle(valor)
                if arquivo != '':
                    name = arquivo.get('filename','')
                    return '<a href="../form-file?id=%s" target="_blank">%s</a><br />'%(id,name)
                else:
                    return ''
            else:
                return ''

        elif tipo == 'date':
            data = self.decodePickle(valor)
            try:
                return data.strftime('%d/%m/%Y')

            except:
                return ''


        elif tipo == 'choice':
            if id:
                valor_campo = ModelsFormValues().get_Values_byID(id)
                id_form = int(self.context.forms_id)

                if valor_campo:
                    campo = ModelsFormFields().get_Fields_ByField(valor_campo.fields,id_form)
    
                    items = campo.list_values.splitlines()
                    D=[]
                    for i in items:
                        L = i.split(' | ')
    
                        if len(L) >= 2:
                            if L[0] == valor:
                                return L[1]

            return valor

        elif tipo == 'foreign_key':
            if id:
                valor_campo = ModelsFormValues().get_Values_byID(id)
                id_form = int(self.context.forms_id)







                if valor_campo:
                    campo = ModelsFormFields().get_Fields_ByField(valor_campo.fields,id_form)

                    if campo:
                        form_ref = campo.ref_form

                        form_ref_id = form_ref.id
                        label = form_ref.campo_label
                        key = form_ref.campo_chave

                        if full_text:
                            instance = 0
                            txt = ''

                            v_campos = form_ref.fields 
                            campo_busca = ModelsFormValues().store.find(ModelsFormValues, ModelsFormValues.fields==key,
                                                                                          ModelsFormValues.forms_id==form_ref_id,
                                                                                          ModelsFormValues.value==valor
                                                                        )
                            if campo_busca.count():
                                instance = campo_busca[0].instance_id

                                valores = ModelsFormValues().get_FormValues_byForm_and_Instance(form_ref_id,instance)

                                txt = '<br/>'
                                for v_campo in v_campos:
                                    v_valor = valores.find(fields=v_campo.name_field).one()
                                    txt += '<b> %s : </b><span> %s </span><br/>' %(v_campo.title,v_valor.value)

                            return txt

                        else:
                            dados = ModelsFormValues().get_FormValues_byForm_and_Field(form_ref_id,key)
                            for item in dados:
                                if item.value == valor:
                                    dados_label = ModelsFormValues().get_FormValues_byForm_and_Instance_and_Field(form_ref_id, item.instance_id, label)

                                    return dados_label.value

        return valor
Esempio n. 20
0
def CreatFormDataBase(context, event):
    title = context.Title()
    description = context.Description()
    uid_form = IUUID(context)

    forms_id = context.forms_id

    D = {}
    try:
        D['name_form'] = to_utf8(title)
    except:
        D['name_form'] = title

    try:
        D['description_form'] = to_utf8(description)
    except:
        D['description_form'] = description

    try:
        D['uid_form'] = to_utf8(uid_form)
    except:
        D['uid_form'] = uid_form

    id_form = ModelsForm().set_Form(**D)
    if forms_id != id_form:
        context.forms_id = id_form

    if context.active_workflow:

        for campo in campos_controle:
            campo['forms_id'] = int(id_form)

            ModelsFormFields().set_FormFields(**campo)

    if 'original' in event.__dict__.keys():
        org = event.original
        new = event.object

        fields_org = ModelsFormFields().get_Fields_ByIdForm(int(org.forms_id))

        campos = ['name_field','type_fields', 'list_values','title','value_default',\
                  'description_fields','ordenacao','required','flag_ativo', 'flag_float_left']

        for item in fields_org:
            D = {}
            for i in campos:
                D[i] = item.__getattribute__(i)

            D['forms_id'] = int(new.forms_id)

            ModelsFormFields().set_FormFields(**D)

        instances_org = ModelsFormInstance().get_Instance(int(org.forms_id))

        for instance in instances_org:
            values_instance = ModelsFormValues(
            ).get_FormValues_byForm_and_Instance(int(org.forms_id),
                                                 instance.instance_id)

            id_inst = ModelsFormInstance().set_FormInstance(int(new.forms_id))

            campos_value = ['value', 'value_blob', 'fields']

            for value in values_instance:
                D = {}
                for i in campos_value:
                    D[i] = value.__getattribute__(i)

                D['forms_id'] = int(new.forms_id)
                D['instance_id'] = id_inst

                ModelsFormValues().set_FormValues(**D)
Esempio n. 21
0
    def update(self):
        id_form = int(self.context.forms_id)
        form = self.request.form
        self.errors = {}
        self.dados = []
        self.configuracao = ModelsConfigImport().get_Config_byIdForm(
            int(id_form))

        FIELD_BLACKLIST = [
            'form.config.save',
            'form.importar',
        ]
        configura = form.get('form.config.save', False)
        importacao = form.get('form.importar', False)

        if configura:

            for field in form.keys():
                if not field in FIELD_BLACKLIST:
                    D = {}
                    D['forms_id'] = id_form
                    D['fields'] = self.Convert_utf8(field)
                    D['campo_csv'] = self.Convert_utf8(form.get(field, 0))

                    if self.configuracao:
                        ModelsConfigImport().update_ConfigImport(
                            D['forms_id'], D['fields'], D['campo_csv'])

                    else:
                        ModelsConfigImport().set_ConfigImport(**D)

                    if 'form.config.save' in form.keys():
                        form.pop('form.config.save')

        elif importacao:
            if 'arquivo' in form.keys():
                file = form.get('arquivo').read().splitlines()

                for linha in file[1:]:
                    colunas = linha.split(';')
                    dados = {}

                    for campo in self.configuracao:
                        dados[self.Convert_utf8(
                            campo.fields)] = self.Convert_utf8(
                                colunas[int(campo.campo_csv) - 1])

                    chave_form = self.context.campo_chave
                    result = ModelsFormValues(
                    ).get_FormValues_byForm_and_Field_and_Value(
                        id_form, chave_form, dados[chave_form])

                    if result.count():
                        result = result[0]
                        id_instance = result.instance_id
                        for i in dados:
                            ModelsFormValues().update_form_value(
                                id_form, id_instance, dados[i], i)

                    else:
                        id_instance = ModelsFormInstance().set_FormInstance(
                            id_form)
                        for i in dados:
                            valor = dados[i]
                            if valor:
                                ModelsFormValues().set_form_value(
                                    id_form, id_instance, valor, i)

                    self.dados.append(dados)
Esempio n. 22
0
class VindulaViewForm(grok.View, BaseFunc):
    grok.context(IFormularioPadrao)
    grok.require('cmf.ListFolderContents')
    grok.name('view-form')  #Dados

    data_instance = []
    data_values = []
    ids_instances = []

    def get_FormValues(self, getall=True):
        id_form = int(self.context.forms_id)
        form = self.request.form

        if 'data_inicial' in form.keys():
            data_inicial = self.str2datetime(
                form.get('data_inicial')) + timedelta(days=0)
        else:
            data_inicial = self.str2datetime(self.get_data_inicial())

        if 'data_final' in form.keys():
            data_final = self.str2datetime(
                form.get('data_final')) - timedelta(days=-1)
        else:
            data_final = self.str2datetime(self.get_data_final())

        self.data_instance = ModelsFormInstance().store.find(
            ModelsFormInstance,
            ModelsFormInstance.forms_id == id_form,
            ModelsFormInstance.date_creation >= data_inicial,
            ModelsFormInstance.date_creation <= data_final,
        ).order_by(Desc(ModelsFormInstance.date_creation))

        self.ids_instances = [int(i.instance_id) for i in self.data_instance]

        L_value = []
        self.data_values = ModelsFormValues().store.find(
            ModelsFormValues, ModelsFormValues.forms_id == id_form,
            ModelsFormValues.date_creation >= data_inicial,
            ModelsFormValues.date_creation <= data_final,
            ModelsFormValues.instance_id.is_in(self.ids_instances))

        for item in self.data_instance:
            data = self.data_values.find(
                ModelsFormValues.instance_id == int(item.instance_id))
            if data.count() > 0:
                L_value.append(data)

        L = []
        for item in L_value:
            if self.checkItem(item, form):
                L.append(item)
        return L

    def get_FormValues_filtro(self):
        id_form = int(self.context.forms_id)
        return ModelsForm().get_FormValues_filtro(id_form)

    def get_Form_fields(self):
        id_form = int(self.context.forms_id)
        return ModelsFormFields().get_Fields_ByIdForm(id_form)

    def get_values_filter(self, fields=[]):
        fields_value = {}

        for field in fields:
            if field.type_fields in [
                    'text', 'bool', 'choice', 'list', 'hidden', 'radio',
                    'foreign_key', 'date'
            ]:
                fields_value[field.name_field] = []
                values = self.data_values.find(
                    ModelsFormValues.fields == field.name_field)
                for value in values:
                    if value.value not in fields_value[field.name_field]:
                        fields_value[field.name_field].append(value.value)

        #Filtro de data de criação
        fields_value['creation'] = []
        for instance in self.data_instance:
            date = instance.date_creation.strftime('%d/%m/%Y')
            if date not in fields_value['creation']:
                fields_value['creation'].append(date)
        return fields_value

    def get_Form_instance(self):
        id_form = int(self.context.forms_id)
        return ModelsFormInstance().get_Instance(id_form)

    def find_group_by(self, valores):
        L = []
        for valor in valores:
            V = valor.value
            if V and not V in L:
                L.append(V)

        return L

    def find_group_by_data(self, valores):
        L = []
        for valor in valores:
            V = valor.date_creation.strftime('%d/%m/%Y %H:%M:%S')
            if not V in L:
                L.append(V)
        return L

    def valores_b(self, all_values, campo):
        L = []
        for i in all_values:
            x = i.find(fields=campo.name_field)
            if x.count():
                x = x[0]
                L.append(x)

        return L

    def canRequestPermission(self, permissao):
        return checkPermission(permissao, self.context)

    def checkItem(self, item, form):
        for campo in form.keys():
            if campo not in [
                    'b_start', 'date_creation', 'data_final', 'data_inicial'
            ]:

                valor = form.get(campo, '')
                field = item.find(fields=self.Convert_utf8(campo)).one()

                if not valor:
                    continue
                if not field:
                    return False

                elif type(valor) == list:
                    existe = False
                    for val in valor:
                        if field:
                            if field.value == self.Convert_utf8(val):
                                existe = True
                                break

                    if not existe:
                        return False
                elif field:
                    if not field.value == self.Convert_utf8(valor):
                        return False

            elif campo == 'date_creation':
                valor = form.get(campo, '')
                if valor and item[0].instancia.date_creation.strftime(
                        '%d/%m/%Y %H:%M:%S') != valor:
                    return False

        return True

    def get_data_final(self):
        date = datetime.now()
        return date.strftime('%d/%m/%Y')

    def get_data_inicial(self):
        date = datetime.now() - timedelta(days=5)
        return date.strftime('%d/%m/%Y')

    def str2datetime(self, str):
        split_date = str.split('/')
        try:
            return datetime(int(split_date[2]), int(split_date[1]),
                            int(split_date[0]))
        except ValueError:
            return datetime.now()

    def get_data(self, item, campo):
        return item.find(fields=campo.name_field).one()
Esempio n. 23
0
    def geraHTMLContent(self, id, tipo, valor, full_text=False):
        if tipo == 'list':
            txt = ''
            for i in self.decodePickle(valor):
                txt += i + ', '

            return txt

        elif tipo == 'img':

            if id:
                return '<img width="100px" src="../form-image?id=%s">' % id
            else:
                return ''

        elif tipo == 'file':
            if id:
                arquivo = self.decodePickle(valor)
                if arquivo != '':
                    name = arquivo.get('filename', '')
                    return '<a href="../form-file?id=%s" target="_blank">%s</a><br />' % (
                        id, name)
                else:
                    return ''
            else:
                return ''

        elif tipo == 'date':
            data = self.decodePickle(valor)
            try:
                return data.strftime('%d/%m/%Y')

            except:
                return ''

        elif tipo == 'choice':
            if id:
                valor_campo = ModelsFormValues().get_Values_byID(id)
                id_form = int(self.context.forms_id)

                if valor_campo:
                    campo = ModelsFormFields().get_Fields_ByField(
                        valor_campo.fields, id_form)

                    items = campo.list_values.splitlines()
                    D = []
                    for i in items:
                        L = i.split(' | ')

                        if len(L) >= 2:
                            if L[0] == valor:
                                return L[1]

            return valor

        elif tipo == 'foreign_key':
            if id:
                valor_campo = ModelsFormValues().get_Values_byID(id)
                id_form = int(self.context.forms_id)

                if valor_campo:
                    campo = ModelsFormFields().get_Fields_ByField(
                        valor_campo.fields, id_form)

                    if campo:
                        form_ref = campo.ref_form

                        form_ref_id = form_ref.id
                        label = form_ref.campo_label
                        key = form_ref.campo_chave

                        if full_text:
                            instance = 0
                            txt = ''

                            v_campos = form_ref.fields
                            campo_busca = ModelsFormValues().store.find(
                                ModelsFormValues,
                                ModelsFormValues.fields == key,
                                ModelsFormValues.forms_id == form_ref_id,
                                ModelsFormValues.value == valor)
                            if campo_busca.count():
                                instance = campo_busca[0].instance_id

                                valores = ModelsFormValues(
                                ).get_FormValues_byForm_and_Instance(
                                    form_ref_id, instance)

                                txt = '<br/>'
                                for v_campo in v_campos:
                                    v_valor = valores.find(
                                        fields=v_campo.name_field).one()
                                    txt += '<b> %s : </b><span> %s </span><br/>' % (
                                        v_campo.title, v_valor.value)

                            return txt

                        else:
                            dados = ModelsFormValues(
                            ).get_FormValues_byForm_and_Field(
                                form_ref_id, key)
                            for item in dados:
                                if item.value == valor:
                                    dados_label = ModelsFormValues(
                                    ).get_FormValues_byForm_and_Instance_and_Field(
                                        form_ref_id, item.instance_id, label)

                                    return dados_label.value

        return valor
Esempio n. 24
0
 def get_FormValues(self, id_form, id_instance):
     return ModelsFormValues().get_FormValues_byForm_and_Instance(
         int(id_form), int(id_instance))
Esempio n. 25
0
class VindulaViewForm(grok.View, BaseFunc):
    grok.context(IFormularioPadrao)
    grok.require('cmf.ListFolderContents')
    grok.name('view-form') #Dados


    data_instance = []
    data_values = []
    ids_instances = []

    def get_FormValues(self,getall=True):
        id_form = int(self.context.forms_id)
        form = self.request.form

        if 'data_inicial' in form.keys():
            data_inicial = self.str2datetime(form.get('data_inicial')) + timedelta(days=0)
        else:
            data_inicial = self.str2datetime(self.get_data_inicial())


        if 'data_final' in form.keys():
            data_final = self.str2datetime(form.get('data_final')) - timedelta(days=-1)
        else:
            data_final = self.str2datetime(self.get_data_final())

        self.data_instance = ModelsFormInstance().store.find(
            ModelsFormInstance, ModelsFormInstance.forms_id==id_form,
            ModelsFormInstance.date_creation>=data_inicial,
            ModelsFormInstance.date_creation<=data_final,
        ).order_by(Desc(ModelsFormInstance.date_creation))

        self.ids_instances = [int(i.instance_id) for i in self.data_instance]

        L_value = []
        self.data_values = ModelsFormValues().store.find(
            ModelsFormValues, 
            ModelsFormValues.forms_id == id_form,
            ModelsFormValues.date_creation >= data_inicial,
            ModelsFormValues.date_creation <= data_final,
            ModelsFormValues.instance_id.is_in(self.ids_instances))

        for item in self.data_instance: 
            data = self.data_values.find(ModelsFormValues.instance_id == int(item.instance_id))
            if data.count() > 0:
                L_value.append(data)

        L = []
        for item in L_value:
            if self.checkItem(item, form):
                L.append(item)
        return L

    def get_FormValues_filtro(self):
        id_form = int(self.context.forms_id)
        return ModelsForm().get_FormValues_filtro(id_form)

    def get_Form_fields(self):
        id_form = int(self.context.forms_id)
        return ModelsFormFields().get_Fields_ByIdForm(id_form)

    def get_values_filter(self, fields=[]):
        fields_value = {}

        for field in fields:
            if field.type_fields in ['text', 'bool', 'choice', 'list', 'hidden', 'radio', 'foreign_key', 'date']:
                fields_value[field.name_field] = []
                values = self.data_values.find(ModelsFormValues.fields==field.name_field)  
                for value in values:
                    if value.value not in fields_value[field.name_field]:
                        fields_value[field.name_field].append(value.value)

        #Filtro de data de criação
        fields_value['creation'] = []
        for instance in self.data_instance:
            date = instance.date_creation.strftime('%d/%m/%Y')
            if date not in fields_value['creation']:
                fields_value['creation'].append(date)
        return fields_value


    def get_Form_instance(self):
        id_form = int(self.context.forms_id)
        return ModelsFormInstance().get_Instance(id_form)

    def find_group_by(self, valores):
        L = []
        for valor in valores:
            V = valor.value
            if V and not V in L:
                L.append(V)

        return L

    def find_group_by_data(self, valores):
        L = []
        for valor in valores:
            V = valor.date_creation.strftime('%d/%m/%Y %H:%M:%S')
            if not V in L:
                L.append(V)
        return L

    def valores_b(self, all_values,campo):
        L = []
        for i in all_values:
            x = i.find(fields=campo.name_field)
            if x.count():
                x = x[0]
                L.append(x)

        return L


    def canRequestPermission(self,permissao):
        return checkPermission(permissao, self.context)

    def checkItem(self, item, form):
        for campo in form.keys():
            if campo not in ['b_start','date_creation','data_final','data_inicial']:

                valor = form.get(campo,'')
                field = item.find(fields=self.Convert_utf8(campo)).one()

                if not valor :
                    continue
                if not field:
                    return False

                elif type(valor) == list:
                    existe = False
                    for val in valor:
                        if field:
                            if field.value == self.Convert_utf8(val):
                                existe = True
                                break

                    if not existe:
                        return False
                elif field:
                    if not field.value == self.Convert_utf8(valor):
                        return False

            elif campo == 'date_creation':
                valor = form.get(campo,'')
                if valor and item[0].instancia.date_creation.strftime('%d/%m/%Y %H:%M:%S') != valor:
                    return False

        return True

    def get_data_final(self):
        date = datetime.now()
        return date.strftime('%d/%m/%Y')

    def get_data_inicial(self):
        date = datetime.now() - timedelta(days=5)
        return date.strftime('%d/%m/%Y')

    def str2datetime(self, str):
        split_date = str.split('/')
        try:
            return datetime(int(split_date[2]),
                            int(split_date[1]),
                            int(split_date[0]))
        except ValueError:
            return datetime.now()

    def get_data(self, item, campo):
        return item.find(fields=campo.name_field).one()
Esempio n. 26
0
    def itens(self,instance_id):
        if not isinstance(instance_id, int):
            instance_id = int(instance_id)

        return ModelsFormValues().get_FormValues_byForm_and_Instance(self.form_id,instance_id)