Exemple #1
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)
Exemple #2
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
Exemple #3
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)
Exemple #4
0
     except Exception, e:
         logger.error(e)
         transaction.abort()
         
 elif update['type'] == 'sql':
     transaction.begin()
     try:
         for script in update['sql_text'].split('--#'):
             if script.strip():
                 
                 logger.warning(u'[%s] Executing [%s__%s "%s"] "%s..."' % (update['topid'], 
                                                                           update['dirname'], 
                                                                           os.path.basename(update['path']),
                                                                           update['code'],
                                                                           script.strip()[:30].replace('\n', ' '),
                                                                           ))
                 
                 dbs.execute(script.strip())
                 dbs.flush()
                 
         # register update
         add_update(update['code'], update['desc'])
     
         transaction.commit()
                     
     except Exception, e:
         logger.error(e)
         transaction.abort()
         
         
         
Exemple #5
0
                    except ImportError:
                        pass

            _exec_post_conditions('before', 'sapns', update)
            _exec_post_conditions('before', config.get('app.root_folder'),
                                  update)

            meta = MetaData(bind=dbs.bind)
            tbl = Table(cls.name, meta, autoload=True)

            is_insert = False
            if update.get('id'):
                logger.info('Updating object [%d] of "%s"' %
                            (update['id'], cls.name))
                dbs.execute(
                    tbl.update(whereclause=tbl.c.id == update['id'],
                               values=update))

            else:
                logger.info('Inserting new object in "%s"' % cls.name)
                ins = tbl.insert(values=update).returning(tbl.c.id)
                r = dbs.execute(ins)
                is_insert = True

            ch_cls.name = ch_cls.name
            dbs.add(ch_cls)
            dbs.flush()

            if not update.get('id'):
                update['id'] = r.fetchone().id
Exemple #6
0
                except Exception, e:
                    logger.error(e)
                    transaction.abort()

            elif update['type'] == 'sql':
                transaction.begin()
                try:
                    for script in update['sql_text'].split('--#'):
                        if script.strip():

                            logger.warning(
                                u'[%s] Executing [%s__%s "%s"] "%s..."' % (
                                    update['topid'],
                                    update['dirname'],
                                    os.path.basename(update['path']),
                                    update['code'],
                                    script.strip()[:30].replace('\n', ' '),
                                ))

                            dbs.execute(script.strip())
                            dbs.flush()

                    # register update
                    add_update(update['code'], update['desc'])

                    transaction.commit()

                except Exception, e:
                    logger.error(e)
                    transaction.abort()
Exemple #7
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)
Exemple #8
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)
Exemple #9
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
Exemple #10
0
                            f = getattr(c, method_name)
                            f(moment, update)

                    except ImportError:
                        pass

            _exec_post_conditions('before', 'sapns', update)
            _exec_post_conditions('before', config.get('app.root_folder'), update)

            meta = MetaData(bind=dbs.bind)
            tbl = Table(cls.name, meta, autoload=True)

            is_insert = False
            if update.get('id'):
                logger.info('Updating object [%d] of "%s"' % (update['id'], cls.name))
                dbs.execute(tbl.update(whereclause=tbl.c.id == update['id'], values=update))

            else:
                logger.info('Inserting new object in "%s"' % cls.name)
                ins = tbl.insert(values=update).returning(tbl.c.id)
                r = dbs.execute(ins)
                is_insert = True

            ch_cls.name = ch_cls.name
            dbs.add(ch_cls)
            dbs.flush()

            if not update.get('id'):
                update['id'] = r.fetchone().id

            _exec_post_conditions('after', 'sapns', update)