예제 #1
0
    def grid_data(self, cls, **params):

        _logger = logging.getLogger('DashboardController.grid_data')

        # picking up parameters
        q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp = get_paramw(params,
                        'rp',
                        int,
                        opcional=True,
                        por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)
        pos = (pag_n - 1) * rp

        # collections
        ch_attr = params.get('ch_attr')
        parent_id = params.get('parent_id')

        # filters
        filters = get_paramw(params, 'filters', sj.loads, opcional=True)

        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)

        #logger.info('Parent class: %s' % cls_.name)
        #logger.info('Child class: %s' % ch_cls_.name)

        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']

        if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
        not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \
             '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions):
            return dict(
                status=False,
                message=_('Sorry, you do not have privilege on this class'))

        # get view name
        view = user.get_view_name(ch_cls_.name)

        #logger.info('search...%s / q=%s' % (view, q))

        # collection
        col = None
        if ch_attr and parent_id:
            col = (
                cls,
                ch_attr,
                parent_id,
            )

        # get dataset
        _search = Search(dbs, view, strtodatef=_strtodate)
        _search.apply_qry(q.encode('utf-8'))
        _search.apply_filters(filters)

        return _search(rp=rp, offset=pos, collection=col)
예제 #2
0
    def list(self, cls, **params):

        _logger = logging.getLogger('DashboardController.list')

        q     = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp    = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)

        came_from = params.get('came_from', '')
        if came_from:
            came_from = url(came_from)

        # collections
        ch_attr = params.get('ch_attr')
        parent_id = params.get('parent_id')

        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']

        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)

#        _logger.info('Parent class: %s' % cls_.name)
#        _logger.info('Child class: %s' % ch_cls_.name)

        if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
        not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \
             '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions):
            redirect(url('/message',
                         params=dict(message=_('Sorry, you do not have privilege on this class'),
                                     came_from=came_from)))

        # related classes
        rel_classes = cls_.related_classes()

        # collection
        caption = ch_cls_.title
        if ch_attr and parent_id:

            p_cls = cls_.attr_by_name(ch_attr).related_class
            p_title = SapnsClass.object_title(p_cls.name, parent_id)

            caption = _('%s of [%s]') % (ch_cls_.title, p_title)

        return dict(page=_('list of %s') % ch_cls_.title.lower(), came_from=came_from,
                    grid=dict(cls=ch_cls_.name,
                              caption=caption,
                              q=q.replace('"', '\\\"'), rp=rp, pag_n=pag_n,
                              # collection
                              ch_attr=ch_attr, parent_id=parent_id,
                              # related classes
                              rel_classes=rel_classes))
예제 #3
0
    def grid_data(self, cls, **params):

        _logger = logging.getLogger('DashboardController.grid_data')

        # picking up parameters
        q     = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp    = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)
        pos   = (pag_n-1) * rp

        # collections
        ch_attr = params.get('ch_attr')
        parent_id = params.get('parent_id')

        # filters
        filters = get_paramw(params, 'filters', sj.loads, opcional=True)

        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)

        #logger.info('Parent class: %s' % cls_.name)
        #logger.info('Child class: %s' % ch_cls_.name)

        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']

        if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
        not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \
             '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions):
            return dict(status=False,
                        message=_('Sorry, you do not have privilege on this class'))

        # get view name
        view = user.get_view_name(ch_cls_.name)

        #logger.info('search...%s / q=%s' % (view, q))

        # collection
        col = None
        if ch_attr and parent_id:
            col = (cls, ch_attr, parent_id,)

        # get dataset
        _search = Search(dbs, view, strtodatef=_strtodate)
        _search.apply_qry(q.encode('utf-8'))
        _search.apply_filters(filters)

        return _search(rp=rp, offset=pos, collection=col)
예제 #4
0
    def title(self, cls, id):
        logger = logging.getLogger('DashboardController.title')
        try:
            logger.info(id)
            try:
                _title = SapnsClass.object_title(cls, int(id))

            except Exception, e:
                logger.error(e)

                ids = sj.loads(id)
                _title = []
                ot = SapnsClass.ObjectTitle(cls)
                for id_ in ids:
                    _title.append(ot.title(id_))

            return dict(status=True, title=_title)
예제 #5
0
파일: docs.py 프로젝트: leondomingo/Sapns
 def _default(self, cls, id, **kw):
     
     # TODO: comprobar permisos
     
     class_ = SapnsClass.by_name(cls)
     id_object = int(id)
     
     title = SapnsClass.object_title(cls, id_object)
     
     return dict(page='', came_from=kw.get('came_from'),
                 lang=init_lang(), 
                 obj=dict(id_class=class_.class_id, 
                          id=id_object,
                          title=title),
                 grid=dict(caption=_('Documents of [%s]') % title,
                           cls=cls,
                           id_object=id_object,
                           ))
예제 #6
0
    def grid_actions(self, cls, **kw):

        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))

        # actions for this class
        cls_ = SapnsClass.by_name(cls)

        actions_ = {}
        for action in cls_.sorted_actions(user.user_id):
            if action['type'] in [
                    SapnsPermission.TYPE_NEW,
                    SapnsPermission.TYPE_EDIT,
                    SapnsPermission.TYPE_DELETE,
                    SapnsPermission.TYPE_DOCS,
                    SapnsPermission.TYPE_PROCESS,
            ]:

                actions_[action['name']] = action

        ch_cls_ = SapnsClass.by_name(cls, parent=False)
        for action_ch in ch_cls_.sorted_actions(user.user_id):
            if action_ch['type'] in [
                    SapnsPermission.TYPE_NEW,
                    SapnsPermission.TYPE_EDIT,
                    SapnsPermission.TYPE_DELETE,
                    SapnsPermission.TYPE_DOCS,
                    SapnsPermission.TYPE_PROCESS,
            ]:

                actions_.update({action_ch['name']: action_ch})

        def cmp_act(x, y):
            if x.pos == y.pos:
                return cmp(x.title, y.title)

            else:
                return cmp(x.pos, y.pos)

        return dict(status=True,
                    actions=sorted(actions_.values(), cmp=cmp_act))
예제 #7
0
    def ref_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(url('/message',
                         params=dict(message=_('Sorry, you do not have privilege on this class'),
                                     came_from=came_from)))

        class_ = SapnsClass.by_name(cls)

        return dict(page='reference order', reference=class_.reference(all=True),
                    came_from=came_from)
예제 #8
0
    def ins_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(url('/message',
                         params=dict(message=_('Sorry, you do not have privilege on this class'),
                                     came_from=came_from)))

        class_ = SapnsClass.by_name(cls)

        return dict(page='insertion order', insertion=class_.insertion(),
                    title=class_.title, came_from=url(came_from))
예제 #9
0
    def grid_actions(self, cls, **kw):

        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))

        # actions for this class
        cls_ = SapnsClass.by_name(cls)

        actions_ = {}
        for action in cls_.sorted_actions(user.user_id):
            if action['type'] in [SapnsPermission.TYPE_NEW,
                                  SapnsPermission.TYPE_EDIT,
                                  SapnsPermission.TYPE_DELETE,
                                  SapnsPermission.TYPE_DOCS,
                                  SapnsPermission.TYPE_PROCESS,
                                  ]:

                actions_[action['name']] = action

        ch_cls_ = SapnsClass.by_name(cls, parent=False)
        for action_ch in ch_cls_.sorted_actions(user.user_id):
            if action_ch['type'] in [SapnsPermission.TYPE_NEW,
                                     SapnsPermission.TYPE_EDIT,
                                     SapnsPermission.TYPE_DELETE,
                                     SapnsPermission.TYPE_DOCS,
                                     SapnsPermission.TYPE_PROCESS,
                                     ]:

                actions_.update({action_ch['name']: action_ch})

        def cmp_act(x, y):
            if x.pos == y.pos:
                return cmp(x.title, y.title)

            else:
                return cmp(x.pos, y.pos)

        return dict(status=True, actions=sorted(actions_.values(), cmp=cmp_act))
예제 #10
0
 def __call__(self):
     
     logger = logging.getLogger('TM_Test')
     
     managers = SapnsRole.by_name(u'managers')
     for usuario in managers.users_:
         
         logger.info(usuario.display_name)
         db = usuario.get_dashboard()
         for sc in db.children:
             logger.info(sc.title)
             sc.title = '_%s' % sc.title
             dbs.add(sc)
             dbs.flush()
             
     def attributes(cls):
         for attr in cls.attributes:
             logger.info(attr.name)
             attr.title = '*%s' % attr.title
             dbs.add(attr)
             dbs.flush()
             
     attributes(SapnsClass.by_name(u'alumnos'))
     attributes(SapnsClass.by_name(u'clientes'))
예제 #11
0
 def __call__(self):
     
     csfp = SapnsPermission()
     csfp.class_id = SapnsClass.by_name(u'sp_permission').class_id
     csfp.permission_name = u'sp_permission#create_shortcuts'
     csfp.display_name = u'Create shortcuts'
     csfp.type = SapnsPermission.TYPE_PROCESS
     csfp.url = u'/dashboard/permissions/create_shortcuts/'
     csfp.requires_id = True
     
     dbs.add(csfp)
     dbs.flush()
     
     managers = SapnsRole.by_name(u'managers')
     managers.permissions_.append(csfp)
     dbs.flush()
예제 #12
0
파일: docs.py 프로젝트: leondomingo/Sapns
 def search(self, cls, id, **kw):
     
     class_ = SapnsClass.by_name(cls)
     id_object = int(id)
     
     # picking up parameters
     q     = get_paramw(kw, 'q', unicode, opcional=True, por_defecto='')
     rp    = get_paramw(kw, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10)))
     pag_n = get_paramw(kw, 'pag_n', int, opcional=True, por_defecto=1)
     pos   = (pag_n-1) * rp
     
     filters = [('id_class', class_.class_id), ('id_object', id_object)]
     view_name = '%ssp_docs' % config.get('views_prefix', '_view_') 
     ds = search(dbs, view_name, q=q.encode('utf-8'), rp=rp, offset=pos,
                 filters=filters)
     
     cols = []
     for col in ds.labels:
         w = 125
         if col == 'id':
             w = 60
             
         cols.append(dict(title=col, width=w, align='center'))
         
     # total number of pages
     total_pag = 1
     if rp > 0:
         total_pag = ds.count / rp
         
         if ds.count % rp != 0:
             total_pag += 1
         
         if total_pag == 0:
             total_pag = 1
     
     # rows in this page
     totalp = ds.count - pos
     if rp and totalp > rp:
         totalp = rp
         
     # rows in this page
     this_page = ds.count - pos
     if rp and this_page > rp:
         this_page = rp
         
     return dict(status=True, cols=cols, data=ds.to_data(), 
                 this_page=this_page, total_count=ds.count, total_pag=total_pag)
예제 #13
0
    def ref_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(
                url('/message',
                    params=dict(message=_(
                        'Sorry, you do not have privilege on this class'),
                                came_from=came_from)))

        class_ = SapnsClass.by_name(cls)

        return dict(page='reference order',
                    reference=class_.reference(all=True),
                    came_from=came_from)
예제 #14
0
    def title(self, cls, id):
        logger = logging.getLogger('DashboardController.title')
        try:
            logger.info(id)
            try:
                _title = SapnsClass.object_title(cls, int(id))

            except Exception, e:
                logger.error(e)

                ids = sj.loads(id)
                _title = []
                ot = SapnsClass.ObjectTitle(cls)
                for id_ in ids:
                    _title.append(ot.title(id_))

            return dict(status=True, title=_title)
예제 #15
0
    def ins_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(
                url('/message',
                    params=dict(message=_(
                        'Sorry, you do not have privilege on this class'),
                                came_from=came_from)))

        class_ = SapnsClass.by_name(cls)

        return dict(page='insertion order',
                    insertion=class_.insertion(),
                    title=class_.title,
                    came_from=url(came_from))
예제 #16
0
파일: logs.py 프로젝트: leondomingo/Sapns
    def grid(self, cls, **params):
        
        #logger = logging.getLogger('DashboardController.grid')

        # picking up parameters
        q     = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp    = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)
        pos   = (pag_n-1) * rp
        
        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']
        
        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)        
            
        if not user.has_privilege(cls_.name) or \
        not '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions:
            return dict(status=False, 
                        message=_('Sorry, you do not have privilege on this class'))
        
        # get view name
        view = user.get_view_name(ch_cls_.name)
            
        # get dataset
        s = Search(dbs, view, strtodatef=_strtodate)
        # TODO: joins
        meta = MetaData(bind=dbs.bind)
        t_logs = Table('sp_logs', meta, autoload=True)
        
        table_name = get_paramw(params, 'table_name', unicode)
        row_id = get_paramw(params, 'row_id', int)
        
        s.join(t_logs, and_(t_logs.c.id == s.tbl.c.id,
                            t_logs.c.table_name == table_name,
                            t_logs.c.row_id == row_id,
                            ))
        
        # q
        s.apply_qry(q.encode('utf-8'))
        
        # ordenar
        #s.order_by(desc(s.tbl.c.id))
        
        ds = s(rp=rp, offset=pos)
                 
        # Reading global settings
        ds.date_fmt = date_fmt
        ds.time_fmt = config.get('formats.time', default='%H:%M')
        ds.datetime_fmt = config.get('formats.datetime', default='%m/%d/%Y %H:%M')
        ds.true_const = _('Yes')
        ds.false_const = _('No')
        
        ds.float_fmt = app_cfg.format_float
        
        cols = []
        for col in ds.labels:
            w = 125
            if col == 'id':
                w = 60
                
            cols.append(dict(title=col, width=w, align='center'))
            
        this_page, total_pag = pagination(rp, pag_n, ds.count)
        
        return dict(status=True, cols=cols, data=ds.to_data(), 
                    this_page=this_page, total_count=ds.count, total_pag=total_pag)        
예제 #17
0
파일: initsp.py 프로젝트: leondomingo/Sapns
 def update_metadata(self):
     
     logger = logging.getLogger('lib.sapns.update_metadata')
     
     env = Environment(loader=FileSystemLoader(current_path))
     
     managers = dbs.query(SapnsRole).\
         filter(SapnsRole.group_name == u'managers').\
         first()
             
     tables = self.extract_model(all_=True)
     tables_id = {}
     for tbl in tables:
         
         logger.info('Table: %s' % tbl['name'])
         
         klass = dbs.query(SapnsClass).\
             filter(SapnsClass.name == tbl['name']).\
             first()
         
         if not klass:
             logger.warning('.....creating')
             
             klass = SapnsClass()
             klass.name = tbl['name']
             klass.title = tbl['name'].title()
             klass.description =  u'Clases: %s' % tbl['name']
             
             dbs.add(klass)
             dbs.flush()
             
             # grant access (r/w) to "managers"
             priv = SapnsPrivilege()
             priv.role_id = managers.group_id
             priv.class_id = klass.class_id
             priv.granted = True
             
             dbs.add(priv)
             dbs.flush()
             
         else:
             logger.warning('.....already exists')
             
         tables_id[tbl['name']] = klass #.class_id
         
     tmpl = env.get_template('trigger_function_log.txt')
     
     pending_attr = {}
     for tbl in tables:
         
         #tables_id[tbl['name']] = klass.class_id
         klass = tables_id[tbl['name']]
             
         # create an action
         def create_action(name, type_):
             action = dbs.query(SapnsPermission).\
                 filter(and_(SapnsPermission.class_id == klass.class_id,
                             SapnsPermission.type == type_)).\
                 first()
                             
             if not action:
                 action = SapnsPermission()
                 action.permission_name = u'%s#%s' % (klass.name, name.lower())
                 action.display_name = name
                 action.type = type_
                 action.class_id = klass.class_id
                 
                 dbs.add(action)
                 dbs.flush()
                 
                 # add this action to "managers" role
                 managers.permissions_.append(action)
                 dbs.flush()
                 
             elif action.type == SapnsPermission.TYPE_LIST:
                 for s in action.shortcuts:
                     s.title = action.class_.title
                     dbs.add(s)
                     dbs.flush()
                 
         # create standard actions
         create_action(u'New', SapnsPermission.TYPE_NEW)
         create_action(u'Edit', SapnsPermission.TYPE_EDIT)
         create_action(u'Delete', SapnsPermission.TYPE_DELETE)
         create_action(u'List', SapnsPermission.TYPE_LIST)
         create_action(u'Docs', SapnsPermission.TYPE_DOCS)
             
         log_attributes = Dict(created=False, updated=False)
         log_cols = []
         first_ref = False
         for i, col in enumerate(tbl['columns']):
             
             logger.info('Column: %s' % col['name'])
             
             attr = dbs.query(SapnsAttribute).\
                 filter(and_(SapnsAttribute.name == col['name'],
                             SapnsAttribute.class_id == klass.class_id, 
                             )).\
                 first()
                 
             # log attributes
             if col['name'] in ['_created', '_updated']:
                 
                 if col['name'] == '_created':
                     log_attributes.created = True
                     
                 if col['name'] == '_updated':
                     log_attributes.updated = True
                 
                 continue
             
             elif col['name'] != 'id':
                 log_cols.append(col['name'])
                     
             if col['name'] not in ['id', '_created', '_updated']:
                 if not attr: 
                     logger.warning('.....creating')
                     
                     attr = SapnsAttribute()
                     attr.name = col['name']
                     attr.title = col['name'].replace('_', ' ').title()
                     attr.class_id = klass.class_id
                     attr.type = col['type_name']
                     if attr.type == SapnsAttribute.TYPE_STRING and not first_ref:
                         attr.reference_order = 0
                         first_ref = True
                         
                     attr.visible = True
                     attr.insertion_order = i
                     
                     if attr.type == SapnsAttribute.TYPE_INTEGER and \
                     not attr.name.startswith('id_'):
                         # signed
                         attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'
                         
                     elif attr.type == SapnsAttribute.TYPE_FLOAT:
                         # signed
                         # col['prec']
                         # col['scale']
                         attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                             (col['prec']-col['scale'],
                              col['scale'])
                             
                     elif attr.type == SapnsAttribute.TYPE_TIME:
                         attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'
                     
                     dbs.add(attr)
                     dbs.flush()
                     
                     # grant access (r/w) to managers
                     priv = SapnsAttrPrivilege()
                     priv.role_id = managers.group_id
                     priv.attribute_id = attr.attribute_id
                     priv.access = SapnsAttrPrivilege.ACCESS_READWRITE
                     
                     dbs.add(priv)
                     dbs.flush()
                     
                 else:
                     logger.warning('.....already exists')
                     
                     # fill the "field_regex"
                     if attr and not attr.field_regex:
                         if attr.type == SapnsAttribute.TYPE_INTEGER and \
                         not attr.name.startswith('id_'):
                             # signed
                             attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'
                             
                         elif attr.type == SapnsAttribute.TYPE_FLOAT:
                             # signed
                             attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                                 (col['prec'] - col['scale'], col['scale'])
                                 
                         elif attr.type == SapnsAttribute.TYPE_TIME:
                             attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'
                 
             # foreign key
             if col['fk_table'] != None:
                 pending_attr[attr.attribute_id] = col['fk_table'].name
                 
         if tbl['name'] not in [u'sp_logs', 
                                u'sp_role_permission', 
                                u'sp_user_role']:
             
             _log_attributes = []
             
             # _created
             if not log_attributes.created:
                 _log_attributes.append('ADD _created TIMESTAMP')
             
             # _updated
             if not log_attributes.updated:
                 _log_attributes.append('ADD _updated TIMESTAMP')
                 
             if _log_attributes:
                 _alter = 'ALTER TABLE %s %s;' % (tbl['name'], ', '.join(_log_attributes))
                 logger.info(_alter)
                 
                 try:
                     dbs.execute(_alter)
                     dbs.flush()
                     
                 except Exception, e:
                     #dbs.rollback()
                     logger.error(e)
                     
             # log trigger function
             try:
                 logf = tmpl.render(tbl_name=tbl['name'], cols=log_cols,
                                    class_id=klass.class_id,
                                    )
                 #logger.info(logf)
                 dbs.execute(logf)
                 dbs.flush()
                 
             except Exception, e:
                 #dbs.rollback()
                 logger.error(e)
                         
             # log triggers
             log_trigger = 'SELECT COUNT(*) FROM pg_trigger WHERE tgname = \'zzzflog_%s\'' % tbl['name']
             lt = dbs.execute(log_trigger).fetchone()
             if lt[0] == 0:
                 _trigger = '''create trigger zzzflog_%s
                               after insert or update or delete
                               on %s
                               for each row
                               execute procedure flog_%s();''' % ((tbl['name'],)*3)
                               
                 #logger.info(_trigger)
                 try:
                     dbs.execute(_trigger)
                     dbs.flush()
                     
                 except Exception, e:
                     #dbs.rollback()
                     logger.error(e)
예제 #18
0
    def list(self, cls, **params):

        _logger = logging.getLogger('DashboardController.list')

        q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp = get_paramw(params,
                        'rp',
                        int,
                        opcional=True,
                        por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)

        came_from = params.get('came_from', '')
        if came_from:
            came_from = url(came_from)

        # collections
        ch_attr = params.get('ch_attr')
        parent_id = params.get('parent_id')

        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']

        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)

        #        _logger.info('Parent class: %s' % cls_.name)
        #        _logger.info('Child class: %s' % ch_cls_.name)

        if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
        not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \
             '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions):
            redirect(
                url('/message',
                    params=dict(message=_(
                        'Sorry, you do not have privilege on this class'),
                                came_from=came_from)))

        # related classes
        rel_classes = cls_.related_classes()

        # collection
        caption = ch_cls_.title
        if ch_attr and parent_id:

            p_cls = cls_.attr_by_name(ch_attr).related_class
            p_title = SapnsClass.object_title(p_cls.name, parent_id)

            caption = _('%s of [%s]') % (ch_cls_.title, p_title)

        return dict(
            page=_('list of %s') % ch_cls_.title.lower(),
            came_from=came_from,
            grid=dict(
                cls=ch_cls_.name,
                caption=caption,
                q=q.replace('"', '\\\"'),
                rp=rp,
                pag_n=pag_n,
                # collection
                ch_attr=ch_attr,
                parent_id=parent_id,
                # related classes
                rel_classes=rel_classes))
예제 #19
0
    def update_metadata(self):

        logger = logging.getLogger('lib.sapns.update_metadata')

        env = Environment(loader=FileSystemLoader(current_path))

        managers = dbs.query(SapnsRole).\
            filter(SapnsRole.group_name == u'managers').\
            first()

        tables = self.extract_model(all_=True)
        tables_id = {}
        for tbl in tables:

            logger.info('Table: %s' % tbl['name'])

            klass = dbs.query(SapnsClass).\
                filter(SapnsClass.name == tbl['name']).\
                first()

            if not klass:
                logger.warning('.....creating')

                klass = SapnsClass()
                klass.name = tbl['name']
                klass.title = tbl['name'].title()
                klass.description = u'Clases: %s' % tbl['name']

                dbs.add(klass)
                dbs.flush()

                # grant access (r/w) to "managers"
                priv = SapnsPrivilege()
                priv.role_id = managers.group_id
                priv.class_id = klass.class_id
                priv.granted = True

                dbs.add(priv)
                dbs.flush()

            else:
                logger.warning('.....already exists')

            tables_id[tbl['name']] = klass  #.class_id

        tmpl = env.get_template('trigger_function_log.txt')

        pending_attr = {}
        for tbl in tables:

            #tables_id[tbl['name']] = klass.class_id
            klass = tables_id[tbl['name']]

            # create an action
            def create_action(name, type_):
                action = dbs.query(SapnsPermission).\
                    filter(and_(SapnsPermission.class_id == klass.class_id,
                                SapnsPermission.type == type_)).\
                    first()

                if not action:
                    action = SapnsPermission()
                    action.permission_name = u'%s#%s' % (klass.name,
                                                         name.lower())
                    action.display_name = name
                    action.type = type_
                    action.class_id = klass.class_id

                    dbs.add(action)
                    dbs.flush()

                    # add this action to "managers" role
                    managers.permissions_.append(action)
                    dbs.flush()

                elif action.type == SapnsPermission.TYPE_LIST:
                    for s in action.shortcuts:
                        s.title = action.class_.title
                        dbs.add(s)
                        dbs.flush()

            # create standard actions
            create_action(u'New', SapnsPermission.TYPE_NEW)
            create_action(u'Edit', SapnsPermission.TYPE_EDIT)
            create_action(u'Delete', SapnsPermission.TYPE_DELETE)
            create_action(u'List', SapnsPermission.TYPE_LIST)
            create_action(u'Docs', SapnsPermission.TYPE_DOCS)

            log_attributes = Dict(created=False, updated=False)
            log_cols = []
            first_ref = False
            for i, col in enumerate(tbl['columns']):

                logger.info('Column: %s' % col['name'])

                attr = dbs.query(SapnsAttribute).\
                    filter(and_(SapnsAttribute.name == col['name'],
                                SapnsAttribute.class_id == klass.class_id,
                                )).\
                    first()

                # log attributes
                if col['name'] in ['_created', '_updated']:

                    if col['name'] == '_created':
                        log_attributes.created = True

                    if col['name'] == '_updated':
                        log_attributes.updated = True

                    continue

                elif col['name'] != 'id':
                    log_cols.append(col['name'])

                if col['name'] not in ['id', '_created', '_updated']:
                    if not attr:
                        logger.warning('.....creating')

                        attr = SapnsAttribute()
                        attr.name = col['name']
                        attr.title = col['name'].replace('_', ' ').title()
                        attr.class_id = klass.class_id
                        attr.type = col['type_name']
                        if attr.type == SapnsAttribute.TYPE_STRING and not first_ref:
                            attr.reference_order = 0
                            first_ref = True

                        attr.visible = True
                        attr.insertion_order = i

                        if attr.type == SapnsAttribute.TYPE_INTEGER and \
                        not attr.name.startswith('id_'):
                            # signed
                            attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'

                        elif attr.type == SapnsAttribute.TYPE_FLOAT:
                            # signed
                            # col['prec']
                            # col['scale']
                            attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                                (col['prec']-col['scale'],
                                 col['scale'])

                        elif attr.type == SapnsAttribute.TYPE_TIME:
                            attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'

                        dbs.add(attr)
                        dbs.flush()

                        # grant access (r/w) to managers
                        priv = SapnsAttrPrivilege()
                        priv.role_id = managers.group_id
                        priv.attribute_id = attr.attribute_id
                        priv.access = SapnsAttrPrivilege.ACCESS_READWRITE

                        dbs.add(priv)
                        dbs.flush()

                    else:
                        logger.warning('.....already exists')

                        # fill the "field_regex"
                        if attr and not attr.field_regex:
                            if attr.type == SapnsAttribute.TYPE_INTEGER and \
                            not attr.name.startswith('id_'):
                                # signed
                                attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'

                            elif attr.type == SapnsAttribute.TYPE_FLOAT:
                                # signed
                                attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                                    (col['prec'] - col['scale'], col['scale'])

                            elif attr.type == SapnsAttribute.TYPE_TIME:
                                attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'

                # foreign key
                if col['fk_table'] != None:
                    pending_attr[attr.attribute_id] = col['fk_table'].name

            if tbl['name'] not in [
                    u'sp_logs', u'sp_role_permission', u'sp_user_role'
            ]:

                _log_attributes = []

                # _created
                if not log_attributes.created:
                    _log_attributes.append('ADD _created TIMESTAMP')

                # _updated
                if not log_attributes.updated:
                    _log_attributes.append('ADD _updated TIMESTAMP')

                if _log_attributes:
                    _alter = 'ALTER TABLE %s %s;' % (
                        tbl['name'], ', '.join(_log_attributes))
                    logger.info(_alter)

                    try:
                        dbs.execute(_alter)
                        dbs.flush()

                    except Exception, e:
                        #dbs.rollback()
                        logger.error(e)

                # log trigger function
                try:
                    logf = tmpl.render(
                        tbl_name=tbl['name'],
                        cols=log_cols,
                        class_id=klass.class_id,
                    )
                    #logger.info(logf)
                    dbs.execute(logf)
                    dbs.flush()

                except Exception, e:
                    #dbs.rollback()
                    logger.error(e)

                # log triggers
                log_trigger = 'SELECT COUNT(*) FROM pg_trigger WHERE tgname = \'zzzflog_%s\'' % tbl[
                    'name']
                lt = dbs.execute(log_trigger).fetchone()
                if lt[0] == 0:
                    _trigger = '''create trigger zzzflog_%s
                                  after insert or update or delete
                                  on %s
                                  for each row
                                  execute procedure flog_%s();''' % (
                        (tbl['name'], ) * 3)

                    #logger.info(_trigger)
                    try:
                        dbs.execute(_trigger)
                        dbs.flush()

                    except Exception, e:
                        #dbs.rollback()
                        logger.error(e)
예제 #20
0
    def edit(self, cls, id='', **params):

        _logger = logging.getLogger('DashboardController.edit')

        came_from = get_paramw(params,
                               'came_from',
                               unicode,
                               opcional=True,
                               por_defecto='/')

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
        permissions = request.identity['permissions']

        class_ = SapnsClass.by_name(cls)
        ch_class_ = SapnsClass.by_name(cls, parent=False)

        # log
        _what = _('edit record')
        if not id:
            _what = _('new record')
            _id = None
        else:
            _id = int(id)

        SapnsLog.register(
            table_name=ch_class_.name,
            row_id=_id,
            who=user.user_id,
            what=_what,
        )

        if id:
            id = int(id)
            perm = '%s#%s' % (ch_class_.name, SapnsPermission.TYPE_EDIT) in permissions or \
                   '%s#%s' % (class_.name, SapnsPermission.TYPE_EDIT) in permissions

        else:
            perm = '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions or \
                   '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions

        if not (user.has_privilege(ch_class_.name)
                or user.has_privilege(class_.name)) or not perm:
            redirect(
                url('/message',
                    params=dict(message=_(
                        'Sorry, you do not have privilege on this class'),
                                came_from=came_from)))

        # actions
        actions = [
            action for action in class_.sorted_actions(user.user_id)
            if action['type'] == 'process'
        ]

        meta = MetaData(dbs.bind)
        try:
            tbl = Table(class_.name, meta, autoload=True)

        except NoSuchTableError:
            redirect(
                url('/message',
                    params=dict(message=_('This class does not exist'),
                                came_from=came_from)))

        default_values_ro = {}
        default_values = {}
        for field_name, value in params.iteritems():

            # default read-only values (_xxxx)
            m = re.search(r'^_([a-z]\w+)$', field_name, re.I | re.U)
            if m:
                #logger.info('Default value (read-only): %s = %s' % (m.group(1), params[field_name]))
                default_values_ro[m.group(1)] = params[field_name]

            else:
                # default read/write values (__xxxx)
                # depends on privilege of this attribute
                m = re.search(r'^__([a-z]\w+)$', field_name, re.I | re.U)
                if m:
                    #logger.info('Default value (read/write*): %s = %s' % (m.group(1), params[field_name]))
                    default_values[m.group(1)] = params[field_name]

        _created = None
        _updated = None

        ref = None
        row = None
        if id:
            row = dbs.execute(tbl.select(tbl.c.id == id)).fetchone()
            if not row:
                # row does not exist
                redirect(
                    url('/message',
                        params=dict(message=_('Record does not exist'),
                                    came_from=came_from)))

            # reference
            ref = SapnsClass.object_title(class_.name, id)

            if class_.name != u'sp_logs':
                _created = row['_created'].strftime(
                    datetime_fmt) if row['_created'] else None
                _updated = row['_updated'].strftime(
                    datetime_fmt) if row['_updated'] else None

        #logger.info(row)

        # get attributes
        attributes = []
        for attr, attr_priv in SapnsClass.by_name(cls).get_attributes(
                user.user_id):

            #logger.info('%s [%s]' % (attr.name, attr_priv.access))

            value = ''
            read_only = attr_priv.access == SapnsAttrPrivilege.ACCESS_READONLY
            if attr.name in default_values_ro:
                value = default_values_ro[attr.name]
                read_only = True

            elif attr.name in default_values:
                value = default_values[attr.name]

            elif row:
                #logger.info(row[attr.name])
                #logger.info(attr)
                if row[attr.name] != None:
                    # date
                    if attr.type == SapnsAttribute.TYPE_DATE:
                        value = datetostr(row[attr.name], fmt=date_fmt)

                    # datetime
                    elif attr.type == SapnsAttribute.TYPE_DATETIME:
                        value = row[attr.name].strftime(datetime_fmt) if row[
                            attr.name] else ''

                    # numeric (int, float)
                    elif attr.type in [
                            SapnsAttribute.TYPE_INTEGER,
                            SapnsAttribute.TYPE_FLOAT
                    ]:
                        value = row[attr.name]

                    # rest of types
                    else:
                        value = row[attr.name] or ''

            attribute = dict(
                name=attr.name,
                title=attr.title,
                type=attr.type,
                value=value,
                required=attr.required,
                related_class=None,
                related_class_title='',
                read_only=read_only,
                vals=None,
                field_regex=attr.field_regex,
            )

            #logger.info('%s = %s' % (attr.name, repr(value)))

            attributes.append(attribute)

            if attr.related_class_id:
                # vals
                try:
                    rel_class = dbs.query(SapnsClass).get(
                        attr.related_class_id)

                    # related_class
                    attribute['related_class'] = rel_class.name
                    attribute['related_class_title'] = rel_class.title
                    attribute['related_title'] = SapnsClass.object_title(
                        rel_class.name, value)

                except Exception, e:
                    _logger.error(e)
                    attribute['vals'] = None
예제 #21
0
    def save(self, cls, **params):
        """
        IN
          cls          <unicode>
          params
            id         <int>
            came_from  <unicode>
            fld_*      ???        Fields to be saved
        """

        logger = logging.getLogger(__name__ + '/save')
        try:
            #logger.info(params)

            ch_cls = SapnsClass.by_name(cls, parent=False)
            cls = SapnsClass.by_name(cls)
            id_ = get_paramw(params, 'id', int, opcional=True)

            # does this user have permission on this table?
            user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
            permissions = request.identity['permissions']

            if not user.has_privilege(cls.name) or \
            not '%s#%s' % (cls.name, SapnsPermission.TYPE_EDIT) in permissions:
                return dict(status=False)

            # init "update" dictionary
            update = {}

            if id_:
                update['id'] = int(id_)

            READONLY_DENIED = [
                SapnsAttrPrivilege.ACCESS_READONLY,
                SapnsAttrPrivilege.ACCESS_DENIED
            ]

            def _strtodatetime(s, fmt):

                # build regex
                regex = r'^\s*%s\s*$' % (fmt.replace('%d', r'(?P<day>([0-2]?[1-9]|3[0-1]))').\
                                         replace('%m', r'(?P<month>(0?[1-9]|1[0-2]))').\
                                         replace('%Y', r'(?P<year>\d{4})').\
                                         replace('%H', r'(?P<hour>([0-1]?[0-9]|2[0-3]))').\
                                         replace('%M', r'(?P<minute>[0-5][0-9])').\
                                         replace('%S', r'(?P<second>[0-5][0-9])').\
                                         replace(' ', r'\s'))

                m1 = re.search(regex, s)
                if m1:
                    try:
                        day = int(m1.groupdict().get('day') or 1)
                        month = int(m1.groupdict().get('month') or 1)
                        year = int(m1.groupdict().get('year') or 1900)
                        hour = int(m1.groupdict().get('hour') or 0)
                        min_ = int(m1.groupdict().get('minute') or 0)
                        sec = int(m1.groupdict().get('second') or 0)

                        return dt.datetime(year, month, day, hour, min_, sec)

                    except Exception, e:
                        logger.error(e)
                        raise
                else:
예제 #22
0
    def delete(self, cls, id_, **kw):

        #came_from = get_paramw(kw, 'came_from', opcional=True, por_defecto='/')

        logger = logging.getLogger('DashboardController.delete')
        rel_tables = []
        try:
            user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
            permissions = request.identity['permissions']
            cls_ = SapnsClass.by_name(cls)
            ch_cls_ = SapnsClass.by_name(cls, parent=False)

            # check privilege on this class
            if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
            not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_DELETE) in permissions or \
                 '%s#%s' % (cls_.name, SapnsPermission.TYPE_DELETE) in permissions):
                return dict(status=False,
                            message=_('Sorry, you do not have privilege on this class'))

            # does the record exist?
            meta = MetaData(dbs.bind)
            tbl = Table(cls_.name, meta, autoload=True)

            try:
                id_ = int(id_)

            except:
                id_ = sj.loads(id_)

            if isinstance(id_, int):
                # int
                this_record = dbs.execute(tbl.select(tbl.c.id == id_)).fetchone()
                if not this_record:
                    return dict(status=False, message=_('Record does not exist'))

            else:
                # array of ints
                these_records = dbs.execute(tbl.select(tbl.c.id.in_(id_))).fetchall()
                if len(these_records) != len(id_):
                    return dict(status=False, message=_('Some records do not exist'))

            # look for objects in other classes that are related with this

            rel_classes = cls_.related_classes()
            for rcls in rel_classes:

                logger.info('Related class: "%s.%s"' % (rcls['name'], rcls['attr_name']))
                rtbl = Table(rcls['name'], meta, autoload=True)
                attr_name = rcls['attr_name']

                if isinstance(id_, int):
                    # int
                    i = id_

                else:
                    # array of ints
                    i = id_[0]

                sel = rtbl.select(whereclause=rtbl.c[attr_name] == int(i))
                robj = dbs.execute(sel).fetchone()

                if robj != None:
                    rel_tables.append(dict(class_title=rcls['title'],
                                           attr_title=rcls['attr_title']))

                else:
                    logger.info('---No related objects have been found')

            # delete record
            if isinstance(id_, int):
                # int
                tbl.delete(tbl.c.id == id_).execute()

                # log
                SapnsLog.register(table_name=cls_.name,
                                  row_id=id_,
                                  who=user.user_id,
                                  what=_('delete'),
                                  )

            else:
                # array of int's
                tbl.delete(tbl.c.id.in_(id_)).execute()

                for i in id_:
                    # log
                    SapnsLog.register(table_name=cls_.name,
                                      row_id=i,
                                      who=user.user_id,
                                      what=_('delete'),
                                      )

            dbs.flush()

            # success!
            return dict(status=True)

        except Exception, e:
            logger.error(e)
            return dict(status=False, message=str(e), rel_tables=rel_tables)
예제 #23
0
    def edit(self, cls, id='', **params):

        _logger = logging.getLogger('DashboardController.edit')

        came_from = get_paramw(params, 'came_from', unicode, opcional=True,
                               por_defecto='/')

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
        permissions = request.identity['permissions']

        class_ = SapnsClass.by_name(cls)
        ch_class_ = SapnsClass.by_name(cls, parent=False)

        # log
        _what = _('edit record')
        if not id:
            _what = _('new record')
            _id = None
        else:
            _id = int(id)

        SapnsLog.register(table_name=ch_class_.name,
                          row_id=_id,
                          who=user.user_id,
                          what=_what,
                          )

        if id:
            id = int(id)
            perm = '%s#%s' % (ch_class_.name, SapnsPermission.TYPE_EDIT) in permissions or \
                   '%s#%s' % (class_.name, SapnsPermission.TYPE_EDIT) in permissions

        else:
            perm = '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions or \
                   '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions

        if not (user.has_privilege(ch_class_.name) or user.has_privilege(class_.name)) or not perm:
            redirect(url('/message',
                         params=dict(message=_('Sorry, you do not have privilege on this class'),
                                     came_from=came_from)))

        # actions
        actions = [action for action in class_.sorted_actions(user.user_id)
                   if action['type']  == 'process']

        meta = MetaData(dbs.bind)
        try:
            tbl = Table(class_.name, meta, autoload=True)

        except NoSuchTableError:
            redirect(url('/message',
                         params=dict(message=_('This class does not exist'),
                                     came_from=came_from)))

        default_values_ro = {}
        default_values = {}
        for field_name, value in params.iteritems():

            # default read-only values (_xxxx)
            m = re.search(r'^_([a-z]\w+)$', field_name, re.I | re.U)
            if m:
                #logger.info('Default value (read-only): %s = %s' % (m.group(1), params[field_name]))
                default_values_ro[m.group(1)] = params[field_name]

            else:
                # default read/write values (__xxxx)
                # depends on privilege of this attribute
                m = re.search(r'^__([a-z]\w+)$', field_name, re.I | re.U)
                if m:
                    #logger.info('Default value (read/write*): %s = %s' % (m.group(1), params[field_name]))
                    default_values[m.group(1)] = params[field_name]

        _created = None
        _updated = None

        ref = None
        row = None
        if id:
            row = dbs.execute(tbl.select(tbl.c.id == id)).fetchone()
            if not row:
                # row does not exist
                redirect(url('/message',
                             params=dict(message=_('Record does not exist'),
                                         came_from=came_from)))

            # reference
            ref = SapnsClass.object_title(class_.name, id)

            if class_.name != u'sp_logs':
                _created = row['_created'].strftime(datetime_fmt) if row['_created'] else None
                _updated = row['_updated'].strftime(datetime_fmt) if row['_updated'] else None

        #logger.info(row)

        # get attributes
        attributes = []
        for attr, attr_priv in SapnsClass.by_name(cls).get_attributes(user.user_id):

            #logger.info('%s [%s]' % (attr.name, attr_priv.access))

            value = ''
            read_only = attr_priv.access == SapnsAttrPrivilege.ACCESS_READONLY
            if attr.name in default_values_ro:
                value = default_values_ro[attr.name]
                read_only = True

            elif attr.name in default_values:
                value = default_values[attr.name]

            elif row:
                #logger.info(row[attr.name])
                #logger.info(attr)
                if row[attr.name] != None:
                    # date
                    if attr.type == SapnsAttribute.TYPE_DATE:
                        value = datetostr(row[attr.name], fmt=date_fmt)

                    # datetime
                    elif attr.type == SapnsAttribute.TYPE_DATETIME:
                        value = row[attr.name].strftime(datetime_fmt) if row[attr.name] else ''

                    # numeric (int, float)
                    elif attr.type in [SapnsAttribute.TYPE_INTEGER, SapnsAttribute.TYPE_FLOAT]:
                        value = row[attr.name]

                    # rest of types
                    else:
                        value = row[attr.name] or ''

            attribute = dict(name=attr.name, title=attr.title,
                             type=attr.type, value=value, required=attr.required,
                             related_class=None, related_class_title='',
                             read_only=read_only, vals=None, field_regex=attr.field_regex,)

            #logger.info('%s = %s' % (attr.name, repr(value)))

            attributes.append(attribute)

            if attr.related_class_id:
                # vals
                try:
                    rel_class = dbs.query(SapnsClass).get(attr.related_class_id)

                    # related_class
                    attribute['related_class'] = rel_class.name
                    attribute['related_class_title'] = rel_class.title
                    attribute['related_title'] = SapnsClass.object_title(rel_class.name, value)

                except Exception, e:
                    _logger.error(e)
                    attribute['vals'] = None
예제 #24
0
    def grid(self, cls, **params):

        #logger = logging.getLogger('DashboardController.grid')

        # picking up parameters
        q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='')
        rp = get_paramw(params,
                        'rp',
                        int,
                        opcional=True,
                        por_defecto=int(config.get('grid.default_rp', 10)))
        pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1)
        pos = (pag_n - 1) * rp

        # does this user have permission on this table?
        user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id))
        permissions = request.identity['permissions']

        cls_ = SapnsClass.by_name(cls)
        ch_cls_ = SapnsClass.by_name(cls, parent=False)

        if not user.has_privilege(cls_.name) or \
        not '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions:
            return dict(
                status=False,
                message=_('Sorry, you do not have privilege on this class'))

        # get view name
        view = user.get_view_name(ch_cls_.name)

        # get dataset
        s = Search(dbs, view, strtodatef=_strtodate)
        # TODO: joins
        meta = MetaData(bind=dbs.bind)
        t_logs = Table('sp_logs', meta, autoload=True)

        table_name = get_paramw(params, 'table_name', unicode)
        row_id = get_paramw(params, 'row_id', int)

        s.join(
            t_logs,
            and_(
                t_logs.c.id == s.tbl.c.id,
                t_logs.c.table_name == table_name,
                t_logs.c.row_id == row_id,
            ))

        # q
        s.apply_qry(q.encode('utf-8'))

        # ordenar
        #s.order_by(desc(s.tbl.c.id))

        ds = s(rp=rp, offset=pos)

        # Reading global settings
        ds.date_fmt = date_fmt
        ds.time_fmt = config.get('formats.time', default='%H:%M')
        ds.datetime_fmt = config.get('formats.datetime',
                                     default='%m/%d/%Y %H:%M')
        ds.true_const = _('Yes')
        ds.false_const = _('No')

        ds.float_fmt = app_cfg.format_float

        cols = []
        for col in ds.labels:
            w = 125
            if col == 'id':
                w = 60

            cols.append(dict(title=col, width=w, align='center'))

        this_page, total_pag = pagination(rp, pag_n, ds.count)

        return dict(status=True,
                    cols=cols,
                    data=ds.to_data(),
                    this_page=this_page,
                    total_count=ds.count,
                    total_pag=total_pag)
예제 #25
0
파일: util.py 프로젝트: leondomingo/Sapns
def update_metadata():
    
    logger = logging.getLogger('lib.sapns.update_metadata')
    
    managers = SapnsRole.by_name(ROLE_MANAGERS)
    #managers = SapnsRole()
    
    tables = extract_model(all=True)
    tables_id = {}
    pending_attr = {}
    for tbl in tables:
        
        logger.info('Table: %s' % tbl['name'])
        
        klass = dbs.query(SapnsClass).\
                    filter(SapnsClass.name == tbl['name']).\
                    first()
        
        if not klass:
            logger.warning('.....creating')
            
            klass = SapnsClass()
            klass.name = tbl['name']
            klass.title = tbl['name'].title()
            desc = unicode(l_('Class: %s'))
            klass.description =  desc % tbl['name']
            
            dbs.add(klass)
            dbs.flush()
            
            # # grant access (r/w) to managers
            managers.add_privilege(klass.class_id)

        else:
            logger.warning('.....already exists')
            
        tables_id[tbl['name']] = klass.class_id
            
        # create an action
        def create_action(name, type_):
            action = dbs.query(SapnsPermission).\
                        filter(and_(SapnsPermission.class_id == klass.class_id,
                                    SapnsPermission.type == type_)).\
                        first()
                            
            if not action:
                action = SapnsPermission()
                action.permission_name = '%s#%s' % (klass.name, name.lower())
                action.display_name = name
                action.type = type_
                action.class_id = klass.class_id
                
                dbs.add(action)
                dbs.flush()
                
                # add this action to "managers" role
                managers.permissions_.append(action)
                dbs.flush()
                
            elif action.type == SapnsPermission.TYPE_LIST:
                for s in action.shortcuts:
                    s.title = action.class_.title
                    dbs.add(s)
                    dbs.flush()
                
        # create standard actions
        create_action(unicode(l_('New')), SapnsPermission.TYPE_NEW)
        create_action(unicode(l_('Edit')), SapnsPermission.TYPE_EDIT)
        create_action(unicode(l_('Delete')), SapnsPermission.TYPE_DELETE)
        create_action(unicode(l_('List')), SapnsPermission.TYPE_LIST)
        create_action(unicode(l_('Docs')), SapnsPermission.TYPE_DOCS)
            
        first_ref = False
        for i, col in enumerate(tbl['columns']):
            
            logger.info('Column: %s' % col['name'])
            
            attr = dbs.query(SapnsAttribute).\
                    filter(and_(SapnsAttribute.name == col['name'],
                                SapnsAttribute.class_id == klass.class_id, 
                                )).\
                    first()
                    
            if not attr and col['name'] != 'id':
                logger.warning('.....creating')
                
                attr = SapnsAttribute()
                attr.name = col['name']
                attr.title = col['name'].replace('_', ' ').title()
                attr.class_id = klass.class_id
                attr.type = col['type_name']
                if attr.type == SapnsAttribute.TYPE_STRING and not first_ref:
                    attr.reference_order = 0
                    first_ref = True
                    
                attr.visible = True
                attr.insertion_order = i
                
                if attr.type == SapnsAttribute.TYPE_INTEGER and \
                not attr.name.startswith('id_'):
                    # signed
                    attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'
                    
                elif attr.type == SapnsAttribute.TYPE_FLOAT:
                    # signed
                    # col['prec']
                    # col['scale']
                    attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                        (col['prec']-col['scale'],
                         col['scale'])
                        
                elif attr.type == SapnsAttribute.TYPE_TIME:
                    attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'
                
                dbs.add(attr)
                dbs.flush()
                
                # grant access (r/w) to managers
                rw_access = SapnsAttrPrivilege.ACCESS_READWRITE
                managers.add_attr_privilege(attr.attribute_id, rw_access)
                
            else:
                logger.warning('.....already exists')
                
                # fill the "field_regex"
                if attr and not attr.field_regex:
                    if attr.type == SapnsAttribute.TYPE_INTEGER and \
                    not attr.name.startswith('id_'):
                        # signed
                        attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'
                        
                    elif attr.type == SapnsAttribute.TYPE_FLOAT:
                        # signed
                        attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                            (col['prec'] - col['scale'], col['scale'])
                            
                    elif attr.type == SapnsAttribute.TYPE_TIME:
                        attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'
                
            # foreign key
            if col['fk_table'] != None:
                pending_attr[attr.attribute_id] = col['fk_table'].name
        
    # update related classes
    for attr_id, fk_table in pending_attr.iteritems():
        attr = dbs.query(SapnsAttribute).get(attr_id)
        attr.related_class_id = tables_id[fk_table]
        
        dbs.add(attr)
        dbs.flush()
예제 #26
0
    def delete(self, cls, id_, **kw):

        #came_from = get_paramw(kw, 'came_from', opcional=True, por_defecto='/')

        logger = logging.getLogger('DashboardController.delete')
        rel_tables = []
        try:
            user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
            permissions = request.identity['permissions']
            cls_ = SapnsClass.by_name(cls)
            ch_cls_ = SapnsClass.by_name(cls, parent=False)

            # check privilege on this class
            if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \
            not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_DELETE) in permissions or \
                 '%s#%s' % (cls_.name, SapnsPermission.TYPE_DELETE) in permissions):
                return dict(
                    status=False,
                    message=_(
                        'Sorry, you do not have privilege on this class'))

            # does the record exist?
            meta = MetaData(dbs.bind)
            tbl = Table(cls_.name, meta, autoload=True)

            try:
                id_ = int(id_)

            except:
                id_ = sj.loads(id_)

            if isinstance(id_, int):
                # int
                this_record = dbs.execute(
                    tbl.select(tbl.c.id == id_)).fetchone()
                if not this_record:
                    return dict(status=False,
                                message=_('Record does not exist'))

            else:
                # array of ints
                these_records = dbs.execute(tbl.select(
                    tbl.c.id.in_(id_))).fetchall()
                if len(these_records) != len(id_):
                    return dict(status=False,
                                message=_('Some records do not exist'))

            # look for objects in other classes that are related with this

            rel_classes = cls_.related_classes()
            for rcls in rel_classes:

                logger.info('Related class: "%s.%s"' %
                            (rcls['name'], rcls['attr_name']))
                rtbl = Table(rcls['name'], meta, autoload=True)
                attr_name = rcls['attr_name']

                if isinstance(id_, int):
                    # int
                    i = id_

                else:
                    # array of ints
                    i = id_[0]

                sel = rtbl.select(whereclause=rtbl.c[attr_name] == int(i))
                robj = dbs.execute(sel).fetchone()

                if robj != None:
                    rel_tables.append(
                        dict(class_title=rcls['title'],
                             attr_title=rcls['attr_title']))

                else:
                    logger.info('---No related objects have been found')

            # delete record
            if isinstance(id_, int):
                # int
                tbl.delete(tbl.c.id == id_).execute()

                # log
                SapnsLog.register(
                    table_name=cls_.name,
                    row_id=id_,
                    who=user.user_id,
                    what=_('delete'),
                )

            else:
                # array of int's
                tbl.delete(tbl.c.id.in_(id_)).execute()

                for i in id_:
                    # log
                    SapnsLog.register(
                        table_name=cls_.name,
                        row_id=i,
                        who=user.user_id,
                        what=_('delete'),
                    )

            dbs.flush()

            # success!
            return dict(status=True)

        except Exception, e:
            logger.error(e)
            return dict(status=False, message=str(e), rel_tables=rel_tables)
예제 #27
0
    def save(self, cls, **params):
        """
        IN
          cls          <unicode>
          params
            id         <int>
            came_from  <unicode>
            fld_*      ???        Fields to be saved
        """

        logger = logging.getLogger(__name__ + '/save')
        try:
            #logger.info(params)

            ch_cls = SapnsClass.by_name(cls, parent=False)
            cls = SapnsClass.by_name(cls)
            id_ = get_paramw(params, 'id', int, opcional=True)

            # does this user have permission on this table?
            user = dbs.query(SapnsUser).get(request.identity['user'].user_id)
            permissions = request.identity['permissions']

            if not user.has_privilege(cls.name) or \
            not '%s#%s' % (cls.name, SapnsPermission.TYPE_EDIT) in permissions:
                return dict(status=False)

            # init "update" dictionary
            update = {}

            if id_:
                update['id'] = int(id_)

            READONLY_DENIED = [SapnsAttrPrivilege.ACCESS_READONLY,
                               SapnsAttrPrivilege.ACCESS_DENIED]

            def _strtodatetime(s, fmt):

                # build regex
                regex = r'^\s*%s\s*$' % (fmt.replace('%d', r'(?P<day>([0-2]?[1-9]|3[0-1]))').\
                                         replace('%m', r'(?P<month>(0?[1-9]|1[0-2]))').\
                                         replace('%Y', r'(?P<year>\d{4})').\
                                         replace('%H', r'(?P<hour>([0-1]?[0-9]|2[0-3]))').\
                                         replace('%M', r'(?P<minute>[0-5][0-9])').\
                                         replace('%S', r'(?P<second>[0-5][0-9])').\
                                         replace(' ', r'\s'))

                m1 = re.search(regex, s)
                if m1:
                    try:
                        day = int(m1.groupdict().get('day') or 1)
                        month = int(m1.groupdict().get('month') or 1)
                        year = int(m1.groupdict().get('year') or 1900)
                        hour = int(m1.groupdict().get('hour') or 0)
                        min_ = int(m1.groupdict().get('minute') or 0)
                        sec = int(m1.groupdict().get('second') or 0)

                        return dt.datetime(year, month, day, hour, min_, sec)

                    except Exception, e:
                        logger.error(e)
                        raise
                else:
예제 #28
0
def update_metadata():

    logger = logging.getLogger('lib.sapns.update_metadata')

    managers = SapnsRole.by_name(ROLE_MANAGERS)
    #managers = SapnsRole()

    tables = extract_model(all=True)
    tables_id = {}
    pending_attr = {}
    for tbl in tables:

        logger.info('Table: %s' % tbl['name'])

        klass = dbs.query(SapnsClass).\
                    filter(SapnsClass.name == tbl['name']).\
                    first()

        if not klass:
            logger.warning('.....creating')

            klass = SapnsClass()
            klass.name = tbl['name']
            klass.title = tbl['name'].title()
            desc = unicode(l_('Class: %s'))
            klass.description = desc % tbl['name']

            dbs.add(klass)
            dbs.flush()

            # # grant access (r/w) to managers
            managers.add_privilege(klass.class_id)

        else:
            logger.warning('.....already exists')

        tables_id[tbl['name']] = klass.class_id

        # create an action
        def create_action(name, type_):
            action = dbs.query(SapnsPermission).\
                        filter(and_(SapnsPermission.class_id == klass.class_id,
                                    SapnsPermission.type == type_)).\
                        first()

            if not action:
                action = SapnsPermission()
                action.permission_name = '%s#%s' % (klass.name, name.lower())
                action.display_name = name
                action.type = type_
                action.class_id = klass.class_id

                dbs.add(action)
                dbs.flush()

                # add this action to "managers" role
                managers.permissions_.append(action)
                dbs.flush()

            elif action.type == SapnsPermission.TYPE_LIST:
                for s in action.shortcuts:
                    s.title = action.class_.title
                    dbs.add(s)
                    dbs.flush()

        # create standard actions
        create_action(unicode(l_('New')), SapnsPermission.TYPE_NEW)
        create_action(unicode(l_('Edit')), SapnsPermission.TYPE_EDIT)
        create_action(unicode(l_('Delete')), SapnsPermission.TYPE_DELETE)
        create_action(unicode(l_('List')), SapnsPermission.TYPE_LIST)
        create_action(unicode(l_('Docs')), SapnsPermission.TYPE_DOCS)

        first_ref = False
        for i, col in enumerate(tbl['columns']):

            logger.info('Column: %s' % col['name'])

            attr = dbs.query(SapnsAttribute).\
                    filter(and_(SapnsAttribute.name == col['name'],
                                SapnsAttribute.class_id == klass.class_id,
                                )).\
                    first()

            if not attr and col['name'] != 'id':
                logger.warning('.....creating')

                attr = SapnsAttribute()
                attr.name = col['name']
                attr.title = col['name'].replace('_', ' ').title()
                attr.class_id = klass.class_id
                attr.type = col['type_name']
                if attr.type == SapnsAttribute.TYPE_STRING and not first_ref:
                    attr.reference_order = 0
                    first_ref = True

                attr.visible = True
                attr.insertion_order = i

                if attr.type == SapnsAttribute.TYPE_INTEGER and \
                not attr.name.startswith('id_'):
                    # signed
                    attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'

                elif attr.type == SapnsAttribute.TYPE_FLOAT:
                    # signed
                    # col['prec']
                    # col['scale']
                    attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                        (col['prec']-col['scale'],
                         col['scale'])

                elif attr.type == SapnsAttribute.TYPE_TIME:
                    attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'

                dbs.add(attr)
                dbs.flush()

                # grant access (r/w) to managers
                rw_access = SapnsAttrPrivilege.ACCESS_READWRITE
                managers.add_attr_privilege(attr.attribute_id, rw_access)

            else:
                logger.warning('.....already exists')

                # fill the "field_regex"
                if attr and not attr.field_regex:
                    if attr.type == SapnsAttribute.TYPE_INTEGER and \
                    not attr.name.startswith('id_'):
                        # signed
                        attr.field_regex = r'^\s*(\+|\-)?\d+\s*$'

                    elif attr.type == SapnsAttribute.TYPE_FLOAT:
                        # signed
                        attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \
                            (col['prec'] - col['scale'], col['scale'])

                    elif attr.type == SapnsAttribute.TYPE_TIME:
                        attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$'

            # foreign key
            if col['fk_table'] != None:
                pending_attr[attr.attribute_id] = col['fk_table'].name

    # update related classes
    for attr_id, fk_table in pending_attr.iteritems():
        attr = dbs.query(SapnsAttribute).get(attr_id)
        attr.related_class_id = tables_id[fk_table]

        dbs.add(attr)
        dbs.flush()