Esempio n. 1
0
    def duplicate(self, **kw):
        params, data = TinyDict.split(kw)

        id = params.id
        ctx = params.context
        model = params.model

        proxy = rpc.RPCProxy(model)
        new_id = proxy.copy(id, {}, ctx)

        if new_id:
            params.id = new_id
            params.ids += [int(new_id)]
            params.count += 1

        args = {'model': params.model,
                'id': params.id,
                'ids': ustr(params.ids),
                'view_ids': ustr(params.view_ids),
                'view_mode': ustr(params.view_mode),
                'domain': ustr(params.domain),
                'context': ustr(params.context),
                'offset': params.offset,
                'limit': params.limit,
                'count': params.count,
                'search_domain': ustr(params.search_domain),
                'filter_domain': ustr(params.filter_domain)}

        if new_id:
            raise redirect(self.path + '/edit', **args)

        raise redirect(self.path + '/view', **args)
Esempio n. 2
0
    def duplicate(self, **kw):
        params, data = TinyDict.split(kw)

        id = params.id
        ctx = params.context
        model = params.model

        proxy = rpc.RPCProxy(model)
        new_id = proxy.copy(id, {}, ctx)

        if new_id:
            params.id = new_id
            params.ids += [int(new_id)]
            params.count += 1

        args = {
            'model': params.model,
            'id': params.id,
            'ids': ustr(params.ids),
            'view_ids': ustr(params.view_ids),
            'view_mode': ustr(params.view_mode),
            'domain': ustr(params.domain),
            'context': ustr(params.context),
            'offset': params.offset,
            'limit': params.limit,
            'count': params.count,
            'search_domain': ustr(params.search_domain),
            'filter_domain': ustr(params.filter_domain)
        }

        if new_id:
            raise redirect(self.path + '/edit', **args)

        raise redirect(self.path + '/view', **args)
Esempio n. 3
0
    def cancel(self, **kw):
        params, data = TinyDict.split(kw)

        if params.button:
            res = self.button_action(params)
            if res:
                return res
            raise redirect('/')

        if not params.id and params.ids:
            params.id = params.ids[0]

        if params.id and params.editable:
            raise redirect(self.path + "/view",
                           model=params.model,
                           id=params.id,
                           ids=ustr(params.ids),
                           view_ids=ustr(params.view_ids),
                           view_mode=ustr(params.view_mode),
                           domain=ustr(params.domain),
                           context=ustr(params.context),
                           offset=params.offset,
                           limit=params.limit,
                           count=params.count,
                           search_domain=ustr(params.search_domain),
                           search_data=ustr(params.search_data),
                           filter_domain=ustr(params.filter_domain))

        params.view_type = 'tree'
        return self.create(params)
Esempio n. 4
0
    def cancel(self, **kw):
        params, data = TinyDict.split(kw)

        if params.button:
            res = self.button_action(params)
            if res:
                return res
            raise redirect('/')

        if not params.id and params.ids:
            params.id = params.ids[0]

        if params.id and params.editable:
            raise redirect(self.path + "/view", model=params.model,
                                               id=params.id,
                                               ids=ustr(params.ids),
                                               view_ids=ustr(params.view_ids),
                                               view_mode=ustr(params.view_mode),
                                               domain=ustr(params.domain),
                                               context=ustr(params.context),
                                               offset=params.offset,
                                               limit=params.limit,
                                               count=params.count,
                                               search_domain=ustr(params.search_domain),
                                               search_data = ustr(params.search_data),
                                               filter_domain= ustr(params.filter_domain))

        params.view_type = 'tree'
        return self.create(params)
def sso_login(self, db=None, *args, **kwargs):
    db, user, security_key = _get_connection_info(db)
    _check_connection_info(db, user, security_key)
    if db and user and security_key:
        user_info = rpc.session.execute_noauth('common', 'sso_login', db, user, security_key)
        if user_info and user_info['id'] > 0:
            rpc.session._logged_as(db, user_info['id'], user_info['password'])
            raise redirect('/')
        elif sso_portal == '/':
            return login(sso_portal, message='Unknown user!', db=db, user=user, action='sso_login')
    raise redirect(sso_portal)
Esempio n. 6
0
    def clear_binary_data(self, **kw):
        params, data = TinyDict.split(kw)

        proxy = rpc.RPCProxy(params.model)
        ctx = utils.context_with_concurrency_info(params.context,
                                                  params.concurrency_info)

        if params.fname:
            proxy.write([params.id], {
                params.field: False,
                params.fname: False
            }, ctx)
        else:
            proxy.write([params.id], {params.field: False}, ctx)

        args = {
            'model': params.model,
            'id': params.id,
            'ids': ustr(params.ids),
            'view_ids': ustr(params.view_ids),
            'view_mode': ustr(params.view_mode),
            'domain': ustr(params.domain),
            'context': ustr(params.context),
            'offset': params.offset,
            'limit': params.limit,
            'count': params.count,
            'search_domain': ustr(params.search_domain),
            'filter_domain': ustr(params.filter_domain)
        }

        raise redirect(self.path + '/edit', **args)
Esempio n. 7
0
    def clear_binary_data(self, **kw):
        params, data = TinyDict.split(kw)

        proxy = rpc.RPCProxy(params.model)
        ctx = utils.context_with_concurrency_info(params.context, params.concurrency_info)

        if params.fname:
            proxy.write([params.id], {params.field: False, params.fname: False}, ctx)
        else:
            proxy.write([params.id], {params.field: False}, ctx)

        args = {'model': params.model,
                'id': params.id,
                'ids': ustr(params.ids),
                'view_ids': ustr(params.view_ids),
                'view_mode': ustr(params.view_mode),
                'domain': ustr(params.domain),
                'context': ustr(params.context),
                'offset': params.offset,
                'limit': params.limit,
                'count': params.count,
                'search_domain': ustr(params.search_domain),
                'filter_domain': ustr(params.filter_domain)}

        raise redirect(self.path + '/edit', **args)
def sso_logout(self, db=None, *args, **kwargs):
    db, user, security_key = _get_connection_info(db)
    _check_connection_info(db, user, security_key)
    if db and user and security_key:
        rpc.session.execute_noauth('common', 'sso_logout', db, user, security_key)
    rpc.session.logout()  # Same behaviour as the original Root.logout() method
    raise redirect(sso_portal)
Esempio n. 9
0
    def delete(self, model, id):

        id = int(id)

        proxy = rpc.RPCProxy('ir.ui.view')
        proxy.unlink(id)

        raise redirect('/openerp/viewlist', model=model)
Esempio n. 10
0
    def delete(self, model, id):

        id = int(id)

        proxy = rpc.RPCProxy('ir.ui.view')
        proxy.unlink(id)

        raise redirect('/openerp/viewlist', model=model)
Esempio n. 11
0
    def delete_listname(self, **kw):

        params, data = TinyDict.split(kw)
        proxy = rpc.RPCProxy('ir.exports')

        proxy.unlink(params.id)

        raise redirect('/openerp/impex/exp', **kw)
Esempio n. 12
0
    def delete_listname(self, **kw):

        params, data = TinyDict.split(kw)
        proxy = rpc.RPCProxy('ir.exports')

        proxy.unlink(params.id)

        raise redirect('/openerp/impex/exp', **kw)
Esempio n. 13
0
    def delete(self, **kw):
        params, data = TinyDict.split(kw)

        current = params.chain_get(params.source or '') or params
        proxy = rpc.RPCProxy(current.model)

        idx = -1
        if current.id:
            ctx = utils.context_with_concurrency_info(current.context,
                                                      params.concurrency_info)
            res = proxy.unlink([current.id], ctx)
            if current.ids:
                idx = current.ids.index(current.id)
                if idx >= 0:
                    current.ids.remove(current.id)
            params.count -= 1
            if not len(current.ids) and params.count > 0:
                params.offset = params.offset - params.limit
                current.ids = proxy.search([], params.offset, params.limit, 0,
                                           ctx)
                idx = -1
            if idx == len(current.ids):
                idx = -1
        current.id = (current.ids or None) and current.ids[idx]
        self.reset_notebooks()

        args = {
            'model': params.model,
            'id': params.id,
            'ids': ustr(params.ids),
            'view_ids': ustr(params.view_ids),
            'view_mode': ustr(params.view_mode),
            'domain': ustr(params.domain),
            'context': ustr(params.context),
            'offset': params.offset,
            'limit': params.limit,
            'count': params.count,
            'search_domain': ustr(params.search_domain),
            'filter_domain': ustr(params.filter_domain)
        }

        if not params.id:
            raise redirect(self.path + '/edit', **args)

        raise redirect(self.path + '/view', **args)
Esempio n. 14
0
    def add(self, id):
        id = int(id)

        if not self.by_res_id().get(id):
            name = rpc.RPCProxy('ir.ui.menu').name_get([id], rpc.session.context)[0][1]
            rpc.RPCProxy('ir.ui.view_sc').create({'user_id': rpc.session.uid, 'res_id': id, 'resource': 'ir.ui.menu', 'name': name})
            self.refresh_session()

        raise redirect('/openerp/tree/open', id=id, model='ir.ui.menu')
Esempio n. 15
0
    def add(self, id):
        id = int(id)

        if not self.by_res_id().get(id):
            name = rpc.RPCProxy('ir.ui.menu').name_get([id], rpc.get_session().context)[0][1]
            rpc.RPCProxy('ir.ui.view_sc').create({'user_id': rpc.get_session().uid, 'res_id': id, 'resource': 'ir.ui.menu', 'name': name})
            self.refresh_session()

        raise redirect('/openerp/tree/open', id=id, model='ir.ui.menu')
Esempio n. 16
0
    def delete(self, id):
        id = int(id)

        shortcut = self.by_res_id().get(id)
        if shortcut:
            rpc.RPCProxy('ir.ui.view_sc').unlink(shortcut['id'])
            self.refresh_session()

        raise redirect('/openerp/tree/open', id=id, model='ir.ui.menu')
Esempio n. 17
0
    def delete(self, id):
        id = int(id)

        shortcut = self.by_res_id().get(id)
        if shortcut:
            rpc.RPCProxy('ir.ui.view_sc').unlink(shortcut['id'])
            self.refresh_session()

        raise redirect('/openerp/tree/open', id=id, model='ir.ui.menu')
Esempio n. 18
0
    def get(self, record=False):
        record = int(record)
        attachment = rpc.RPCProxy('ir.attachment').read(record, [], rpc.get_session().context)

        if attachment['type'] == 'binary':
            cherrypy.response.headers["Content-Disposition"] = 'attachment; filename="%s"' % attachment['name']
            return base64.decodestring(attachment['datas'])
        elif attachment['type'] == 'url':
            raise redirect(attachment['url'])
        raise Exception('Unknown attachment type %(type)s for attachment name %(name)s' % attachment)
Esempio n. 19
0
    def delete(self, **kw):
        params, data = TinyDict.split(kw)

        current = params.chain_get(params.source or '') or params
        proxy = rpc.RPCProxy(current.model)

        idx = -1
        if current.id:
            ctx = utils.context_with_concurrency_info(current.context, params.concurrency_info)
            res = proxy.unlink([current.id], ctx)
            if current.ids:
                idx = current.ids.index(current.id)
                if idx >= 0:
                    current.ids.remove(current.id)
            params.count -= 1
            if not len(current.ids) and params.count > 0:
                params.offset = max(params.offset - params.limit, 0)
                current.ids = proxy.search([], params.offset, params.limit,0, ctx)
                idx = -1
            if idx == len(current.ids):
                idx = -1
        current.id = (current.ids or None) and current.ids[idx]
        self.reset_notebooks()

        args = {'model': params.model,
                'id': params.id,
                'ids': ustr(params.ids),
                'view_ids': ustr(params.view_ids),
                'view_mode': ustr(params.view_mode),
                'domain': ustr(params.domain),
                'context': ustr(params.context),
                'offset': params.offset,
                'limit': params.limit,
                'count': params.count,
                'search_domain': ustr(params.search_domain),
                'filter_domain': ustr(params.filter_domain),
                'sidebar_closed': params.sidebar_closed}

        if not params.id:
            raise redirect(self.path + '/edit', **args)

        raise redirect(self.path + '/view', **args)
Esempio n. 20
0
    def create(self, model, **kw):

        view_name = kw.get('name')
        view_type = kw.get('type')
        priority = kw.get('priority', 16)

        if not view_name:
            raise redirect('/openerp/viewlist', model=model)

        proxy = rpc.RPCProxy(model)
        fields = proxy.fields_get({}).keys()
        string = "Unknown"

        try:
            proxy2 = rpc.RPCProxy('ir.model')
            mid = proxy2.search([('model', '=', model)])[0]
            string = proxy2.read([mid], ['name'])[0]['name']
        except:
            pass

        fname = None
        for n in ('name', 'x_name'):
            if n in fields:
                fname = n
                break

        if fname:
            arch = """<?xml version="1.0"?>
            <%s string="%s">
                <field name="%s"/>
            </%s>
            """ % (view_type, string, fname, view_type)

            proxy = rpc.RPCProxy('ir.ui.view')
            proxy.create(
                dict(model=model,
                     name=view_name,
                     type=view_type,
                     priority=priority,
                     arch=arch))

        raise redirect('/openerp/viewlist', model=model)
Esempio n. 21
0
 def ok(self, **kw):
     params, data = TinyDict.split(kw)
     proxy = rpc.RPCProxy('res.users')
     # validators generally do that...
     for key in data.keys():
         if not data[key]: data[key] = False
         elif int_pattern.match(data[key]):
             data[key] = int(data[key])
     proxy.write([rpc.get_session().uid], data)
     rpc.get_session().context_reload()
     raise redirect('/openerp/pref/create', saved=True)
Esempio n. 22
0
 def ok(self, **kw):
     params, data = TinyDict.split(kw)
     proxy = rpc.RPCProxy('res.users')
     # validators generally do that...
     for key in data.keys():
         if not data[key]: data[key] = False
         elif int_pattern.match(data[key]):
             data[key] = int(data[key])
     proxy.write([rpc.session.uid], data)
     rpc.session.context_reload()
     raise redirect('/openerp/pref/create', saved=True)
Esempio n. 23
0
 def do_backup(self, dbname, password, **kw):
     self.msg = {}
     try:
         res = rpc.session.execute_db('dump', password, dbname)
         if res:
             cherrypy.response.headers['Content-Type'] = "application/data"
             cherrypy.response.headers['Content-Disposition'] = 'filename="' + dbname + '.dump"'
             return base64.decodestring(res)
     except Exception:
         self.msg = {'message' : _("Could not create backup.")}
         return self.backup()
     raise redirect('/openerp/login')
 def do_backup(self, dbname, password, **kw):
     self.msg = {}
     try:
         res = rpc.session.execute_db('dump', password, dbname)
         if res:
             cherrypy.response.headers['Content-Type'] = "application/data"
             cherrypy.response.headers[
                 'Content-Disposition'] = 'filename="' + dbname + '.dump"'
             return base64.decodestring(res)
     except Exception:
         self.msg = {'message': _("Could not create backup.")}
         return self.backup()
     raise redirect('/openerp/login')
Esempio n. 25
0
    def save_exp(self, **kw):
        params, data = TinyDict.split(kw)

        selected_list = data.get('fields')
        name = data.get('savelist_name')

        proxy = rpc.RPCProxy('ir.exports')

        if selected_list and name:
            if isinstance(selected_list, basestring):
                selected_list = [selected_list]
            proxy.create({'name' : name, 'resource' : params.model, 'export_fields' : [(0, 0, {'name' : f}) for f in selected_list]})

        raise redirect('/openerp/impex/exp', **kw)
Esempio n. 26
0
    def create(self, model, **kw):

        view_name = kw.get('name')
        view_type = kw.get('type')
        priority = kw.get('priority', 16)

        if not view_name:
            raise redirect('/openerp/viewlist', model=model)

        proxy = rpc.RPCProxy(model)
        fields = proxy.fields_get({}).keys()
        string = "Unknown"

        try:
            proxy2 = rpc.RPCProxy('ir.model')
            mid = proxy2.search([('model','=',model)])[0]
            string = proxy2.read([mid], ['name'])[0]['name']
        except:
            pass

        fname = None
        for n in ('name', 'x_name'):
            if n in fields:
                fname = n
                break

        if fname:
            arch = """<?xml version="1.0"?>
            <%s string="%s">
                <field name="%s"/>
            </%s>
            """ % (view_type, string, fname, view_type)

            proxy = rpc.RPCProxy('ir.ui.view')
            proxy.create(dict(model=model, name=view_name, type=view_type, priority=priority, arch=arch))

        raise redirect('/openerp/viewlist', model=model)
Esempio n. 27
0
    def get(self, record=False):
        record = int(record)
        attachment = rpc.RPCProxy('ir.attachment').read(
            record, [], rpc.session.context)

        if attachment['type'] == 'binary':
            cherrypy.response.headers[
                "Content-Disposition"] = 'attachment; filename="%s"' % attachment[
                    'name']
            return base64.decodestring(attachment['datas'])
        elif attachment['type'] == 'url':
            raise redirect(attachment['url'])
        raise Exception(
            'Unknown attachment type %(type)s for attachment name %(name)s' %
            attachment)
Esempio n. 28
0
    def __init__( self, **attrs ):
        if attrs.get( 'ids' ):
            self.query = []
            self.schema = []
            self.filters = []
            self.rows = []
            self.header = []
            error = False
            if attrs.get( 'ids' ):
                if attrs.get( 'model' ) == 'olap.saved.query':
                    cherrypy.session['saved_model'] = attrs.get( 'model' )
                    cherrypy.session['saved_query_id'] = attrs.get( 'ids' )
#                    cherrypy.session['hier_level'] = ''
                    raise redirect( '/browser', model = attrs.get( 'model' ) )
                else:
                    query_id = rpc.RPCProxy( attrs['model'] ).search( [( 'id', '=', attrs.get( 'ids' )[0] )] )[0]
                    query_logs_obj = rpc.RPCProxy( attrs['model'] ).read( [query_id] )[0]
                    self.query = [str( query_logs_obj['query'] )]
                    cube_obj = rpc.RPCProxy( 'olap.cube' ).read( [query_logs_obj['cube_id'][0]] )[0]
                    self.schema = [cube_obj['schema_id'][1]]
            else:
                error = True
            if not error:
                try:
                    temp = {}
                    filter = self.query[0].split( "where" )
                    if len( filter ) > 1:
                        temp = filter[1].split( "," )
                        temp[0] = temp[0].lstrip()[1:]
                        temp[-1] = temp[-1][:-1]
                        res = []
                        for t in range( len( temp ) ):
                            res.append( [t, temp[t]] )
                        self.filters = res
                    axis, data = rpc.RPCProxy( 'olap.schema' ).request( self.schema[0], self.query[0] )
                    temp = self.form_data( axis, data )
                    self.header = temp['header']
                    self.rows = temp['rows']
                except:
                    error = True
                    rows = False
Esempio n. 29
0
    def save_exp(self, **kw):
        params, data = TinyDict.split(kw)

        selected_list = data.get('fields')
        name = data.get('savelist_name')

        proxy = rpc.RPCProxy('ir.exports')

        if selected_list and name:
            if isinstance(selected_list, basestring):
                selected_list = [selected_list]
            proxy.create({
                'name':
                name,
                'resource':
                params.model,
                'export_fields': [(0, 0, {
                    'name': f
                }) for f in selected_list]
            })

        raise redirect('/openerp/impex/exp', **kw)
Esempio n. 30
0
    def execute(self, params):

        action = params.name
        model = params.model
        state = params.state
        datas = params.datas

        form = None
        buttons = []

        if model:
            action = model.replace('wizard.', '', 1)
        else:
            model = 'wizard.' + action

        params.name = action
        params.model = model
        params.view_mode = []

        if 'form' not in datas:
            datas['form'] = {}

        wiz_id = params.wiz_id or rpc.session.execute('wizard', 'create', action)

        while state != 'end':

            ctx = rpc.session.context.copy()
            ctx.update(datas.get('context' or {}) or {})

            res = rpc.session.execute('wizard', 'execute', wiz_id, datas, state, ctx)

            if 'datas' in res:
                datas['form'].update(res['datas'])
            else:
                res['datas'] = {}

            if res['type']=='form':

                fields = res['fields']
                form_values = {}

                for f in fields:
                    if 'value' in fields[f]:
                        form_values[f] = fields[f]['value']
                    
                    if f in datas['form'] and fields[f]['type'] == "one2many":
                        datas['form'][f] = [(1, d, {}) for d in datas['form'][f]]

                form_values.update(datas['form'])

                datas['form'] = form_values

                res['datas'].update(datas['form'])

                params.is_wizard = True
                params.view_mode = ['form']
                params.view_type = 'form'
                params.views = {'form': res}

                # keep track of datas and some other required information
                params.hidden_fields = [tw.form.Hidden(name='_terp_datas', default=ustr(datas)),
                                        tw.form.Hidden(name='_terp_state2', default=state),
                                        tw.form.Hidden(name='_terp_wiz_id', default=wiz_id)]

                form = tw.form_view.ViewForm(params, name="view_form", action="/openerp/wizard/action")

                buttons = []
                for x in res.get('state', []):
                    x = list(x)
                    x[1] = re.sub('_(?!_)', '', x[1]) # remove mnemonic

                    if len(x) >= 3:
                        x[2] = icons.get_icon(x[2])

                    buttons.append(tuple(x))

                params.state = state
                return dict(form=form, buttons=buttons)

            elif res['type']=='action':
                import actions
                # If configuration is done 
                if res.get('action') and res.get('action').get('res_model') == 'ir.ui.menu' and res['state'] == 'end':
                    return self.end()
                
                act_res = actions.execute(res['action'], **datas)
                if act_res:
                    return act_res
                
                state = res['state']

            elif res['type']=='print':
                import actions

                datas['report_id'] = res.get('report_id', False)
                if res.get('get_id_from_action', False):
                    backup_ids = datas['ids']
                    datas['ids'] = datas['form']['ids']

                return actions.execute_report(res['report'], **datas)

            elif res['type']=='state':
                state = res['state']

        raise redirect('/openerp/wizard/end')
    def execute(self, params):

        action = params.name
        model = params.model
        state = params.state
        datas = params.datas

        form = None
        buttons = []

        if model:
            action = model.replace('wizard.', '', 1)
        else:
            model = 'wizard.' + action

        params.name = action
        params.model = model
        params.view_mode = []

        if 'form' not in datas:
            datas['form'] = {}

        wiz_id = params.wiz_id or rpc.session.execute('wizard', 'create',
                                                      action)

        while state != 'end':

            ctx = rpc.session.context.copy()
            ctx.update(datas.get('context' or {}) or {})

            res = rpc.session.execute('wizard', 'execute', wiz_id, datas,
                                      state, ctx)

            if 'datas' in res:
                datas['form'].update(res['datas'])
            else:
                res['datas'] = {}

            if res['type'] == 'form':

                fields = res['fields']
                form_values = {}

                for f in fields:
                    if 'value' in fields[f]:
                        form_values[f] = fields[f]['value']

                    if f in datas['form'] and fields[f]['type'] == "one2many":
                        datas['form'][f] = [(1, d, {})
                                            for d in datas['form'][f]]

                form_values.update(datas['form'])

                datas['form'] = form_values

                res['datas'].update(datas['form'])

                params.is_wizard = True
                params.view_mode = ['form']
                params.view_type = 'form'
                params.views = {'form': res}

                # keep track of datas and some other required information
                params.hidden_fields = [
                    tw.form.Hidden(name='_terp_datas', default=ustr(datas)),
                    tw.form.Hidden(name='_terp_state2', default=state),
                    tw.form.Hidden(name='_terp_wiz_id', default=wiz_id)
                ]

                form = tw.form_view.ViewForm(params,
                                             name="view_form",
                                             action="/openerp/wizard/action")

                buttons = []
                for x in res.get('state', []):
                    x = list(x)
                    x[1] = re.sub('_(?!_)', '', x[1])  # remove mnemonic

                    if len(x) >= 3:
                        x[2] = icons.get_icon(x[2])

                    buttons.append(tuple(x))

                params.state = state
                return dict(form=form, buttons=buttons)

            elif res['type'] == 'action':
                import actions
                # If configuration is done
                if res.get('action') and res.get('action').get(
                        'res_model') == 'ir.ui.menu' and res['state'] == 'end':
                    return self.end()

                act_res = actions.execute(res['action'], **datas)
                if act_res:
                    return act_res

                state = res['state']

            elif res['type'] == 'print':
                import actions

                datas['report_id'] = res.get('report_id', False)
                if res.get('get_id_from_action', False):
                    backup_ids = datas['ids']
                    datas['ids'] = datas['form']['ids']

                return actions.execute_report(res['report'], **datas)

            elif res['type'] == 'state':
                state = res['state']

        raise redirect('/openerp/wizard/end')
Esempio n. 32
0
 def index(self, *args, **kw):
     raise redirect('/openerp')
    def save(self, terp_save_only=False, tg_source=None, tg_errors=None, tg_exceptions=None, **kw):
        """Controller method to save/button actions...

        @param tg_errors: TG special arg, used durring validation
        @param kw: keyword arguments

        @return: form view
        """
        params, data = TinyDict.split(kw)
        # remember the current notebook tab
        cherrypy.session['remember_notebook'] = True
        if tg_errors:
            return self.create(params, tg_errors=tg_errors)

        # bypass save, for button action in non-editable view
        if not (params.button and not params.editable and params.id):

            proxy = rpc.RPCProxy(params.model)

            if not params.id:
                id = proxy.create(data, params.context)
                cherrypy.session['_bi_terp_id'] = id
                params.ids = (params.ids or []) + [int(id)]
                params.id = int(id)
                params.count += 1
            else:
                params['_terp_bi_type'] = 'true'
                id = proxy.write([params.id], data, params.context)
        button = params.button

        # perform button action
        if params.button:
            res = self.button_action(params)
            if res:
                return res

        current = params.chain_get(params.source or '')
        if current:
            current.id = None
            if not params.id:
                params.id = int(id)
        elif not button:
            params.editable = False

        if terp_save_only:
            params.load_counter = 2
            return dict(params=params, data=data)
        
        args = {'model': params.model,
                'id': params.id,
                'ids': ustr(params.ids),
                'view_ids': ustr(params.view_ids),
                'view_mode': ustr(params.view_mode),
                'domain': ustr(params.domain),
                'context': ustr(params.context),
                'offset': params.offset,
                'limit': params.limit,
                'count': params.count,
                'search_domain': ustr(params.search_domain)}

        if params.editable or params.source or params.return_edit:
            raise redirect(self.path + '/edit', source=params.source, **args)       
        
        params.load_counter = 2
        return self.create(params)
Esempio n. 34
0
def execute_report(name, **data):
    """Executes a report with the given data, on success returns `application/pdf` data

    @param name: name of the report
    @param data: report data

    @return: `application/pdf` data
    """
    datas = data.copy()
    ids = datas['ids']
    del datas['ids']

    if not ids:
        ids =  rpc.session.execute('object', 'execute', datas['model'], 'search', [])
        if not ids:
            raise common.message(_('Nothing to print'))

        datas['id'] = ids[0]

    try:
        ctx = dict(rpc.session.context)
        ctx.update(datas.get('context', {}))
        if is_server_local():
            ctx['report_fromfile'] = 1
        report_id = rpc.session.execute('report', 'report', name, ids, datas, ctx)
        state = False
        attempt = 0
        val = None
        bg_report = False
        background_id = ctx.get('background_id')
        max_attempt = ctx.get('background_time', 200)
        report_name = 'report'

        if name != 'custom':
            proxy = rpc.RPCProxy('ir.actions.report.xml')
            res = proxy.search([('report_name','=', name)])
            if res:
                read_ctx = datas.copy()
                read_ctx.setdefault('context', {}).update(ctx)
                report_name = proxy.read(res[0], ['filename'], read_ctx)['filename']

        report_name = report_name.replace('Print ', '')
        if not ids or not datas.get('id') or not datas.get('model'):
            if datas.get('target_filename'):
                report_name = datas['target_filename']
            elif datas.get('context', {}).get('_terp_view_name'):
                report_name = datas['context']['_terp_view_name']
        attachment = ''
        if datas.get('force_attach'):
            attachment = 'attachment;'
        if background_id:
            bg_report = rpc.session.execute('object', 'execute', 'memory.background.report', 'write', [background_id], {'report_id': report_id, 'report_name': report_name})

        while not state:
            val = rpc.session.execute('report', 'report_get', report_id)
            if not val:
                return False
            state = val['state']
            if not state:
                time.sleep(1)
                attempt += 1
            if attempt>max_attempt:
                if bg_report:
                    cherrypy.response.headers['Content-Type'] = 'text/html'
                    raise tools.redirect('/openerp/downloadbg', res_id=bg_report)
#                    return execute_window(False, 'memory.background.report', res_id=bg_report, domain=[], view_type='form', mode='form', target='new')
                else:
                    raise common.message(_('Printing aborted, too long delay'))

        cherrypy.response.headers['Content-Type'] = 'application/octet-stream'
        report_type = val['format']

        try:
            report_name = report_name.decode('utf-8')
        except UnicodeEncodeError:
            # replace all compatibility characters with their equivalents ("e with accent" becomes "e"...)
            report_name = unicodedata.normalize('NFKD', report_name).encode('ascii','ignore')
        cherrypy.response.headers['Content-Disposition'] = '%sfilename="' % attachment + report_name + '.' + report_type + '"'

        return _print_data(val)

    except rpc.RPCException, e:
        raise e
Esempio n. 35
0
 def clear_cache(self):
     cache.clear()
     raise redirect('/')
Esempio n. 36
0
    def execute(self, params):

        action = params.name
        model = params.model
        state = params.state
        datas = params.datas

        form = None
        buttons = []

        if model:
            action = model.replace("wizard.", "", 1)
        else:
            model = "wizard." + action

        params.name = action
        params.model = model
        params.view_mode = []

        if "form" not in datas:
            datas["form"] = {}

        wiz_id = params.wiz_id or rpc.Wizard().create(action)

        while state != "end":

            ctx = rpc.get_session().context.copy()
            ctx.update(datas.get("context" or {}) or {})

            res = rpc.Wizard().execute(wiz_id, datas, state, ctx)

            if "datas" in res:
                datas["form"].update(res["datas"])
            else:
                res["datas"] = {}

            if res["type"] == "form":

                fields = res["fields"]
                form_values = {}

                for f in fields:
                    if "value" in fields[f]:
                        form_values[f] = fields[f]["value"]

                    if f in datas["form"] and fields[f]["type"] == "one2many":
                        datas["form"][f] = [(1, d, {}) for d in datas["form"][f]]

                form_values.update(datas["form"])

                datas["form"] = form_values

                res["datas"].update(datas["form"])

                params.is_wizard = True
                params.view_mode = ["form"]
                params.view_type = "form"
                params.views = {"form": res}

                # keep track of datas and some other required information
                params.hidden_fields = [
                    tw.form.Hidden(name="_terp_datas", default=ustr(datas)),
                    tw.form.Hidden(name="_terp_state2", default=state),
                    tw.form.Hidden(name="_terp_wiz_id", default=wiz_id),
                ]

                form = tw.form_view.ViewForm(params, name="view_form", action="/openerp/wizard/action")

                buttons = []
                for x in res.get("state", []):
                    x = list(x)
                    x[1] = re.sub("_(?!_)", "", x[1])  # remove mnemonic

                    if len(x) >= 3:
                        x[2] = icons.get_icon(x[2])

                    buttons.append(tuple(x))

                params.state = state
                return dict(form=form, buttons=buttons)

            elif res["type"] == "action":
                import actions

                # If configuration is done
                if res.get("action") and res.get("action").get("res_model") == "ir.ui.menu" and res["state"] == "end":
                    return self.end()

                act_res = actions.execute(res["action"], **datas)
                if act_res:
                    return act_res

                state = res["state"]

            elif res["type"] == "print":
                import actions

                datas["report_id"] = res.get("report_id", False)
                if res.get("get_id_from_action", False):
                    backup_ids = datas["ids"]
                    datas["ids"] = datas["form"]["ids"]

                return actions.execute_report(res["report"], **datas)

            elif res["type"] == "state":
                state = res["state"]

        raise redirect("/openerp/wizard/end")
Esempio n. 37
0
    def save(self, terp_save_only=False, **kw):
        """Controller method to save/button actions...

        @param tg_errors: TG special arg, used durring validation
        @param kw: keyword arguments

        @return: form view
        """
        params, data = TinyDict.split(kw)
        # remember the current page (tab) of notebooks
        cherrypy.session['remember_notebooks'] = True

        Model = rpc.RPCProxy(params.model)
        # bypass save, for button action in non-editable view
        if params.editable:
            if not params.id:

                if params.default_o2m:
                    data.update(params.default_o2m)
                ctx = dict((params.context or {}), **rpc.get_session().context)
                params.id = int(Model.create(data, ctx))
                params.ids = (params.ids or []) + [params.id]
                params.count += 1
            else:
                original_data = Model.read(params.id, data.keys())
                modified = {}

                if original_data and isinstance(original_data, dict):
                    for field, original_value in original_data.iteritems():
                        if isinstance(original_value, tuple):
                            original_data[field] = original_value[0]
                        if field in data and data[field] != original_data[field]:
                            modified[field] = data[field]

                    ctx = utils.context_with_concurrency_info(params.context, params.concurrency_info)
                    Model.write([params.id], modified, ctx)
                else:
                    ctx = utils.context_with_concurrency_info(params.context, params.concurrency_info)
                    Model.write([params.id], data, ctx)

            tw.ConcurrencyInfo.update(
                params.model, Model.read([params.id], ['__last_update'], ctx)
            )

        cherrypy.request.params = params

        button = params.button

        # perform button action
        if params.button:
            res = self.button_action(params)
            if res:
                return res

        current = params.chain_get(params.source or '')
        if current:
            current.id = None
        elif not button:
            params.editable = False

        if terp_save_only:
            return dict(params=params, data=data)

        def get_params(p, f):

            pp = p.chain_get(f)
            px = rpc.RPCProxy(p.model)

            _ids = pp.ids
            _all = px.read([p.id], [f])[0][f]
            _new = [i for i in _all if i not in _ids]

            pp.ids = _all
            if _new:
                pp.id = _new[0]

            return pp

        if params.source and len(params.source.split("/")) > 1:

            path = params.source.split("/")
            p = params
            for f in path:
                p = get_params(p, f)

            return self.create(params)

        args = {'model': params.model,
                'id': params.id,
                'ids': ustr(params.ids),
                'view_ids': ustr(params.view_ids),
                'view_mode': ustr(params.view_mode),
                'domain': ustr(params.domain),
                'context': ustr(params.context),
                'offset': params.offset,
                'limit': params.limit,
                'count': params.count,
                'search_domain': ustr(params.search_domain),
                'search_data': ustr(params.search_data),
                'filter_domain': ustr(params.filter_domain),
                'notebook_tab': params.notebook_tab}
        if params.o2m_edit:
            # hack to avoid creating new record line when editing o2m inline:
            # by default one2many.mako is going to fetch a new line (.create)
            # on /edit
            args['o2m_edit'] = "1"

        if params.editable or params.source or params.return_edit:
            raise redirect(self.path + '/edit', source=params.source, **args)
        raise redirect(self.path + '/view', **args)
 def index(self, *args, **kw):
     raise redirect('/openerp')
Esempio n. 39
0
 def logout(self):
     """ Logout method, will terminate the current session.
     """
     rpc.session.logout()
     raise redirect('/')
Esempio n. 40
0
                    raise DatabaseCreationCrash()
        except DatabaseCreationCrash:
            self.msg = {'message': (_("The server crashed during installation.\nWe suggest you to drop this database.")),
                        'title': (_('Error during database creation'))}
            return self.create()
        except openobject.errors.AccessDenied, e:
            self.msg = {'message': _('Bad super admin password'),
                        'title' : e.title}
            return self.create()
        except Exception:
            self.msg = {'message':_("Could not create database.")}

            return self.create()

        if ok:
            raise redirect('/openerp/menu', {'next': '/openerp/home'})
        raise redirect('/openerp/login', db=dbname)

    @expose(template="/openerp/controllers/templates/database.mako")
    def drop(self, tg_errors=None, **kw):
        form = _FORMS['drop']
        error = self.msg
        self.msg = {}
        return dict(form=form, error=error)

    @expose()
    @validate(form=_FORMS['drop'])
    @error_handler(drop)
    def do_drop(self, dbname, password, **kw):
        self.msg = {}
        try:
Esempio n. 41
0
 def index(self, *args, **kw):
     self.msg = {}
     raise redirect('/openerp/database/create')
Esempio n. 42
0
 def clear_cache(self):
     cache.clear()
     raise redirect('/')
                'title': (_('Error during database creation'))
            }
            return self.create()
        except openobject.errors.AccessDenied, e:
            self.msg = {
                'message': _('Bad super admin password'),
                'title': e.title
            }
            return self.create()
        except Exception:
            self.msg = {'message': _("Could not create database.")}

            return self.create()

        if ok:
            raise redirect('/openerp/menu', {'next': '/openerp/home'})
        raise redirect('/openerp/login', db=dbname)

    @expose(template="/openerp/controllers/templates/database.mako")
    def drop(self, tg_errors=None, **kw):
        form = _FORMS['drop']
        error = self.msg
        self.msg = {}
        return dict(form=form, error=error)

    @expose()
    @validate(form=_FORMS['drop'])
    @error_handler(drop)
    def do_drop(self, dbname, password, **kw):
        self.msg = {}
        try:
 def index(self, *args, **kw):
     self.msg = {}
     raise redirect('/openerp/database/create')
Esempio n. 45
0
    def save(self, terp_save_only=False, **kw):
        """Controller method to save/button actions...

        @param tg_errors: TG special arg, used durring validation
        @param kw: keyword arguments

        @return: form view
        """
        params, data = TinyDict.split(kw)
        # remember the current page (tab) of notebooks
        cherrypy.session['remember_notebooks'] = True

        Model = rpc.RPCProxy(params.model)
        # bypass save, for button action in non-editable view
        if params.editable:
            if not params.id:

                if params.default_o2m:
                    data.update(params.default_o2m)
                ctx = dict((params.context or {}), **rpc.session.context)
                params.id = int(Model.create(data, ctx))
                params.ids = (params.ids or []) + [params.id]
                params.count += 1
            else:
                original_data = Model.read(params.id, data.keys())
                modified = {}

                if original_data and isinstance(original_data, dict):
                    for field, original_value in original_data.iteritems():
                        if isinstance(original_value, tuple):
                            original_data[field] = original_value[0]
                        if field in data and data[field] != original_data[
                                field]:
                            #When field is many2many at that time following code will be applied
                            if isinstance(data[field], list) and isinstance(
                                    data[field][0][2], list):
                                if sorted(data[field][0][2]) != sorted(
                                        original_data[field]):
                                    modified[field] = data[field]
                            else:
                                modified[field] = data[field]

                    ctx = utils.context_with_concurrency_info(
                        params.context, params.concurrency_info)
                    Model.write([params.id], modified, ctx)
                else:
                    ctx = utils.context_with_concurrency_info(
                        params.context, params.concurrency_info)
                    Model.write([params.id], data, ctx)

            tw.ConcurrencyInfo.update(
                params.model, Model.read([params.id], ['__last_update'], ctx))

        cherrypy.request.params = params

        button = params.button

        # perform button action
        if params.button:
            res = self.button_action(params)
            if res:
                return res

        current = params.chain_get(params.source or '')
        if current:
            current.id = None
        elif not button:
            params.editable = False

        if terp_save_only:
            return dict(params=params, data=data)

        def get_params(p, f):

            pp = p.chain_get(f)
            px = rpc.RPCProxy(p.model)

            _ids = pp.ids
            _all = px.read([p.id], [f])[0][f]
            _new = [i for i in _all if i not in _ids]

            pp.ids = _all
            if _new:
                pp.id = _new[0]

            return pp

        if params.source and len(params.source.split("/")) > 1:

            path = params.source.split("/")
            p = params
            for f in path:
                p = get_params(p, f)

            return self.create(params)

        args = {
            'model': params.model,
            'id': params.id,
            'ids': ustr(params.ids),
            'view_ids': ustr(params.view_ids),
            'view_mode': ustr(params.view_mode),
            'domain': ustr(params.domain),
            'context': ustr(params.context),
            'offset': params.offset,
            'limit': params.limit,
            'count': params.count,
            'search_domain': ustr(params.search_domain),
            'search_data': ustr(params.search_data),
            'filter_domain': ustr(params.filter_domain),
            'notebook_tab': params.notebook_tab
        }
        if params.o2m_edit:
            # hack to avoid creating new record line when editing o2m inline:
            # by default one2many.mako is going to fetch a new line (.create)
            # on /edit
            args['o2m_edit'] = "1"

        if params.editable or params.source or params.return_edit:
            raise redirect(self.path + '/edit', source=params.source, **args)
        raise redirect(self.path + '/view', **args)