def protoSaveProtoObj(request):
    """ Save full metadata
    
    * objetos del tipo _XXX                   se guardan siempre en CustomDefinition 
    * objetos del tipo prototype.protoTable   se guardan siempre en Prototype 
     
    * Solo los adminstradores tienen el derecho de guardar pcls
    
    custom :  Los objetos de tipo custom, manejan la siguiente llave 
    
        _ColSet.[viewCode]        listDisplaySet  
        _QrySet.[viewCode]        filterSet
        _menu 
    
    Para manejar el modelo en las generacion de protoPci's  se usa :
    
        prototype.protoTable.[protoModel-viewCode]  --> al leer la pcl se leera prototype.protoTable.[protoModel-viewCode]
    
    """

    if request.method != 'POST':
        return JsonError('invalid message') 

    custom = False  
    prototype = False
    create = False 
     
    viewCode = request.POST.get('viewCode', '')

    userProfile = getUserProfile(request.user, 'saveObjs', viewCode) 

    # Reglas para definir q se guarda  
    if viewCode.find('_') == 0 :
        custom = True 
    if viewCode.startswith(PROTO_PREFIX) :
        prototype = True 

    # Carga la meta 
    sMeta = request.POST.get('protoMeta', '')
    
    # Es customProperty 
    if custom: 

        try:
            protoDef, create = CustomDefinition.objects.get_or_create(code=viewCode, smOwningTeam=userProfile.userTeam)
        except Exception as e:
            return JsonError(getReadableError(e)) 

    # Es prototype
    elif prototype: 

        try:
            # debe existir previamente
            protoCode = viewCode.replace(PROTO_PREFIX, '')
            
            protoMeta = json.loads(sMeta)
            entityId = protoMeta['protoEntityId'] 
            entityObj = Entity.objects.get(id=entityId)
            protoDef, create = Prototype.objects.get_or_create(code=protoCode, entity=entityObj, smOwningTeam=userProfile.userTeam)
 
        except Exception as e:
            return JsonError(getReadableError(e)) 

    else: 

        # Verifica los permisos  
        viewEntity = getBaseModelName(viewCode)
        model = getDjangoModel(viewEntity)
        if not getModelPermissions(request.user, model, 'config') : 
            return JsonError('permission denied') 

        try:
            protoDef = ProtoDefinition.objects.get_or_create(code=viewCode)[0]
        except Exception as e:
            return JsonError(getReadableError(e)) 

        protoDef.active = True 
        protoDef.overWrite = False 

        # borra el custom por q confunde haecer modif en un lado y otro 
        try:
            CustomDefinition.objects.filter(code='_custom.' + viewCode, smOwningTeam=userProfile.userTeam).delete()
        except:
            pass

    if custom or prototype: 
        setSecurityInfo(protoDef, {}, userProfile, create)
        

    protoDef.metaDefinition = sMeta 
    protoDef.save()    

    return  JsonSuccess({ 'message': 'Ok' })
def protoGetMenuData(request):
    """
    Cada grupo tiene su propio menu q se construye con las app a las cuales tiene derecho 
    se guarda siempre por grupo en customDefinition,  
    
    Cada usuario tendra una rama de  favoritos para sus opciones frecuentes, 
    el menu es a nivel de grupo  
    """
    
    global ix 

    if not request.user.is_authenticated(): 
        return JsonError('readOnly User')

    if request.method != 'POST': 
        return JsonError('invalid message') 
    
    currentUser = request.user
    userProfile = getUserProfile(currentUser, 'getMenu', '') 

    app_dict = {}

    appAux = cAux()
    appAux.ixApp = 1 
    appAux.ixMod = 1
    

    def getMenuItem(protoAdmin, model, menuNode):
    
        appCode = model._meta.app_label
        
        # Define la rama del menu 
        try:
            menuLabel = model.protoExt["menuApp"]
        except:
            menuLabel = appCode  
        
        if menuLabel in ['contenttypes', 'sites']:
            menuLabel = 'auth' 
        
        # Verifica q el usuairo tenga permiso, considera el admin 
        if not getModelPermissions(currentUser, model, 'menu') :
            return  
        
        pTitle = protoAdmin.get('title', model._meta.verbose_name.title())
    
        # Obtiene el menu de settigs.PROTO_APP          
        try:
            menuDefinition = settings.PROTO_APP.get('app_menu', {}).get(menuLabel, {}) 
        except:
            menuDefinition = {}
            
        if menuDefinition.get('hidden', False):
            return  
    
        # Icono por defecto
        viewIcon = protoAdmin.get('viewIcon', 'icon-1')
    
        model_dict = {
            'viewCode': appCode + '.' + menuNode ,
            'text': pTitle ,
            'index': appAux.ixMod ,
            'iconCls': viewIcon ,
            'leaf': True,
        }
        if menuLabel in app_dict:
            app_dict[menuLabel]['children'].append(model_dict)
    
        else:
            app_dict[menuLabel] = {
                'text': menuDefinition.get('title', menuLabel)  ,
                'expanded': menuDefinition.get('expanded', False) ,
                'index': menuDefinition.get('menu_index', appAux.ixApp),
                'children': [model_dict],
            }
    
            appAux.ixApp += 1
             
        appAux.ixMod += 1 
    

#-- Lectura de la Db ------------------------------------------------------------- 

    forceDefault = request.POST.get('forceDefault', '') 

    viewCode = '__menu'
    protoDef = CustomDefinition.objects.get_or_create(
           code=viewCode, smOwningTeam=userProfile.userTeam,
           defaults={'active': False, 'code' : viewCode, 'smOwningTeam' : userProfile.userTeam }
           )[0]

    # El default solo parece funcionar al insertar en la Db
    if protoDef.active and (forceDefault == '0') :  
        context = protoDef.metaDefinition 

    else:

        for model in models.get_models(include_auto_created=True):
        # for model, model_admin in site._registry.items():
            # protoAdmin = getattr(model_admin, 'protoExt', {})
            menuNode = model._meta.object_name
            protoAdmin = getattr(model, 'protoExt', {}) 
            getMenuItem(protoAdmin, model, menuNode)
    
        # Sort the apps alphabetically.
        app_list = app_dict.values()
        app_list.sort(key=lambda x: x['index'])
    
        # Sort the models alphabetically within each app.
        for app in app_list:
            app['children'].sort(key=lambda x: x['index'])


#=====  lee las opciones del prototipo -----------------------------------------------
        prototypes = Prototype.objects.filter(smOwningTeam=userProfile.userTeam)
        prNodes = {  
            'text': 'ProtoOptions' ,
            'expanded': True ,
            'index': 1000 ,
            'children': [],
            'leaf': False 
        }
        app_list.append(prNodes)

        ix = 0 
        for option in prototypes:

            prBase = getNodeBaseProto(prNodes, option)
            prBase['children'].append({
                'text':  option.code,
                'expanded': True ,
                'viewCode': PROTO_PREFIX + option.code,
                'iconCls': 'icon-proto',
                'index':  ix,
                'leaf': True 
                 })

            ix += 1 

#=====  lee las vistas  -----------------------------------------------
        prototypes = ProtoDefinition.objects.all()
        prNodes = {  
            'text': 'ProtoViews' ,
            'expanded': True ,
            'index': 2000 ,
            'children': [],
            'leaf': False 
        }
        app_list.append(prNodes)

        ix = 0 
        for option in prototypes:

            appName, modName = option.code.split('.')[:2]
            if not getOptionPermissions(currentUser, appName, modName.lower() , 'menu'):
                continue 

            prBase = getNodeBaseViews(prNodes, option)
            if prBase is None: continue  
            prBase['children'].append({
                'text':  option.code,
                'expanded': True ,
                'viewCode': option.code,
                'iconCls': 'icon-1',
                'index':  ix,
                'leaf': True 
                 })

            ix += 1 

        # Pega el menu sobre la definicion anterior  
        try: 
            menuAux = []
            menuTmp = verifyList(json.loads(protoDef.metaDefinition))
            for menuOp in menuTmp:
                if menuOp.get( 'text', '') != 'AutoMenu':
                    menuAux.append (menuOp) 

            menuAux.append({
                    'id': 'prototype.auto.nodes' ,
                    'text': 'AutoMenu' ,
                    'expanded': True,
                    'index': 1000 ,
                    'children': app_list,
                    'leaf': False 
            })
        except: 
            menuAux = app_list 

        context = json.dumps(menuAux) 

        # Lo guarda  ( created : true  --> new
        protoDef.metaDefinition = context  
        protoDef.active = True  
        protoDef.description = 'Menu' 

        setSecurityInfo(protoDef, {}, userProfile, True)

        protoDef.save()
    

    return HttpResponse(context, content_type="application/json")
Beispiel #3
0
def protoSaveProtoObj(request):
    """ Save full metadata
    
    * objetos del tipo _XXX                   se guardan siempre en CustomDefinition 
    * objetos del tipo prototype.protoTable   se guardan siempre en Prototype 
     
    * Solo los adminstradores tienen el derecho de guardar pcls
    
    custom :  Los objetos de tipo custom, manejan la siguiente llave 
    
        _ColSet.[viewCode]        listDisplaySet  
        _QrySet.[viewCode]        filterSet
        _menu 
    
    Para manejar el modelo en las generacion de protoPci's  se usa :
    
        prototype.protoTable.[protoModel-viewCode]  --> al leer la pcl se leera prototype.protoTable.[protoModel-viewCode]
    
    """

    if request.method != 'POST':
        return JsonError('invalid message') 

    custom = False  
    prototype = False
    create = False 
     
    viewCode = request.POST.get('viewCode', '')

    userProfile = getUserProfile(request.user, 'saveObjs', viewCode) 

    # Reglas para definir q se guarda  
    if viewCode.find('_') == 0 :
        custom = True 
    if viewCode.startswith(PROTO_PREFIX) :
        prototype = True 

    # Carga la meta 
    sMeta = request.POST.get('protoMeta', '')
    
    # Es customProperty 
    if custom: 

        try:
            protoDef, create = CustomDefinition.objects.get_or_create(code=viewCode, smOwningTeam=userProfile.userTeam)
        except Exception as e:
            return JsonError(getReadableError(e)) 

    # Es prototype
    elif prototype: 

        try:
            # debe existir previamente
            protoCode = viewCode.replace(PROTO_PREFIX, '')
            
            protoMeta = json.loads(sMeta)
            entityId = protoMeta['protoEntityId'] 
            entityObj = Entity.objects.get(id=entityId)
            protoDef, create = Prototype.objects.get_or_create(code=protoCode, entity=entityObj, smOwningTeam=userProfile.userTeam)
 
        except Exception as e:
            return JsonError(getReadableError(e)) 

    else: 

        # Verifica los permisos  
        viewEntity = getBaseModelName(viewCode)
        model = getDjangoModel(viewEntity)
        if not getModelPermissions(request.user, model, 'config') : 
            return JsonError('permission denied') 

        try:
            protoDef = ProtoDefinition.objects.get_or_create(code=viewCode)[0]
        except Exception as e:
            return JsonError(getReadableError(e)) 

        protoDef.active = True 
        protoDef.overWrite = False 

        # borra el custom por q confunde haecer modif en un lado y otro 
        try:
            CustomDefinition.objects.filter(code='_custom.' + viewCode, smOwningTeam=userProfile.userTeam).delete()
        except:
            pass

    if custom or prototype: 
        setSecurityInfo(protoDef, {}, userProfile, create)
        

    protoDef.metaDefinition = sMeta 
    protoDef.save()    

    return  JsonSuccess({ 'message': 'Ok' })
def protoGetMenuData(request):
    """
    Cada grupo tiene su propio menu q se construye con las app a las cuales tiene derecho 
    se guarda siempre por grupo en customDefinition,  
    
    Cada usuario tendra una rama de  favoritos para sus opciones frecuentes, 
    el menu es a nivel de grupo  
    """
    
    global ix 

    if not request.user.is_authenticated(): 
        return JsonError('readOnly User')

    if request.method != 'POST': 
        return JsonError('invalid message') 
    
    currentUser = request.user
    userProfile = getUserProfile(currentUser, 'getMenu', '') 

    app_dict = {}

    appAux = cAux()
    appAux.ixApp = 1 
    appAux.ixMod = 1
    

    def getMenuItem(protoAdmin, model, menuNode):
    
        appCode = model._meta.app_label
        
        # Define la rama del menu 
        try:
            menuLabel = model.protoExt["menuApp"]
        except:
            menuLabel = appCode  
        
        if menuLabel in ['contenttypes', 'sites']:
            menuLabel = 'auth' 
        
        # Verifica q el usuairo tenga permiso, considera el admin 
        if not getModelPermissions(currentUser, model, 'menu') :
            return  
        
        pTitle = protoAdmin.get('title', model._meta.verbose_name.title())
    
        # Obtiene el menu de settigs.PROTO_APP          
        try:
            menuDefinition = settings.PROTO_APP.get('app_menu', {}).get(menuLabel, {}) 
        except:
            menuDefinition = {}
            
        if menuDefinition.get('hidden', False):
            return  
    
        # Icono por defecto
        viewIcon = protoAdmin.get('viewIcon', 'icon-1')
    
        model_dict = {
            'viewCode': appCode + '.' + menuNode ,
            'text': pTitle ,
            'index': appAux.ixMod ,
            'iconCls': viewIcon ,
            'leaf': True,
        }
        if menuLabel in app_dict:
            app_dict[menuLabel]['children'].append(model_dict)
    
        else:
            app_dict[menuLabel] = {
                'text': menuDefinition.get('title', menuLabel)  ,
                'expanded': menuDefinition.get('expanded', False) ,
                'index': menuDefinition.get('menu_index', appAux.ixApp),
                'children': [model_dict],
            }
    
            appAux.ixApp += 1
             
        appAux.ixMod += 1 
    

#-- Lectura de la Db ------------------------------------------------------------- 

    forceDefault = request.POST.get('forceDefault', '') 

    viewCode = '__menu'
    protoDef = CustomDefinition.objects.get_or_create(
           code=viewCode, smOwningTeam=userProfile.userTeam,
           defaults={'active': False, 'code' : viewCode, 'smOwningTeam' : userProfile.userTeam }
           )[0]

    # El default solo parece funcionar al insertar en la Db
    if protoDef.active and (forceDefault == '0') :  
        context = protoDef.metaDefinition 

    else:

        for model in models.get_models(include_auto_created=True):
        # for model, model_admin in site._registry.items():
            # protoAdmin = getattr(model_admin, 'protoExt', {})
            menuNode = model._meta.object_name
            protoAdmin = getattr(model, 'protoExt', {}) 
            getMenuItem(protoAdmin, model, menuNode)
    
        # Sort the apps alphabetically.
        app_list = app_dict.values()
        app_list.sort(key=lambda x: x['index'])
    
        # Sort the models alphabetically within each app.
        for app in app_list:
            app['children'].sort(key=lambda x: x['index'])


        # lee las opciones del prototipo -----------------------------------------------
        prototypes = Prototype.objects.filter(smOwningTeam=userProfile.userTeam)
        prNodes = {  
            'text': 'ProtoOptions' ,
            'expanded': True ,
            'index': 1000 ,
            'children': [],
            'leaf': False 
        }
        app_list.append(prNodes)

        ix = 0 
        for option in prototypes:

            prBase = getNodeBaseProto(prNodes, option)
            prBase['children'].append({
                'text':  option.code,
                'expanded': True ,
                'viewCode': PROTO_PREFIX + option.code,
                'iconCls': 'icon-proto',
                'index':  ix,
                'leaf': True 
                 })

            ix += 1 

        # lee las vistas 
        prototypes = ProtoDefinition.objects.all()
        prNodes = {  
            'text': 'ProtoViews' ,
            'expanded': True ,
            'index': 2000 ,
            'children': [],
            'leaf': False 
        }
        app_list.append(prNodes)

        ix = 0 
        for option in prototypes:

            prBase = getNodeBaseViews(prNodes, option)
            prBase['children'].append({
                'text':  option.code,
                'expanded': True ,
                'viewCode': option.code,
                'iconCls': 'icon-1',
                'index':  ix,
                'leaf': True 
                 })

            ix += 1 

        # Pega el menu sobre la definicion anterior  
        try: 
            menuAux = []
            menuTmp = verifyList(json.loads(protoDef.metaDefinition))
            for menuOp in menuTmp:
                if menuOp.get( 'text', '') != 'AutoMenu':
                    menuAux.append (menuOp) 

            menuAux.append({
                    'id': 'prototype.auto.nodes' ,
                    'text': 'AutoMenu' ,
                    'expanded': True,
                    'index': 1000 ,
                    'children': app_list,
                    'leaf': False 
            })
        except: 
            menuAux = app_list 

        context = json.dumps(menuAux) 

        # Lo guarda  ( created : true  --> new
        protoDef.metaDefinition = context  
        protoDef.active = True  
        protoDef.description = 'Menu' 

        setSecurityInfo(protoDef, {}, userProfile, True)

        protoDef.save()
    

    return HttpResponse(context, content_type="application/json")