def protoList(request):
#   Vista simple para cargar la informacion,

    PAGESIZE = 50
    message = ''

    if not request.user or not request.user.is_authenticated():
        return doReturn ({'success':False , 'message' : 'readOnly User'})

    if request.method != 'POST':
        return doReturn ({'success':False, 'message' : 'invalid message'})

#   Los objetos vienen textoJson y hay q hacer el load para construirlos como objetos.
    protoMeta = request.POST.get('protoMeta', '')
    protoMeta = json.loads(protoMeta)

#
    protoFilter = request.POST.get('protoFilter', '')
    baseFilter = request.POST.get('baseFilter', '')
    sort = request.POST.get('sort', '')

    start = int(request.POST.get('start', 0))
    page = int(request.POST.get('page', 1))
    limit = int(request.POST.get('limit', PAGESIZE))


#   Obtiene las filas del modelo
    Qs, orderBy, fakeId, refAllow = getQSet(protoMeta, protoFilter, baseFilter , sort , request.user)
    pRowsCount = Qs.count()


#   Fix: Cuando esta en la pagina el filtro continua en la pagina 2 y no muestra nada.
#   if ( ( page -1 ) *limit >= pRowsCount ): page = 1

#   En el sitio en produccion, el pRows pasaba sin asignar; no entiendo el porq?
    if orderBy:
        try:
            pRows = Qs.order_by(*orderBy)[ start: page * limit ]
        except:
            pRows = Qs.all()[ start: page * limit ]
    else: 
        pRows = Qs.all()[ start: page * limit ]


    # Verifica los nodos validos 
    if refAllow: 
        userNodes = getUserNodes(request.user, protoMeta.get('viewEntity', ''))
    else: 
        userNodes = []

#   Prepara las cols del Query
    try:
        # TODO: improve performance
        pList = Q2Dict(protoMeta , pRows, fakeId, userNodes)
        bResult = True
    except Exception, e:
        traceback.print_exc()
        message = getReadableError(e)
        bResult = False
        pList = []
Beispiel #2
0
def protoList(request):
    #   Vista simple para cargar la informacion,

    PAGESIZE = 50
    message = ''

    if not request.user or not request.user.is_authenticated():
        return doReturn({'success': False, 'message': 'readOnly User'})

    if request.method != 'POST':
        return doReturn({'success': False, 'message': 'invalid message'})

#   Los objetos vienen textoJson y hay q hacer el load para construirlos como objetos.
    protoMeta = request.POST.get('protoMeta', '')
    protoMeta = json.loads(protoMeta)

    #
    protoFilter = request.POST.get('protoFilter', '')
    baseFilter = request.POST.get('baseFilter', '')
    sort = request.POST.get('sort', '')

    start = int(request.POST.get('start', 0))
    page = int(request.POST.get('page', 1))
    limit = int(request.POST.get('limit', PAGESIZE))

    #   Obtiene las filas del modelo
    Qs, orderBy, fakeId, refAllow = getQSet(protoMeta, protoFilter, baseFilter,
                                            sort, request.user)
    pRowsCount = Qs.count()

    #   Fix: Cuando esta en la pagina el filtro continua en la pagina 2 y no muestra nada.
    #   if ( ( page -1 ) *limit >= pRowsCount ): page = 1

    #   En el sitio en produccion, el pRows pasaba sin asignar; no entiendo el porq?
    if orderBy:
        try:
            pRows = Qs.order_by(*orderBy)[start:page * limit]
        except:
            pRows = Qs.all()[start:page * limit]
    else:
        pRows = Qs.all()[start:page * limit]

    # Verifica los nodos validos
    if refAllow:
        userNodes = getUserNodes(request.user, protoMeta.get('viewEntity', ''))
    else:
        userNodes = []

#   Prepara las cols del Query
    try:
        # TODO: improve performance
        pList = Q2Dict(protoMeta, pRows, fakeId, userNodes)
        bResult = True
    except Exception, e:
        traceback.print_exc()
        message = getReadableError(e)
        bResult = False
        pList = []
Beispiel #3
0
def _protoEdit(request, myAction ):

    if not request.user.is_authenticated():
        return doReturn ({'success':False ,'message' : 'readOnly User'})

    if request.method != 'POST':
        return doReturn ({'success':False, 'message' : 'invalid message'})

    message = ''

#   Carga el modelo
    protoMeta = request.POST.get('protoMeta', '')
    protoMeta = json.loads( protoMeta )
    viewEntity = protoMeta.get('viewEntity', '')
    model = getDjangoModel(viewEntity)

#   Autentica
    if not getModelPermissions( request.user, model, myAction ):
        return doReturn ({'success':False ,'message' : 'No ' +  myAction +  'permission'})

#   Obtiene el profile para saber el teamhierarchi
    userProfile = getUserProfile( request.user, 'edit', viewEntity )

#   Verfica si es un protoModel ( maneja TeamHierarchy )
    isProtoModel = hasattr( model , '_protoObj' )

#   Verifica si hay registros que son solo de referencia
    userNodes = []
    refAllow = False 
    if myAction in ['delete', 'change'] and isProtoModel and not request.user.is_superuser  :
        refAllow = getModelPermissions( request.user, model, 'refallow' )
        if refAllow:
            userNodes = getUserNodes( request.user, viewEntity )

#   WorkFlow  
    hasWFlow = hasattr( model , '_WorkFlow' ) and isProtoModel 
    if hasWFlow: 
        wfadmin =  getModelPermissions( request.user , model, 'wfadmin' )
        WFlowControl = getattr( model, '_WorkFlow', {} )
        initialWfStatus = WFlowControl.get( 'initialStatus', '0')

#   Decodifica los eltos
    rows = request.POST.get('rows', [])
    rows = json.loads( rows )

    fieldsDict = list2dict( protoMeta[ 'fields' ], 'name')

#   JsonField
    jsonField = protoMeta.get('jsonField', '')
    if not isinstance( jsonField, (str, unicode) ): jsonField = ''

#   TOOD: Log
#   activityLog ( myAction, request.user , viewEntity,  {  'protoMeta' : protoMeta , 'rows' : rows })


#   Genera la clase UDP
    pUDP = protoMeta.get('usrDefProps', {})
    cUDP = verifyUdpDefinition( pUDP )

    # Verifica q sea una lista de registros, (no deberia pasar, ya desde Extjs se controla )
    if type(rows).__name__=='dict':
        rows = [rows]


    pList = []
    for data in rows:

        data['_ptStatus'] =  ''

        if myAction == 'add':
            rec = model()
        else:
            try:
                rec = model.objects.get( pk = data['id']  )
            except:
                data['_ptStatus'] = data['_ptStatus'] +  ERR_NOEXIST + '<br>'
                pList.append( data )
                continue


        # refAllow verifica si corresponde a los registros modificables  ( solo es true en myAction in ['delete', 'change'] ) 
        if refAllow and isProtoModel :
            if not ( str( rec.smOwningTeam_id ) in userNodes ) :
                data['_ptStatus'] = ERR_REFONLY + '<br>'
                pList.append( data )
                continue

        if not ( myAction == 'delete' ):
            # Upd, Ins
            for key in data:
                key = smart_str( key )
                if  key in ['id', '_ptStatus', '_ptId', '__str__']: continue

                vFld = fieldsDict[key]
                if vFld.get( 'crudType' )  in ["screenOnly", "linked" ]: continue

                #  Los campos de seguridad se manejan a nivel registro
                if isProtoModel:
                    if key in ['smOwningUser','smOwningTeam','smCreatedBy','smModifiedBy',
                               'smWflowStatus','smRegStatus','smCreatedOn','smModifiedOn',
                               'smOwningUser_id','smOwningTeam_id','smCreatedBy_id','smModifiedBy_id']: continue

                #  Udps
                if (cUDP.udpTable and key.startswith( cUDP.propertyPrefix + '__')): continue

                #  JsonField
                if key ==  jsonField: continue
                if key.startswith( jsonField + '__'): continue

                try:
                    setRegister( model,  rec, key,  data )
                except Exception as e:
                    data['_ptStatus'] = data['_ptStatus'] +  getReadableError( e )

            if isProtoModel:
                setSecurityInfo( rec, data, userProfile, ( myAction == 'add' ) )


            if len( jsonField ) > 0:
                jsonInfo = {}
                for key in data:
                    if not key.startswith( jsonField + '__'): continue
                    jKey = key[ len(jsonField) + 2 : ]
                    jsonInfo[ jKey ] = data[ key ]
                setattr( rec, jsonField , jsonInfo   )


            # Inicializa el estado del WF 
            if hasWFlow: 
                setattr( rec, 'smWflowStatus' , initialWfStatus )

            # Guarda el idInterno para concatenar registros nuevos en la grilla
            try:
                _ptId = data['_ptId']
            except:
                _ptId = ''

            try:
                rec.save()

                # Guardar las Udps
                if cUDP.udpTable:
                    try:
                        saveUDP( rec, data, cUDP  )
                    except Exception as e:
                        raise Exception( 'UdpError: saveActiob')

                # -- Los tipos complejos ie. date, generan un error, es necesario hacerlo detalladamente
                # Convierte el registro en una lista y luego toma solo el primer elto de la lista resultado.
                data = Q2Dict(protoMeta , [rec], False  )[0]
                data['_ptId'] =  _ptId

            except Exception as  e:
                data['_ptStatus'] =  data['_ptStatus'] +  getReadableError( e )
                data['_ptId'] =  _ptId
                #traceback.print_exc()
                #return doReturn ({'success':False ,'message' : str( e )})

        else:  # Action Delete
            try:
                rec.delete()

            except Exception,  e:
                data['_ptStatus'] = data['_ptStatus'] +  getReadableError( e )
                pass

        pList.append( data )

        if data.get('_ptStatus', ''):
            message += data['_ptStatus']  + ';'
def getQSet(protoMeta, protoFilter, baseFilter , sort , pUser):

#   Decodifica los eltos
    viewEntity = protoMeta.get('viewEntity', '')
    model = getDjangoModel(viewEntity)

#   Autentica '
    if not getModelPermissions(pUser, model, 'list'):
        return model.objects.none(), [], False, False 

#   modelo Administrado
    isProtoModel = hasattr(model , '_protoObj')
    if isProtoModel:
        userNodes = getUserNodes(pUser, viewEntity)

#   WorkFlow Model 
    hasWFlow = hasattr(model , '_WorkFlow')
    if hasWFlow: 
        WFlowControl = getattr(model, '_WorkFlow', {})
        OkStatus = WFlowControl.get('OkStatus', 'Ok')
        
#   JsonField
    JsonField = protoMeta.get('jsonField', '')
    if not isinstance(JsonField, (str, unicode)): 
        JsonField = ''

#   QSEt
#   Qs = model.objects.select_related(depth=1)
    Qs = model.objects

#   Permite la lectura de todos los registros 
    refAllow = getModelPermissions(pUser, model, 'refallow')
    

#   Solamenete valida si es     
    if isProtoModel and not pUser.is_superuser :

        # Si no tiene wflow y tampoco permiso de referencia, se limita a los nodos de su equipo    
        if not refAllow :
            Qs = Qs.filter(smOwningTeam__in=userNodes)

        # Si tiene permiso de referencia y ademas WF, trae todos los propios o los demas en estado valido 
        elif hasWFlow:
            Qs = Qs.filter(Q(smOwningTeam__in=userNodes) | Q(~Q(smOwningTeam__in=userNodes) , Q(smWflowStatus=OkStatus))) 

#   TODO: Agregar solomente los campos definidos en el safeMeta  ( only,  o defer )
#   Qs.query.select_fields = [f1, f2, .... ]


#   Le pega la meta al modelo para tomar por ejemplo searchFields
    model.protoMeta = protoMeta

#   El filtro base viene en la configuracion MD
    try:
        Qs = addQbeFilter(baseFilter, model, Qs , JsonField)
    except Exception as e:
        traceback.print_exc()
        getReadableError(e)

#   Order by
    localSort = protoMeta.get('localSort', False)
    orderBy = []
    if not localSort :
        sort = verifyList(sort)
        for sField in sort:

            # Verificar que el campo de sort haga parte de los campos del modelo
            # blacklist = [f.name for f in instance._meta.fields] + ['id', 'user']

            # Unicode sort
            if sField['property'] == '__str__' :
                try:
                    unicodeSort = getUnicodeFields(model)
                    for sAux in unicodeSort:
                        if sField['direction'] == 'DESC': 
                            sAux = '-' + sAux
                        orderBy.append(sAux)
                except Exception as e:
                    pass 
                
            else:
                if sField['direction'] == 'DESC': 
                    sField['property'] = '-' + sField['property']
                orderBy.append(sField['property'])

    orderBy = tuple(orderBy)

    try:
        Qs = addQbeFilter(protoFilter, model, Qs, JsonField)
    except Exception as e:
        traceback.print_exc()
        getReadableError(e)

    # DbFirst en caso de q no exista una llave primaria
    fakeId = hasattr(model , '_fakeId')

    # Solo retorna refAllow si este es valido para la tabla ( no es un super usuario y es un modelo manejado por sm )  
    refAllow = refAllow and isProtoModel and not pUser.is_superuser 

    return Qs, orderBy, fakeId, refAllow
Beispiel #5
0
def getQSet(protoMeta, protoFilter, baseFilter, sort, pUser):

    #   Decodifica los eltos
    viewEntity = protoMeta.get('viewEntity', '')
    model = getDjangoModel(viewEntity)

    #   Autentica '
    if not getModelPermissions(pUser, model, 'list'):
        return model.objects.none(), [], False, False

#   modelo Administrado
    isProtoModel = hasattr(model, '_protoObj')
    if isProtoModel:
        userNodes = getUserNodes(pUser, viewEntity)

#   WorkFlow Model
    hasWFlow = hasattr(model, '_WorkFlow')
    if hasWFlow:
        WFlowControl = getattr(model, '_WorkFlow', {})
        OkStatus = WFlowControl.get('OkStatus', 'Ok')

#   JsonField
    JsonField = protoMeta.get('jsonField', '')
    if not isinstance(JsonField, (str, unicode)):
        JsonField = ''

#   QSEt
#   Qs = model.objects.select_related(depth=1)
    Qs = model.objects

    #   Permite la lectura de todos los registros
    refAllow = getModelPermissions(pUser, model, 'refallow')

    #   Solamenete valida si es
    if isProtoModel and not pUser.is_superuser:

        # Si no tiene wflow y tampoco permiso de referencia, se limita a los nodos de su equipo
        if not refAllow:
            Qs = Qs.filter(smOwningTeam__in=userNodes)

        # Si tiene permiso de referencia y ademas WF, trae todos los propios o los demas en estado valido
        elif hasWFlow:
            Qs = Qs.filter(
                Q(smOwningTeam__in=userNodes)
                | Q(~Q(smOwningTeam__in=userNodes), Q(smWflowStatus=OkStatus)))

#   TODO: Agregar solomente los campos definidos en el safeMeta  ( only,  o defer )
#   Qs.query.select_fields = [f1, f2, .... ]

#   Le pega la meta al modelo para tomar por ejemplo searchFields
    model.protoMeta = protoMeta

    #   El filtro base viene en la configuracion MD
    try:
        Qs = addQbeFilter(baseFilter, model, Qs, JsonField)
    except Exception as e:
        traceback.print_exc()
        getReadableError(e)


#   Order by
    localSort = protoMeta.get('localSort', False)
    orderBy = []
    if not localSort:
        sort = verifyList(sort)
        for sField in sort:

            # Verificar que el campo de sort haga parte de los campos del modelo
            # blacklist = [f.name for f in instance._meta.fields] + ['id', 'user']

            # Unicode sort
            if sField['property'] == '__str__':
                try:
                    unicodeSort = getUnicodeFields(model)
                    for sAux in unicodeSort:
                        if sField['direction'] == 'DESC':
                            sAux = '-' + sAux
                        orderBy.append(sAux)
                except Exception as e:
                    pass

            else:
                if sField['direction'] == 'DESC':
                    sField['property'] = '-' + sField['property']
                orderBy.append(sField['property'])

    orderBy = tuple(orderBy)

    try:
        Qs = addQbeFilter(protoFilter, model, Qs, JsonField)
    except Exception as e:
        traceback.print_exc()
        getReadableError(e)

    # DbFirst en caso de q no exista una llave primaria
    fakeId = hasattr(model, '_fakeId')

    # Solo retorna refAllow si este es valido para la tabla ( no es un super usuario y es un modelo manejado por sm )
    refAllow = refAllow and isProtoModel and not pUser.is_superuser

    return Qs, orderBy, fakeId, refAllow
def _protoEdit(request, myAction):

    if not request.user.is_authenticated():
        return doReturn({'success': False, 'message': 'readOnly User'})

    if request.method != 'POST':
        return doReturn({'success': False, 'message': 'invalid message'})

    message = ''

    #   Carga el modelo
    protoMeta = request.POST.get('protoMeta', '')
    protoMeta = json.loads(protoMeta)
    viewEntity = protoMeta.get('viewEntity', '')
    model = getDjangoModel(viewEntity)

    #   Autentica
    if not getModelPermissions(request.user, model, myAction):
        return doReturn({
            'success': False,
            'message': 'No ' + myAction + 'permission'
        })

#   Obtiene el profile para saber el teamhierarchi
    userProfile = getUserProfile(request.user, 'edit', viewEntity)

    #   Verfica si es un protoModel ( maneja TeamHierarchy )
    isProtoModel = hasattr(model, '_protoObj')

    #   Verifica si hay registros que son solo de referencia
    userNodes = []
    refAllow = False
    if myAction in ['DEL', 'UPD'
                    ] and isProtoModel and not request.user.is_superuser:
        refAllow = getModelPermissions(request.user, model, 'refallow')
        if refAllow:
            userNodes = getUserNodes(request.user, viewEntity)

#   WorkFlow
    hasWFlow = hasattr(model, '_WorkFlow') and isProtoModel
    if hasWFlow:
        wfadmin = getModelPermissions(request.user, model, 'wfadmin')
        WFlowControl = getattr(model, '_WorkFlow', {})
        initialWfStatus = WFlowControl.get('initialStatus', '0')

#   Decodifica los eltos
    rows = request.POST.get('rows', [])
    rows = json.loads(rows)

    #   LogInfo
    logEvent(viewEntity, rows, request.user, userProfile.userTeam, '',
             myAction)

    #   Fields
    fieldsDict = list2dict(protoMeta['fields'], 'name')

    #   JsonField
    jsonField = protoMeta.get('jsonField', '')
    if not isinstance(jsonField, (str, unicode)):
        jsonField = ''


#   TOOD: Log
#   activityLog ( myAction, request.user , viewEntity,  {  'protoMeta' : protoMeta , 'rows' : rows })

#   Genera la clase UDP
    pUDP = protoMeta.get('usrDefProps', {})
    cUDP = verifyUdpDefinition(pUDP)

    # Verifica q sea una lista de registros, (no deberia pasar, ya desde Extjs se controla )
    if type(rows).__name__ == 'dict':
        rows = [rows]

    pList = []
    for data in rows:

        data['_ptStatus'] = ''

        if myAction == 'INS':
            rec = model()
        else:
            try:
                rec = model.objects.get(pk=data['id'])
            except:
                data['_ptStatus'] = data['_ptStatus'] + ERR_NOEXIST + '<br>'
                pList.append(data)
                continue

        # refAllow verifica si corresponde a los registros modificables  ( solo es true en myAction in ['DEL', 'UPD'] )
        if refAllow and isProtoModel:
            if not (str(rec.smOwningTeam_id) in userNodes):
                data['_ptStatus'] = ERR_REFONLY + '<br>'
                pList.append(data)
                continue

        if not (myAction == 'DEL'):
            # Upd, Ins
            for key in data:
                key = smart_str(key)
                if key in ['id', '_ptStatus', '_ptId', '__str__']:
                    continue

                vFld = fieldsDict[key]
                if vFld.get('crudType') in ["screenOnly", "linked"]:
                    continue

                #  Los campos de seguridad se manejan a nivel registro
                if isProtoModel:
                    if key in [
                            'smOwningUser', 'smOwningTeam', 'smOwningUser_id',
                            'smOwningTeam_id', 'smCreatedBy', 'smModifiedBy',
                            'smCreatedBy_id', 'smModifiedBy_id', 'smCreatedOn',
                            'smModifiedOn', 'smWflowStatus', 'smRegStatus',
                            'smUUID'
                    ]:
                        continue

                #  Udps
                if (cUDP.udpTable
                        and key.startswith(cUDP.propertyPrefix + '__')):
                    continue

                #  JsonField
                if key == jsonField:
                    continue
                if key.startswith(jsonField + '__'):
                    continue

                try:
                    setRegister(model, rec, key, data)
                except Exception as e:
                    data['_ptStatus'] = data['_ptStatus'] + getReadableError(e)

            if isProtoModel:
                setSecurityInfo(rec, data, userProfile, (myAction == 'INS'))

            if len(jsonField) > 0:
                jsonInfo = {}
                for key in data:
                    if not key.startswith(jsonField + '__'):
                        continue
                    jKey = key[len(jsonField) + 2:]
                    jsonInfo[jKey] = data[key]
                setattr(rec, jsonField, jsonInfo)

            # Inicializa el estado del WF
            if hasWFlow:
                setattr(rec, 'smWflowStatus', initialWfStatus)

            # Guarda el idInterno para concatenar registros nuevos en la grilla
            try:
                _ptId = data['_ptId']
            except:
                _ptId = ''

            try:
                rec.save()

                # Guardar las Udps
                if cUDP.udpTable:
                    try:
                        saveUDP(rec, data, cUDP)
                    except Exception as e:
                        raise Exception('UdpError: saveActiob')

                # -- Los tipos complejos ie. date, generan un error, es necesario hacerlo detalladamente
                # Convierte el registro en una lista y luego toma solo el primer elto de la lista resultado.
                data = Q2Dict(protoMeta, [rec], False)[0]
                data['_ptId'] = _ptId

            except Exception as e:
                data['_ptStatus'] = data['_ptStatus'] + getReadableError(e)
                data['_ptId'] = _ptId
                # traceback.print_exc()
                # return doReturn ({'success':False ,'message' : str( e )})

        else:  # Action Delete
            try:
                rec.delete()

            except Exception, e:
                data['_ptStatus'] = data['_ptStatus'] + getReadableError(e)

        pList.append(data)

        if data.get('_ptStatus', ''):
            message += data['_ptStatus'] + ';'