Exemplo n.º 1
0
def GetDetailsConfigTree(protoEntityId):

    lDetails = []

    try:
        pEntity = Entity.objects.get(id=protoEntityId)
    except:
        return lDetails

    # Details
    for pDetail in pEntity.refEntity_set.all():

        detail = {
            "detailField": "info__" + slugify(pDetail.code) + "_id",
            "conceptDetail": PROTO_PREFIX + getViewCode(pDetail.entity),
            "detailName": slugify(pDetail.entity.code),
            "menuText": pDetail.entity.code,
            "masterField": "pk",
            "id": slugify(pDetail.entity.code),
            "leaf": True
        }

        lDetails.append(detail)

    return lDetails
Exemplo n.º 2
0
    def getDiagramDefinition(self, queryset):
        
        self.diagrams = []
        self.arcs = []
        
        for pDiag in queryset:
            
            gDiagram = {
                'code': getClassName(pDiag.code) ,
                'label': pDiag.code ,
                'showBorder' : getattr(pDiag, 'showBorder' , False),
                'arcs': []
            }

            for pDiagComposition in pDiag.artefactcomposition_set.all():

                #  Verifica si el nodo inicial es el contenedor 
                pArc0 = pDiagComposition.inputArt.code
                if gDiagram['label'] == pArc0: pArc0 = 'Start'

                #  Verifica si el nodo final es nulo, entonces end  
                #  Conserva el nombre diagrama y agrega un :Label 
                try: 
                    pArc1 = pDiagComposition.outputArt.code
                except: pArc1 =  'End'

                pArc01 = {
                    'n0': slugify( pArc0 ) ,
                    'n1': slugify( pArc1 )
                }

                self.arcs.append(pArc01)
                gDiagram['arcs'].append(pArc01)
    
            self.diagrams.append(gDiagram)
Exemplo n.º 3
0
def GetDetailsConfigTree( protoEntityId ):
    
    lDetails = []

    try:
        pEntity = Entity.objects.get( id = protoEntityId )
    except: 
        return lDetails 
    
    # Details
    for pDetail in pEntity.refEntity_set.all():
        
        detail =  {
            "detailField": "info__" + slugify( pDetail.code ) + "_id",
            "conceptDetail": PROTO_PREFIX + getViewCode( pDetail.entity  ),
            "detailName": slugify( pDetail.entity.code ),
            "menuText": pDetail.entity.code ,
            "masterField": "pk", 
            
            "id" : slugify( pDetail.entity.code ) ,  
            "leaf" : True 
        }


                    
        lDetails.append( detail ) 
                
    return lDetails 
Exemplo n.º 4
0
def addProtoFiedToList(fieldList, pEntity, fieldBase, zoomName):
    """ Recorre los campos e itera con los fk ( solo un nivel 'fieldBase' )
    """

    for pProperty in pEntity.property_set.all():

        fName = 'info__' + slugify(pProperty.code)

        field = property2Field(fName, pProperty.__dict__, True, fieldBase)

        # Si es un campo heredado ( Se maneja ahora en la pci generada
        if len(fieldBase) > 0:
            field["cpFromZoom"] = fieldBase
            field["cpFromField"] = fName
            field["required"] = False
            field["readOnly"] = True
            field["leaf"] = True

        elif pProperty.isForeign:
            # Agrega el Id
            fieldList.append(getFkId(fName, True, fieldBase))

            # Agrega los parametros del zoom
            zoomEntity = pProperty.relationship.refEntity

            field["zoomModel"] = PROTO_PREFIX + getViewCode(zoomEntity)
            field["fkId"] = fName + "_id"
            field["type"] = "foreigntext"

            fkFieldList = []
            addProtoFiedToList(fkFieldList, zoomEntity, fName,
                               slugify(zoomEntity.code))

            field["leaf"] = False
            field["children"] = fkFieldList

        fieldList.append(field)

    # agrega las props de seguridad
    if len(fieldBase) == 0:
        for fName in [
                'smOwningUser', 'smOwningTeam', 'smCreatedBy', 'smModifiedBy',
                'smWflowStatus', 'smRegStatus', 'smCreatedOn', 'smModifiedOn',
                'smUUID'
        ]:
            propDict = {"name": fName, "readOnly": True}
            field = property2Field(fName, propDict, True)
            fieldList.append(field)
Exemplo n.º 5
0
def createView( pEntity, viewTitle, userProfile ):

    viewName    = slugify( viewTitle )
    infoEntity  = getViewDefinition( pEntity , viewTitle  )

    # Debe corresponder al viewCodegenerado en el template ( infoEntity[viewCode] ) 
    #viewCode = PROTO_PREFIX + viewName
    
    try:
        # Crea el Prototype ( mismo nombre q la vista : necesario para los zooms y los detalles automaticos  )
        rec = Prototype.objects.get_or_create( code = viewName, 
                                               smOwningTeam = userProfile.userTeam, 
              defaults = { 'entity_id' :  pEntity.id } )[0]
    except Exception:
        raise Exception('can\'t create the view') 
    
    rec.metaDefinition = json.dumps( infoEntity, cls=JSONEncoder ) 
    rec.description = infoEntity['description'] 
    
    setSecurityInfo( rec, {}, userProfile, True    )
    rec.save()



# ----
   
    
Exemplo n.º 6
0
def doExportProtoJson( modeladmin, request, queryset, parameters):

    from prototype.actions.exportViews  import exportProtoJson
    

#   El QSet viene con la lista de Ids  
    if queryset.count() != 1:
        return  {'success':False, 'message' : 'No record selected' }

            
#   Envia el QSet con la lista de modelos, 
    try:
        strModel = exportProtoJson ( request, queryset[0] )
    except Exception as e:
        traceback.print_exc()
        return  {'success':False, 'message' : 'Load error' }

        
#   Genera el archvivo py      
    fileName = 'proto_{0}.json'.format( slugify( queryset[0].code ) )
    fullPath = getFullPath( request, fileName )

    fo = open( fullPath , "w")
    fo.write( strModel.encode('utf-8'))
    fo.close()

    return  {'success':True , 'message' : fileName,  'fileName' : fileName }
Exemplo n.º 7
0
 def myStr(self, *args, **kwargs ):
     # Evalua el string de prototipos
     val = ''
     for arg in args:
         try: val = val + '.' + slugify( self.info.get( arg[6:] ) )
         except: pass 
     return  val[1:] 
Exemplo n.º 8
0
 def myStr(self, *args, **kwargs):
     # Evalua el string de prototipos
     val = ''
     for arg in args:
         try:
             val = val + '.' + slugify(self.info.get(arg[6:]))
         except:
             pass
     return val[1:]
Exemplo n.º 9
0
def addProtoFiedToList( fieldList,  pEntity , fieldBase, zoomName   ): 
    """ Recorre los campos e itera con los fk ( solo un nivel 'fieldBase' )
    """    

    for pProperty in pEntity.property_set.all():

        fName  = 'info__' + slugify( pProperty.code ) 

        field = property2Field( fName, pProperty.__dict__ , True,  fieldBase  )

        # Si es un campo heredado ( Se maneja ahora en la pci generada 
        if len( fieldBase ) > 0 :  
            field["cpFromZoom"] = fieldBase   
            field["cpFromField"] = fName 
            field["required"] = False 
            field["readOnly"] = True 
            field["leaf"] = True

        elif pProperty.isForeign:
            # Agrega el Id  
            fieldList.append( getFkId( fName , True, fieldBase ))
            
            # Agrega los parametros del zoom 
            zoomEntity = pProperty.relationship.refEntity
            
            field["zoomModel"]= PROTO_PREFIX + getViewCode( zoomEntity  ) 
            field["fkId"]     = fName + "_id"
            field["type"]     = "foreigntext"

            fkFieldList= []
            addProtoFiedToList( fkFieldList, zoomEntity, fName, slugify( zoomEntity.code ) )

            field["leaf"] = False 
            field["children"] = fkFieldList
      
        fieldList.append( field )
        
    # agrega las props de seguridad         
    if len( fieldBase ) == 0 :  
        for fName in ['smOwningUser','smOwningTeam','smCreatedBy','smModifiedBy','smWflowStatus','smRegStatus','smCreatedOn','smModifiedOn', 'smUUID']: 
            propDict = { "name" : fName, "readOnly": True }
            field = property2Field( fName, propDict, True  )
            fieldList.append( field )
Exemplo n.º 10
0
def doModelGraph(modeladmin, request, queryset, parameters):
    """ 
    funcion para crear el modelo grafico 
    a partir de Model ( doModel )   
    el proyecto enviara la el QSet de todos los modelos 
    """

#   El QSet viene con la lista de Ids  
    if queryset.count() != 1:
        return  {'success':False, 'message' : 'No record selected' }

    try:

        from graphModel import GraphModel 
        gModel = GraphModel()
    
        gModel.getDiagramDefinition( queryset  )
        dotData = gModel.generateDotModel( )

#   Recorre los registros selccionados   
    except Exception as e:
        traceback.print_exc()
        return  {'success':False, 'message' : 'Load error' }
        pass


#   Genera el archvivo dot     
    fileName = 'gm_' + slugify( queryset[0].code ) + '.dot'
    fullPath = getFullPath( request, fileName )
 
    fo = open( fullPath , "wb")
    fo.write( dotData.encode('utf-8'))
    fo.close()
 
    try:
        import pygraphviz
        fileNamePdf = fileName.replace( '.dot', '.pdf') 
        fullPathPdf = getFullPath( request, fileNamePdf )
 
        graph = pygraphviz.AGraph( fullPath )
        graph.layout( prog= 'dot' )
        graph.draw( fullPathPdf, format ='pdf')
 
        fileName = fileNamePdf
    except ImportError:
        pass

    return  {'success':True , 'message' : fileName,  'fileName' : fileName }
Exemplo n.º 11
0
def doModelGraph(modeladmin, request, queryset, parameters):
    """ 
    funcion para crear el modelo grafico 
    a partir de Model ( doModel )   
    el proyecto enviara la el QSet de todos los modelos 
    """

    #   El QSet viene con la lista de Ids
    if queryset.count() != 1:
        return {'success': False, 'message': 'No record selected'}

    try:

        from graphModel import GraphModel
        gModel = GraphModel()

        gModel.getDiagramDefinition(queryset)
        dotData = gModel.generateDotModel()

#   Recorre los registros selccionados
    except Exception as e:
        traceback.print_exc()
        return {'success': False, 'message': 'Load error'}
        pass


#   Genera el archvivo dot
    fileName = 'gm_' + slugify(queryset[0].code) + '.dot'
    fullPath = getFullPath(request, fileName)

    fo = open(fullPath, "wb")
    fo.write(dotData.encode('utf-8'))
    fo.close()

    try:
        import pygraphviz
        fileNamePdf = fileName.replace('.dot', '.pdf')
        fullPathPdf = getFullPath(request, fileNamePdf)

        graph = pygraphviz.AGraph(fullPath)
        graph.layout(prog='dot')
        graph.draw(fullPathPdf, format='pdf')

        fileName = fileNamePdf
    except ImportError:
        pass

    return {'success': True, 'message': fileName, 'fileName': fileName}
Exemplo n.º 12
0
def doExportPrototype(modeladmin, request, queryset, parameters):

    from prototype.actions.exportProto.exportProtoype import exportPrototypeModel

    #   El QSet viene con la lista de Ids
    if queryset.count() != 1:
        return {'success': False, 'message': 'No record selected'}


#   Envia el QSet con la lista de modelos,
    strModel = exportPrototypeModel(request, queryset[0])

    #   Genera el archvivo py
    fileName = 'model_{0}.py'.format(slugify(queryset[0].code))
    fullPath = getFullPath(request, fileName)

    fo = open(fullPath, "w")
    fo.write(strModel.encode('utf-8'))
    fo.close()

    return {'success': True, 'message': fileName, 'fileName': fileName}
Exemplo n.º 13
0
def doModelGraph( modeladmin, request, queryset, parameters):
    """ 
    funcion para crear el modelo grafico 
    a partir de Model ( doModel )   
    el proyecto enviara la el QSet de todos los modelos 
    """

    from graphModel import generateDotModels

#   El QSet viene con la lista de Ids  
    if queryset.count() != 1:
        return  {'success':False, 'message' : 'No record selected' }

            
#   Envia el QSet con la lista de modelos, 
    dotdata = generateDotModels ( queryset )

#   Genera el archvivo dot     
    fileName = 'gm_' + slugify( queryset[0].code ) + '.dot'
    fullPath = getFullPath( request, fileName )

    fo = open( fullPath , "wb")
    fo.write( dotdata.encode('utf-8'))
    fo.close()

    try:
        import pygraphviz
        fileNamePdf = fileName.replace( '.dot', '.pdf') 
        fullPathPdf = getFullPath( request, fileNamePdf )

        graph = pygraphviz.AGraph( fullPath )
        graph.layout( prog= 'dot' )
        graph.draw( fullPathPdf, format ='pdf')

        fileName = fileNamePdf
    except ImportError:
        pass

    return  {'success':True , 'message' : fileName,  'fileName' : fileName }
Exemplo n.º 14
0
def createView(pEntity, viewTitle, userProfile):

    viewName = slugify(viewTitle)
    infoEntity = getViewDefinition(pEntity, viewTitle)

    # Debe corresponder al viewCodegenerado en el template ( infoEntity[viewCode] )
    #viewCode = PROTO_PREFIX + viewName

    try:
        # Crea el Prototype ( mismo nombre q la vista : necesario para los zooms y los detalles automaticos  )
        rec = Prototype.objects.get_or_create(
            code=viewName,
            smOwningTeam=userProfile.userTeam,
            defaults={'entity_id': pEntity.id})[0]
    except Exception:
        raise Exception('can\'t create the view')

    rec.metaDefinition = json.dumps(infoEntity, cls=JSONEncoder)
    rec.description = infoEntity['description']

    setSecurityInfo(rec, {}, userProfile, True)
    rec.save()
Exemplo n.º 15
0
def docProperty2Field( fName, propDict, fBase = 'info' ):
    """ Genera la definicion del campo en la pci a partir de un diccionario (RAI) 
    """

    from protoLib.utilsBase import slugify
    fCode = slugify( fName )

    field =  { 
        "name"    : '{0}__{1}'.format( fBase, fCode ), 
        "header"  : propDict.get('code', fName),
        "type"    : propDict.get('baseType', 'string'), 
        "required": propDict.get('isRequired', False),
        "tooltip" : propDict.get('description',''), 
        "vType"   : propDict.get('vType',''),   
        "choices" : propDict.get('prpChoices', '') ,
        "prpDefault" : propDict.get('prpDefault', '') , 
        "prpLength"  : propDict.get('prpLength', '') , 
        "prpScale"   : propDict.get('prpScale', '') , 
        "crudType"   : propDict.get('crudType', '') , 
        "readOnly": propDict.get('isReadOnly', False) ,
    }
    
    return field 
Exemplo n.º 16
0
def doExport2Json( modeladmin, request, queryset, parameters):

    
    from prototype.actions.export2json  import exportPrototype2Json
    

#   El QSet viene con la lista de Ids  
    if queryset.count() != 1:
        return  {'success':False, 'message' : 'No record selected' }

            
#   Envia el QSet con la lista de modelos, 
    strModel = exportPrototype2Json( request, queryset[0] )
        
#   Genera el archvivo py      
    fileName = 'model_{0}.jex'.format( slugify( queryset[0].code ) )
    fullPath = getFullPath( request, fileName )

    fo = open( fullPath , "w")
    fo.write( strModel.encode('utf-8'))
    fo.close()

    return  {'success':True , 'message' : fileName,  'fileName' : fileName }
Exemplo n.º 17
0
def doExportProtoJson(modeladmin, request, queryset, parameters):

    from prototype.actions.exportViews import exportProtoJson

    #   El QSet viene con la lista de Ids
    if queryset.count() != 1:
        return {'success': False, 'message': 'No record selected'}

#   Envia el QSet con la lista de modelos,
    try:
        strModel = exportProtoJson(request, queryset[0])
    except Exception as e:
        traceback.print_exc()
        return {'success': False, 'message': 'Load error'}

#   Genera el archvivo py
    fileName = 'proto_{0}.json'.format(slugify(queryset[0].code))
    fullPath = getFullPath(request, fileName)

    fo = open(fullPath, "w")
    fo.write(strModel.encode('utf-8'))
    fo.close()

    return {'success': True, 'message': fileName, 'fileName': fileName}
Exemplo n.º 18
0
 def __unicode__(self):
     return slugify(str( self.domaff_projet) +  '.' + self.nom_projet)
Exemplo n.º 19
0
 def __unicode__(self):
     return slugify(self.nom_specification)
Exemplo n.º 20
0
 def __unicode__(self):
     return slugify(str( self.entite_rela1) +  '.' + str( self.entite_rela2) +  '.' + self.nom_relation)
Exemplo n.º 21
0
 def __unicode__(self):
     return slugify(self.project.code + '-' + self.code)
Exemplo n.º 22
0
 def __unicode__(self):
     return slugify(str( self.domaff_modele) +  '.' + self.nom_modele)
Exemplo n.º 23
0
 def __unicode__(self):
     return slugify(self.no_raccordement)
Exemplo n.º 24
0
 def __unicode__(self):
     return slugify(
         str(self.entite_rela1) + '.' + str(self.entite_rela2) + '.' +
         self.nom_relation)
Exemplo n.º 25
0
 def __unicode__(self):
     return slugify(self.id_domaine_affaires)
Exemplo n.º 26
0
 def __unicode__(self):
     return slugify(self.nom_entite + '.' + str(self.entite_mod))
Exemplo n.º 27
0
def exportPrototypeModel(request, pModel):

    strModel = StringIO()
    modelCode = slugify(pModel.code, '_')

    strModel.write("# -*- coding: utf-8 -*-\n\n")
    strModel.write(
        '# This is an auto-generated model module by CeRTAE SoftMachine v13.12dgt\n'
    )
    strModel.write("# for model : \"{0}\"\n".format(modelCode))
    strModel.write(
        "# You'll have to do the following manually to clean this up:\n")
    strModel.write("#     * Add specific procedures  (WFlow)\n\n")
    strModel.write("from django.db import models\n")
    strModel.write("from protoLib.models import ProtoModel\n")
    strModel.write("from protoLib.utilsBase import slugify\n")

    for pEntity in pModel.entity_set.all():

        strModel.write("\n")
        strModel.write("class {0}(ProtoModel):\n".format(
            getClassName(pEntity.code)))

        arrKeys = []

        #  Field Str Formating
        #     0. pCode,
        #     1. pType,
        #     2. strNull,
        #     3. str( intLength ),
        #     4. str( intScale )
        #     5. slugify(pEntity.code, '_')

        for pProperty in pEntity.property_set.all():

            pCode = slugify(pProperty.code, '_')

            if pProperty.isForeign:
                pType = getClassName(pProperty.relationship.refEntity.code)
                strAux = "{0} = models.ForeignKey('{1}', blank= {2}, null= {2}, related_name='{5}_{0}')\n"
                # RelatedName Entity_Field?
#               on_delete={5} : CASCADE, PROTECT, SET_NULL

            else:
                pType = TypeEquivalence.get(pProperty.baseType, 'CharField')
                #               prpDefault

                intLength = pProperty.prpLength
                intScale = pProperty.prpScale

                if pType == 'CharField':
                    strAux = "{0} = models.{1}(blank= {2}, null= {2}, max_length= {3})\n"
                    if intLength == 0:
                        intLength = 200

                elif pType == 'DecimalField':
                    strAux = "{0} = models.{1}(blank= {2}, null= {2}, max_digits={3}, decimal_places= {4})\n"

                    if intLength == 0 or intLength > 24:
                        intLength = 48
                    if intScale < 0 or intScale > intLength:
                        intScale = 2

                elif pType == 'BooleanField':
                    strAux = "{0} = models.{1}()\n"

                else:
                    strAux = "{0} = models.{1}(blank = {2}, null = {2})\n"

#               isRequired isNullable:
            if pProperty.isRequired:
                strNull = 'False'
            else:
                strNull = 'True'

            if pProperty.isPrimary:
                arrKeys.append(pCode)

            strModel.write(
                repStr(' ', 4) +
                strAux.format(pCode, pType, strNull, str(intLength),
                              str(intScale), slugify(pEntity.code, '_')))

        strModel.write("\n")
        strModel.write(repStr(' ', 4) + "def __unicode__(self):\n")

        if arrKeys.__len__() > 0:

            # Unicode
            strOptions = ''
            for pProperty in pEntity.property_set.all():
                if not pProperty.isPrimary: continue
                if strOptions.__len__() > 0: strOptions += " +  '.' + "

                if pProperty.isForeign or not (pProperty.baseType
                                               in ['string', 'text']):
                    strAux = 'str( self.{0})'.format(
                        slugify(pProperty.code, '_'))
                else:
                    strAux = 'self.{0}'.format(slugify(pProperty.code, '_'))
                strOptions += strAux

            strModel.write(
                repStr(' ', 8) + "return slugify({0})\n".format(strOptions))

            #meta
            strModel.write("\n")
            strModel.write(repStr(' ', 4) + "class Meta:\n")

            strOptions = ''
            for pCode in arrKeys:
                strOptions += "'{0}',".format(pCode)

            strModel.write(
                repStr(' ', 8) +
                "unique_together = ({0})\n".format(strOptions))

        else:

            strModel.write(repStr(' ', 8) + "return 'NoKey'")

    strAux = strModel.getvalue()
    strModel.close()

    return strAux
Exemplo n.º 28
0
 def __unicode__(self):
     return slugify(str( self.eledon_regles) +  '.' + self.id_regles_gestion)
Exemplo n.º 29
0
 def __unicode__(self):
     return slugify(self.code_norme)
Exemplo n.º 30
0
 def __unicode__(self):
     return slugify(self.nom_specification)
Exemplo n.º 31
0
def exportProtoJson(request, pModel):

    cViews = {
        'code': pModel.code,
        'model': slugify(pModel.code, '_'),
        'entities': {},
    }

    for pEntity in pModel.entity_set.all():

        # Do not delete ( dgt )
        cEntity = {
            'code': pEntity.code,
            'entity': getClassName(pEntity.code),
            'fullName': cViews['model'] + '.' + getClassName(pEntity.code),
            #          'properties' : {},
            'prototypes': {},
        }

        cViews['entities'][cEntity['code']] = cEntity

        #         Do not delete  ( dgt )
        #         for pProperty in pEntity.property_set.all():
        #
        #
        #             cProperty =  {
        #                 'code'      : pProperty.code,
        #                 'property'  : slugify(pProperty.code, '_'),
        #                 'isForeign' : pProperty.isForeign,
        #
        #                 'baseType'   : pProperty.baseType,
        #                 'prpLength'  : pProperty.prpLength,
        #                 'prpScale'   : pProperty.prpScale,
        #
        #                 'isPrimary'   : pProperty.isPrimary,
        #                 'isReadOnly'  : pProperty.isReadOnly,
        #
        #                 'isNullable'  : pProperty.isNullable,
        #                 'isRequired'  : pProperty.isRequired,
        #                 'isSensitive' : pProperty.isSensitive,
        #                 'prpChoices'  : pProperty.prpChoices,
        #                 'prpDefault'  : pProperty.prpDefault,
        #                 'vType'       : pProperty.vType,
        #
        #                 'crudType'    : pProperty.crudType,
        #                 'description' : pProperty.description,
        #                 'notes'       : pProperty.notes,
        #
        #                 'dbName'      : pProperty.dbName,
        #                 'isEssential' : pProperty.isEssential,
        #                 'isLookUpResult' : pProperty.isLookUpResult,
        #             }
        #
        #
        #             if pProperty.isForeign:
        #                 cProperty[ 'refEntity' ]    = pProperty.relationship.refEntity.code
        #                 cProperty[ 'refCode' ]      = getClassName( pProperty.relationship.refEntity.code )
        #
        #                 cProperty[ 'baseMax']       = pProperty.relationship.baseMax
        #                 cProperty[ 'baseMin']       = pProperty.relationship.baseMin
        #                 cProperty[ 'onRefDelete']   = pProperty.relationship.onRefDelete
        #                 cProperty[ 'refMax']        = pProperty.relationship.refMax
        #                 cProperty[ 'refMin']        = pProperty.relationship.refMin
        #                 cProperty[ 'relatedName']   = pProperty.relationship.relatedName
        #                 cProperty[ 'typeRelation']  = pProperty.relationship.typeRelation
        #
        #             cEntity['properties'][ cProperty['code'] ]  = cProperty

        for pPrototype in pEntity.prototype_set.all():

            # Migration proto - App
            sAux = pPrototype.metaDefinition.replace("info__",
                                                     "").replace("-", "_")
            sAux = sAux.replace("prototype.ProtoTable.", "")
            sAux = sAux.replace('"' + slugify(pModel.code, '_') + '_',
                                '"' + cViews['model'] + '.')

            cProto = json.loads(sAux)

            # Propiedades de base
            try:
                del cProto['jsonField']
                del cProto['protoEntity']
                del cProto['protoEntityId']
                del cProto['__ptType']
            except:
                pass

            cProto['localSort'] = False
            cProto['viewIcon'] = 'icon-1'
            cProto['viewEntity'] = cEntity['fullName']

            # Elimina campos de control de prototypos y redirecciona zooms
            newFields = []
            for fld in cProto['fields']:
                if fld['name'] in ['entity', 'entity_id', 'info']:
                    continue
                if fld['name'] == '__str__':
                    try:
                        del fld['cpFromZoom']
                        del fld['cpFromField']
                        del fld['physicalName']
                    except:
                        pass

                try:
                    del fld['__ptType']
                except:
                    pass
                newFields.append(fld)

            cProto['fields'] = newFields

            cPrototype = {
                'code': pPrototype.code,
                'description': pPrototype.description,
                'notes': cEntity['fullName'],
                'metaDefinition': cProto
            }

            cEntity['prototypes'][cPrototype['code']] = cPrototype

            # Creacion de la vista
            try:
                protoDef = ProtoDefinition.objects.get_or_create(
                    code=cProto['viewCode'])[0]
                protoDef.active = True
                protoDef.overWrite = False
                protoDef.description = cEntity.get('fullName',
                                                   '') + ' - ' + cProto.get(
                                                       'viewCode', '') + '<br>'
                protoDef.description += cProto.get(
                    'shortTitle', '') + '<br>' + cProto.get('description', '')

                protoDef.metaDefinition = json.dumps(cProto, cls=JSONEncoder)
                protoDef.save()

            except:
                pass

    return json.dumps(cViews,
                      cls=JSONEncoder,
                      sort_keys=True,
                      indent=4,
                      separators=(',', ':'))
Exemplo n.º 32
0
 def __unicode__(self):
     return slugify(self.nom_donnee)
Exemplo n.º 33
0
def baseDefinition( pEntity , entityName, viewTitle  ):
    """ protoEntity: Es la traza de la generacion del protipo  dominio.modelo.entidad  
    """ 
    
    viewName   = slugify( viewTitle  )

    return  {
    "__ptType": "pcl",
    "viewEntity": "prototype.ProtoTable",
    "viewCode" : PROTO_PREFIX + viewName,
    "protoEntity" : entityName,  
    "protoEntityId" : pEntity.id,  
    "description" : pEntity.description ,
    "jsonField"   : "info" ,
    "viewIcon"   : "icon-proto",
    "localSort"   : True, 
    "shortTitle"  : viewTitle,
    "updateTime"  : datetime.now(),
    "metaVersion" : "13.0301",
    "idProperty"  : "id",
    "fields": [
        {
            "name": "id",
            "readOnly": True,
            "hidden": True,
            "type": "autofield"
        },
        {
            "name": "entity",
            "readOnly": True,
            "hidden": True,
        },
        {
            "name": "entity_id",
            "readOnly": True,
            "hidden": True,
            "prpDefault" : pEntity.id, 
        },
        {
            "name": "info",
            "searchable": True,
            "readOnly": True,
            "hidden": True,
            "type": "jsonfield",
        },               
        {
            "name": "smOwningUser",
            "readOnly": True,
            "type": "foreigntext"
        },
        {
            "name": "smOwningTeam",
            "readOnly": True,
            "type": "foreigntext"
        },
        {
            "name": "smCreatedOn",
            "readOnly": True,
            "type": "datetime"
        },
#        {
#            "name": "smModifiedOn",
#            "readOnly": True,
#            "type": "datetime"
#        },
#        {
#            "zoomModel": "auth.User",
#            "name": "smModifiedBy",
#            "readOnly": True,
#            "type": "foreigntext"
#        },
#        {
#            "name": "smRegStatus",
#            "readOnly": True,
#            "type": "string"
#        },
#        {
#            "zoomModel": "auth.User",
#            "name": "smCreatedBy",
#            "readOnly": True,
#            "type": "foreigntext"
#        },
#        {
#            "name": "smWflowStatus",
#            "readOnly": True,
#            "type": "string"
#        }
    ],
    "detailsConfig": [],
    "gridConfig": {
        "listDisplay": [],
        "baseFilter": [],
        "searchFields": [ "info",],
        "sortFields": [],
        "hiddenFields": [ "id", "info", "entity_id" ],
        "readOnlyFields": [],
    },
    "formConfig": {
        "__ptType": "formConfig",
        "items": [
            {
                "__ptType": "fieldset",
                "fsLayout": "2col",
                "items": []
            },
#            {
#                "__ptType": "fieldset",
#                "collapsible": True,
#                "title": "Admin",
#                "collapsed": True,
#                "fsLayout": "2col",
#                "items": [
#                    {
#                        "__ptType": "formField",
#                        "name": "smOwningUser"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smOwningTeam"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smModifiedBy"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smCreatedBy"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smModifiedOn"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smCreatedOn"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smRegStatus"
#                    },
#                    {
#                        "__ptType": "formField",
#                        "name": "smWflowStatus"
#                    }
#                ]
#            }
        ]
    }
}    
Exemplo n.º 34
0
 def __unicode__(self):
     return slugify(str(self.domaff_projet) + '.' + self.nom_projet)
Exemplo n.º 35
0
def baseDefinition(pEntity, entityName, viewTitle):
    """ protoEntity: Es la traza de la generacion del protipo  dominio.modelo.entidad  
    """

    viewName = slugify(viewTitle)

    return {
        "__ptType":
        "pcl",
        "viewEntity":
        "prototype.ProtoTable",
        "viewCode":
        PROTO_PREFIX + viewName,
        "protoEntity":
        entityName,
        "protoEntityId":
        pEntity.id,
        "description":
        pEntity.description,
        "jsonField":
        "info",
        "viewIcon":
        "icon-proto",
        "localSort":
        True,
        "shortTitle":
        viewTitle,
        "updateTime":
        datetime.now(),
        "metaVersion":
        "13.0301",
        "idProperty":
        "id",
        "fields": [
            {
                "name": "id",
                "readOnly": True,
                "hidden": True,
                "type": "autofield"
            },
            {
                "name": "entity",
                "readOnly": True,
                "hidden": True,
            },
            {
                "name": "entity_id",
                "readOnly": True,
                "hidden": True,
                "prpDefault": pEntity.id,
            },
            {
                "name": "info",
                "searchable": True,
                "readOnly": True,
                "hidden": True,
                "type": "jsonfield",
            },
            {
                "name": "smOwningUser",
                "readOnly": True,
                "type": "foreigntext"
            },
            {
                "name": "smOwningTeam",
                "readOnly": True,
                "type": "foreigntext"
            },
            {
                "name": "smCreatedOn",
                "readOnly": True,
                "type": "datetime"
            },
            #        {
            #            "name": "smModifiedOn",
            #            "readOnly": True,
            #            "type": "datetime"
            #        },
            #        {
            #            "zoomModel": "auth.User",
            #            "name": "smModifiedBy",
            #            "readOnly": True,
            #            "type": "foreigntext"
            #        },
            #        {
            #            "name": "smRegStatus",
            #            "readOnly": True,
            #            "type": "string"
            #        },
            #        {
            #            "zoomModel": "auth.User",
            #            "name": "smCreatedBy",
            #            "readOnly": True,
            #            "type": "foreigntext"
            #        },
            #        {
            #            "name": "smWflowStatus",
            #            "readOnly": True,
            #            "type": "string"
            #        }
        ],
        "detailsConfig": [],
        "gridConfig": {
            "listDisplay": [],
            "baseFilter": [],
            "searchFields": [
                "info",
            ],
            "sortFields": [],
            "hiddenFields": ["id", "info", "entity_id"],
            "readOnlyFields": [],
        },
        "formConfig": {
            "__ptType":
            "formConfig",
            "items": [
                {
                    "__ptType": "fieldset",
                    "fsLayout": "2col",
                    "items": []
                },
                #            {
                #                "__ptType": "fieldset",
                #                "collapsible": True,
                #                "title": "Admin",
                #                "collapsed": True,
                #                "fsLayout": "2col",
                #                "items": [
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smOwningUser"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smOwningTeam"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smModifiedBy"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smCreatedBy"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smModifiedOn"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smCreatedOn"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smRegStatus"
                #                    },
                #                    {
                #                        "__ptType": "formField",
                #                        "name": "smWflowStatus"
                #                    }
                #                ]
                #            }
            ]
        }
    }
Exemplo n.º 36
0
 def __unicode__(self):
     return slugify(str(self.mod_regrou) + '.' + str(self.projet_regro))
Exemplo n.º 37
0
 def __unicode__(self):
     return slugify(self.id_domaine_affaires)
Exemplo n.º 38
0
 def __unicode__(self):
     return slugify(str(self.eledon_regles) + '.' + self.id_regles_gestion)
Exemplo n.º 39
0
 def __unicode__(self):
     return slugify( self.no_raccordement )
Exemplo n.º 40
0
 def __unicode__(self):
     return slugify(str(self.eledon_portee))
Exemplo n.º 41
0
 def __unicode__(self):
     return slugify(self.nom_donnee)
Exemplo n.º 42
0
 def __unicode__(self):
     return slugify(self.code_norme)
Exemplo n.º 43
0
 def __unicode__(self):
     return slugify(str( self.mod_regrou) +  '.' + str( self.projet_regro))
Exemplo n.º 44
0
 def __unicode__(self):
     return slugify(self.code_type_regle)
Exemplo n.º 45
0
 def __unicode__(self):
     return slugify(str( self.eledon_portee))
Exemplo n.º 46
0
 def __unicode__(self):
     return slugify(str(self.domaff_modele) + '.' + self.nom_modele)
Exemplo n.º 47
0
 def __unicode__(self):
     return slugify(self.code_type_regle)
Exemplo n.º 48
0
 def __unicode__(self):
     return slugify(self.sourceProperty.code + ' - ' +
                    self.targetProperty.code)
Exemplo n.º 49
0
 def __unicode__(self):
     return slugify(self.nom_entite +  '.' + str( self.entite_mod))
Exemplo n.º 50
0
 def __unicode__(self):
     return slugify(self.entity.code + '.' + self.code)
Exemplo n.º 51
0
 def __unicode__(self):
     return slugify(self.model.code + '-' + self.code)
Exemplo n.º 52
0
 def __unicode__(self):
     return slugify(str( self.cat_class) +  '.' + str( self.log_class))
Exemplo n.º 53
0
def exportPrototypeModel(request, pModel ):

    strModel = StringIO()        
    modelCode = slugify(pModel.code, '_')

    strModel.write("# -*- coding: utf-8 -*-\n\n")
    strModel.write('# This is an auto-generated model module by CeRTAE SoftMachine v13.12dgt\n' )  
    strModel.write("# for model : \"{0}\"\n".format( modelCode ) )  
    strModel.write("# You'll have to do the following manually to clean this up:\n")
    strModel.write("#     * Add specific procedures  (WFlow)\n\n")
    strModel.write("from django.db import models\n")
    strModel.write("from protoLib.models import ProtoModel\n")    
    strModel.write("from protoLib.utilsBase import slugify\n")

    for pEntity in pModel.entity_set.all():

        strModel.write( "\n" ) 
        strModel.write( "class {0}(ProtoModel):\n".format( getClassName( pEntity.code )  )) 
                         
        arrKeys  = []
                                                     
        for pProperty in pEntity.property_set.all():
            
            pCode = slugify(pProperty.code, '_')
            
            if pProperty.isForeign:
                pType  = getClassName( pProperty.relationship.refEntity.code ) 
                strAux = "{0} = models.ForeignKey('{1}', blank= {2}, null= {2}, related_name='+')\n"
#                   on_delete={5} : CASCADE, PROTECT, SET_NULL 
                
            else: 
                pType  = TypeEquivalence.get( pProperty.baseType , 'CharField')
#                   prpDefault

                intLength = pProperty.prpLength 
                intScale  = pProperty.prpScale  

                if pType == 'CharField':
                    strAux = "{0} = models.{1}(blank= {2}, null= {2}, max_length= {3})\n"
                    if intLength == 0: intLength = 200 
                    
                elif pType == 'DecimalField':
                    strAux = "{0} = models.{1}(blank= {2}, null= {2}, max_digits={3}, decimal_places= {4})\n"

                    if intLength == 0 or intLength > 24  : intLength = 48 
                    if intScale  <  0 or intScale  > intLength : intScale = 2 

                elif pType == 'BooleanField':
                    strAux = "{0} = models.{1}()\n"
                    
                else: 
                    strAux = "{0} = models.{1}(blank = {2}, null = {2})\n"

#               isRequired isNullable: 
            if pProperty.isRequired: strNull = 'False'
            else: strNull = 'True'

            if pProperty.isPrimary: 
                arrKeys.append( pCode ) 

            strModel.write( repStr(' ',4) + strAux.format( 
                          pCode,
                          pType, 
                          strNull,
                          str( intLength ), 
                          str( intScale ) 
                          ))  
            

        strModel.write("\n")
        strModel.write(repStr(' ',4)+ "def __unicode__(self):\n")

        if arrKeys.__len__() > 0:

            # Unicode 
            strOptions = ''
            for pProperty in pEntity.property_set.all():
                if not pProperty.isPrimary : continue
                if strOptions.__len__() > 0:  strOptions += " +  '.' + " 

                if pProperty.isForeign or not ( pProperty.baseType in  [ 'string', 'text' ] ):
                    strAux = 'str( self.{0})'.format( slugify(pProperty.code, '_'))
                else :  strAux = 'self.{0}'.format( slugify(pProperty.code, '_'))  
                strOptions += strAux  

            strModel.write( repStr(' ',8) + "return slugify({0})\n".format( strOptions ))


            #meta 
            strModel.write("\n")
            strModel.write(repStr(' ',4)+ "class Meta:\n")
            
            strOptions = ''
            for pCode in arrKeys:
                strOptions +=  "'{0}',".format( pCode ) 
 
            strModel.write( repStr(' ',8) + "unique_together = ({0})\n".format( strOptions ))

        else: 

            strModel.write( repStr(' ',8) + "return 'NoKey'")
                
    strAux = strModel.getvalue()
    strModel.close()

    return strAux  
Exemplo n.º 54
0
 def __unicode__(self):
     return slugify(str( self.lan_lanuti) +  '.' + str( self.log_lanuti))
Exemplo n.º 55
0
def generateDotModels( queryset ):
    
    disable_fields = False  
    use_subgraph =  False  

    # Abre el template 
    t = loader.get_template('graph_models/head.html')
    c = Context({})
    dot = t.render(c)

    gModels = []
    for pModel in queryset:
        
        modelCode = slugify( pModel.code, '_' )
        
        gModel = Context({
            'name': '"%s"' % modelCode ,
            'app_name': "%s" % modelCode ,
            'cluster_app_name': modelCode,
            'disable_fields': disable_fields,
            'use_subgraph': use_subgraph,
            'models': []
        })

        for pEntity in pModel.entity_set.all():
            enttCode = slugify( pEntity.code , '_')
            gEntity = {
                'app_name': modelCode,
                'name': enttCode,
                'label': enttCode,
                'abstracts': [],
                'fields': [],
                'relations': []
            }

            for pProperty in pEntity.property_set.all():

                pptCode =  slugify( pProperty.code, '_' ) 
                if pProperty.isForeign:
                    pType = slugify( pProperty.relationship.refEntity.code , '_') 
                else: pType = slugify( pProperty.baseType , '_')

                gEntity['fields'].append({
                    'name': pptCode,
                    'label': pptCode,
                    'type': pType or 'string',
                    'blank': not pProperty.isPrimary,
                    'abstract': not pProperty.isRequired,
                })

                # relations
                if pProperty.isForeign:
                    if not pProperty.isRequired: 
                        extras = '[arrowhead=empty, arrowtail=dot]'
                    else: extras  = ''  # [arrowhead=none, arrowtail=none]
    
                    label = pptCode + ' (%s)' % pType
    
                    # handle self-relationships
                    _rel = {
                        'target_app': modelCode ,
                        'target': pType ,
                        'type': pType,
                        'name': pptCode + '_' + pType,
                        'label': label,
                        'arrows': extras,
                        'needs_node': True
                    }

                    gEntity['relations'].append(_rel)

            gModel['models'].append(gEntity)

        gModels.append(gModel)

    # ------------------------------------------------------------------------------------
    nodes = []
    for gModel in gModels:
        nodes.extend([e['name'] for e in gModel['models']])

    for gModel in gModels:
        # don't draw duplication nodes because of relations
        for gEntity in gModel['models']:
            for relation in gEntity['relations']:
                if relation['target'] in nodes:
                    relation['needs_node'] = False
        # render templates
        t = loader.get_template('graph_models/body.html')
        dot += '\n' + t.render(gModel)

    for gModel in gModels:
        t = loader.get_template('graph_models/rel.html')
        dot += '\n' + t.render(gModel)

    t = loader.get_template('graph_models/tail.html')
    c = Context({})
    dot += '\n' + t.render(c)
    return dot
Exemplo n.º 56
0
 def __unicode__(self):
     return slugify(self.diagram.code + '-' + self.entity.code)
Exemplo n.º 57
0
def getViewDefinition( pEntity, viewTitle  ):

    entityName = getViewCode( pEntity  )

    infoEntity = baseDefinition( pEntity, entityName, viewTitle  )
    infoEntity['gridConfig']['baseFilter'] = [ { 'property':'entity', 'filterStmt' : '=' + str( pEntity.id )  } ]

    #para crear el campo __str__:  se arma con las llaves definidas como primarias o unicas 
    __str__Base = []
    #infoEntity['gridConfig']['listDisplay'].append( '__str__' )

    for pProperty in pEntity.property_set.order_by('id'):

        fName  = 'info__' + slugify( pProperty.code ) 
        field = property2Field( fName, pProperty.__dict__ )

        if pProperty.isForeign: 
            field["zoomModel"]= PROTO_PREFIX + getViewCode( pProperty.relationship.refEntity ) 
            field["fkId"]     = fName + "_id"
            field["type"]     = "foreigntext"

            infoEntity['fields'].append( getFkId( fName ) )
        
        infoEntity['fields'].append( field )

        # hace las veces de __str__   
        if pProperty.isPrimary or pProperty.isLookUpResult:
            __str__Base.append( fName )

        # DP solicito se generaran todos los campos en la grilla 130308 )
        if  pProperty.isEssential or len( infoEntity['gridConfig']['listDisplay'] ) <= 7 : 
            infoEntity['gridConfig']['listDisplay'].append( fName )


        # forma y ordenamiento    
        infoEntity['gridConfig']['sortFields'].append( fName )
        infoEntity['formConfig']['items'][0]['items'].append( { "name": fName, "__ptType": "formField" } )

    # Al menos incluye el str
    if len (  infoEntity['gridConfig']['listDisplay'] ) ==  0: 
        infoEntity['gridConfig']['listDisplay'].append( '__str__' )

    #  __str__, __unicode__
    field = {
        "flex": 1,
        "sortable": True,
        "name": "__str__",
        "fkId": "id",
        "zoomModel": PROTO_PREFIX + slugify( viewTitle  ),
        "cellLink": True,
        "header": viewTitle,
        "readOnly": True,
        "type": "string",
        "physicalName" : '@myStr("' + '","'.join(__str__Base) + '")'
    }
    fName = '__str__'
    infoEntity['fields'].append( field )
    infoEntity['gridConfig']['sortFields'].append( fName )
            
    # Details
    for pDetail in pEntity.refEntity_set.all():
        detail =  {
            "detailField": "info__" + slugify( pDetail.code ) + "_id",
            "conceptDetail": PROTO_PREFIX + getViewCode( pDetail.entity  ),
            "detailName": slugify( pDetail.entity.code ),
            "menuText": pDetail.entity.code ,
            "masterField": "pk"
        }
                    
        infoEntity['detailsConfig'].append( detail )             
            
    return infoEntity
Exemplo n.º 58
0
def getViewCode(pEntity, viewTitle=None):
    if viewTitle is None:
        viewTitle = pEntity.code
    return slugify(pEntity.model.code + '-' + viewTitle)
Exemplo n.º 59
0
    def getDiagramDefinition(self, diagramSet):

        self.diagrams = []
        self.entities = []

        for pDiag in diagramSet:

            gDiagram = {
                'code': getClassName(pDiag.code),
                'label': pDiag.code,
                'clusterName': getattr(pDiag, 'title', pDiag.code),
                'graphLevel': getattr(pDiag, 'graphLevel',
                                      self.GRAPH_LEVEL.all),
                'graphForm': getattr(pDiag, 'graphForm', self.GRAPH_FORM.orf),
                'showPrpType': getattr(pDiag, 'showPrpType', False),
                'showBorder': getattr(pDiag, 'showBorder', False),
                'prefix': getattr(pDiag, 'prefix', ''),
                'entities': []
            }

            for pDiagEntity in pDiag.diagramentity_set.all():

                pEntity = pDiagEntity.entity
                enttCode = self.getEntityCode(pEntity.code,
                                              gDiagram.get('prefix'))

                if enttCode in self.entities:
                    continue

                self.entities.append(enttCode)

                gEntity = {'code': enttCode, 'fields': [], 'relations': []}

                for pProperty in pEntity.property_set.all():

                    pptCode = slugify(pProperty.code, '_')

                    if pProperty.isForeign:
                        pType = self.getEntityCode(
                            pProperty.relationship.refEntity.code,
                            gDiagram.get('prefix'))

                        gEntity['relations'].append({
                            'code': pptCode,
                            'type': pType,
                            'primary': pProperty.isPrimary,
                            'required': pProperty.isRequired,
                            'essential': pProperty.isEssential,
                            'foreign': True
                        })

                    else:
                        pType = slugify(pProperty.baseType, '_')

                        gEntity['fields'].append({
                            'code': pptCode,
                            'type': pType or 'string',
                            'primary': pProperty.isPrimary,
                            'required': pProperty.isRequired,
                            'essential': pProperty.isEssential,
                            'foreign': False
                        })

                gDiagram['entities'].append(gEntity)

            self.diagrams.append(gDiagram)
Exemplo n.º 60
0
 def __unicode__(self):
     return slugify(self.nom_groupe)