Beispiel #1
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 ids == []:
            raise common.message(_('Nothing to print!'))

        datas['id'] = ids[0]

    try:
        ctx = dict(rpc.session.context)
        ctx.update(datas.get('context', {}))
        report_id = rpc.session.execute('report', 'report', name, ids, datas,
                                        ctx)
        state = False
        attempt = 0
        while not state:
            val = rpc.session.execute('report', 'report_get', report_id)
            state = val['state']
            if not state:
                time.sleep(1)
                attempt += 1
            if attempt > 200:
                raise common.message(_('Printing aborted, too long delay!'))

        # report name
        report_name = 'report'
        report_type = val['format']

        if name != 'custom':
            proxy = rpc.RPCProxy('ir.actions.report.xml')
            res = proxy.search([('report_name', '=', name)])
            if res:
                report_name = proxy.read(res[0], ['name'])['name']

        report_name = report_name.replace('Print ', '')
        cherrypy.response.headers[
            'Content-Disposition'] = 'filename="' + report_name + '.' + report_type + '"'

        return _print_data(val)

    except rpc.RPCException, e:
        raise e
Beispiel #2
0
    def default(self, view_id):

        try:
            view_id = eval(view_id)
        except:
            pass

        if isinstance(view_id, basestring) or not view_id:
            raise common.message(_("Invalid view id."))

        proxy = rpc.RPCProxy('ir.ui.view')
        res = proxy.read([view_id], ['model', 'type'])[0]

        model = res['model']
        view_type = res['type']

        headers = [{'string' : 'Name', 'name' : 'string', 'type' : 'char'},
                   {'string' : '', 'name': 'add', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'delete', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'edit', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'up', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'down', 'type' : 'image', 'width': 2}]

        tree = tw.treegrid.TreeGrid('view_tree', model=model, headers=headers, url='/viewed/data?view_id='+str(view_id))
        tree.showheaders = False
        tree.onselection = 'onSelect'
        tree.onbuttonclick = 'onButtonClick'
        tree.expandall = True

        return dict(view_id=view_id, view_type=view_type, model=model, tree=tree)
Beispiel #3
0
 def action(self, **kw):
     params, data = TinyDict.split(kw)
     
     id = params.id or False
     ids = params.selection or []
     
     if not ids and id:
         ids = [id]
         
     if not id and ids:
         id = ids[0]
         
     domain = params.domain or []
     context = params.context or {}
     context.update(rpc.session.context.copy())
     context.update({'active_id':  rpc.session.active_id, 'active_ids': [rpc.session.active_id]})
     
     if not params.selection and not params.id:
         raise common.message(_('You must save this record to use the sidebar button!'))
     
     if not params.action:
         return self.do_action('client_action_multi', datas=kw)
     
     action_type = rpc.RPCProxy('ir.actions.actions').read(params.action, ['type'], context)['type']
     action = rpc.session.execute('object', 'execute', action_type, 'read', params.action, False, context)
     
     action['domain'] = domain or []
     action['context'] = context or {}
     
     from openerp.controllers import actions
     return actions.execute(action, model=params.model, id=id, ids=ids, report_type='pdf')
Beispiel #4
0
    def do_action(self, name, adds={}, datas={}):
        params, data = TinyDict.split(datas)

        model = params.model

        id = params.id or False
        ids = params.selection or params.ids or []

        if params.view_type == 'form':
            #TODO: save current record
            ids = (id or []) and [id]

        if id and not ids:
            ids = [id]

        if len(ids):
            from openerp.controllers import actions
            return actions.execute_by_keyword(name,
                                              adds=adds,
                                              model=model,
                                              id=id,
                                              ids=ids,
                                              report_type='pdf')
        else:
            raise common.message(_("No record selected!"))
Beispiel #5
0
def export_csv(fields, result, write_title=False):
    try:
        fp = StringIO.StringIO()
        writer = csv.writer(fp)
        if write_title:
            writer.writerow(fields)
        for data in result:
            row = []
            for d in data:
                if isinstance(d, basestring):
                    d = d.replace('\n', ' ').replace('\t', ' ')
                    try:
                        d = d.encode('utf-8')
                    except:
                        pass
                row.append(d)

            writer.writerow(row)

        fp.seek(0)
        data = fp.read()
        fp.close()

        return data
    except IOError, (errno, strerror):
        raise common.message(
            _("Operation failed!\nI/O error") + "(%s)" % (errno, ))
Beispiel #6
0
def execute_url(**data):
    url = data.get('url') or ''

    if not ('://' in url or url.startswith('/')):
        raise common.message(_('Relative URLs are not supported!'))

    raise tools.redirect(url)
Beispiel #7
0
def export_csv(fields, result, write_title=False):
    try:
        fp = StringIO.StringIO()
        writer = csv.writer(fp)
        if write_title:
            writer.writerow(fields)
        for data in result:
            row = []
            for d in data:
                if isinstance(d, basestring):
                    d = d.replace('\n',' ').replace('\t',' ')
                    try:
                        d = d.encode('utf-8')
                    except:
                        pass
                row.append(d)

            writer.writerow(row)

        fp.seek(0)
        data = fp.read()
        fp.close()

        return data
    except IOError, (errno, strerror):
        raise common.message(_("Operation failed!\nI/O error")+"(%s)" % (errno,))
Beispiel #8
0
    def default(self, view_id):

        try:
            view_id = eval(view_id)
        except:
            pass

        if isinstance(view_id, basestring) or not view_id:
            raise common.message(_("Invalid view id."))

        proxy = rpc.RPCProxy('ir.ui.view')
        res = proxy.read([view_id], ['model', 'type'])[0]

        model = res['model']
        view_type = res['type']

        headers = [{'string' : 'Name', 'name' : 'string', 'type' : 'char'},
                   {'string' : '', 'name': 'add', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'delete', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'edit', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'up', 'type' : 'image', 'width': 2},
                   {'string' : '', 'name': 'down', 'type' : 'image', 'width': 2}]

        tree = tw.treegrid.TreeGrid('view_tree', model=model, headers=headers, url='/viewed/data?view_id='+str(view_id))
        tree.showheaders = False
        tree.onselection = 'onSelect'
        tree.onbuttonclick = 'onButtonClick'
        tree.expandall = True

        return dict(view_id=view_id, view_type=view_type, model=model, tree=tree)
Beispiel #9
0
    def action(self, **kw):
        params, data = TinyDict.split(kw)
        
        id = params.id or False
        ids = params.selection or []
        context = params.context or {}
        action = {}

        if data.get('datas'):
            action = eval(data.get('datas'))
        type = action.get('type')
        act_id = params.action

        if not ids and id:
            ids = [id]

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

        domain = params.domain or []
        if not params.selection and not params.id:
            raise common.message(_('You must save this record to use the sidebar button!'))
        
        if not act_id:
            return self.do_action('client_action_multi', datas=kw)
        if type is None:
            action_type = rpc.RPCProxy('ir.actions.actions').read(act_id, ['type'], rpc.session.context)['type']
            action = rpc.session.execute('object', 'execute', action_type, 'read', act_id, False, rpc.session.context)

        action['domain'] = domain or []
        action['context'] = context or {}
        
        from openerp.controllers import actions
        return actions.execute(action, model=params.model, id=id, ids=ids, report_type='pdf')
Beispiel #10
0
    def switch(self, **kw):

        params, data = TinyDict.split(kw)

        ids = params.selection or []            
        if len(ids):
            from openerp.controllers import actions
            return actions.execute_window(False, res_id=ids, model=params.model, domain=params.domain)
        else:
            raise common.message(_('No resource selected!'))
Beispiel #11
0
    def switch(self, **kw):

        params, data = TinyDict.split(kw)

        ids = params.selection or []            
        if len(ids):
            from openerp.controllers import actions
            return actions.execute_window(False, res_id=ids, model=params.model, domain=params.domain)
        else:
            raise common.message(_('No resource selected!'))
Beispiel #12
0
def execute_window(view_ids,
                   model,
                   res_id=False,
                   domain=None,
                   view_type='form',
                   context={},
                   mode='form,tree',
                   name=None,
                   target=None,
                   limit=None):
    """Performs `actions.act_window` action.

    @param view_ids: view ids
    @param model: a model for which the action should be performed
    @param res_id: resource id
    @param domain: domain
    @param view_type: view type, eigther `form` or `tree`
    @param context: the context
    @param mode: view mode, eigther `form,tree` or `tree,form` or None

    @return: view (mostly XHTML code)
    """

    params = TinyDict()

    params.model = model
    params.ids = res_id
    params.view_ids = view_ids
    params.domain = domain or []
    params.context = context or {}
    params.limit = limit

    if name:
        params.context['_terp_view_name'] = name

    if params.ids and not isinstance(params.ids, list):
        params.ids = [params.ids]

    params.id = (params.ids or False) and params.ids[0]

    mode = mode or view_type

    if view_type == 'form':
        mode = mode.split(',')
        params.view_mode = mode

        return Form().create(params)

    elif view_type == 'tree':
        return Tree().create(params)

    else:
        raise common.message(_("Invalid View!"))
Beispiel #13
0
def get_action_type(act_id):
    """Get the action type for the given action id.

    @param act_id: the action id
    @return: action type
    """
    res = rpc.session.execute('object', 'execute', 'ir.actions.actions',
                              'read', act_id, ['type'], rpc.session.context)

    if not (res and len(res)):
        raise common.message(_('Action not found!'))

    return res['type']
Beispiel #14
0
def _print_data(data):

    if 'result' not in data:
        raise common.message(_('Error no report'))

    if data.get('code', 'normal') == 'zlib':
        import zlib
        content = zlib.decompress(base64.decodestring(data['result']))
    else:
        content = base64.decodestring(data['result'])

    cherrypy.response.headers['Content-Type'] = PRINT_FORMATS[data['format']]
    return content
Beispiel #15
0
    def index(self, model, id=None):

        proxy = rpc.RPCProxy("workflow")
        if id:
            ids = proxy.search([('id', '=', id)], 0, 0, 0, rpc.session.context)
        else:
            ids = proxy.search([('osv', '=', model)], 0, 0, 0, rpc.session.context)

        if not ids:
            raise common.message(_('No workflow associated!'))

        wkf = proxy.read(ids, [], rpc.session.context)[0]
        return dict(wkf=wkf)
Beispiel #16
0
    def index(self, model, id=None):

        proxy = rpc.RPCProxy("workflow")
        if id:
            ids = proxy.search([('id', '=', id)], 0, 0, 0, rpc.session.context)
        else:
            ids = proxy.search([('osv', '=', model)], 0, 0, 0,
                               rpc.session.context)

        if not ids:
            raise common.message(_('No workflow associated!'))

        wkf = proxy.read(ids, [], rpc.session.context)[0]
        return dict(wkf=wkf)
Beispiel #17
0
    def action(self, **kw):
        params, data = TinyDict.split(kw)

        id = params.id or False
        ids = params.selection or []
        context = params.context or {}
        action = {}

        if data.get('datas'):
            action = eval(data.get('datas'))
        type = action.get('type')
        act_id = params.action

        if not ids and id:
            ids = [id]

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

        domain = params.domain or []
        if not params.selection and not params.id:
            raise common.message(
                _('You must save this record to use the sidebar button!'))

        if not act_id:
            return self.do_action('client_action_multi', datas=kw)
        if type is None:
            action_type = rpc.RPCProxy('ir.actions.actions').read(
                act_id, ['type'], rpc.session.context)['type']
            action = rpc.session.execute('object', 'execute', action_type,
                                         'read', act_id, False,
                                         rpc.session.context)

        action['domain'] = domain or []
        action['context'] = context or {}

        from openerp.controllers import actions
        return actions.execute(action,
                               model=params.model,
                               id=id,
                               ids=ids,
                               report_type='pdf')
Beispiel #18
0
    def do_action(self, name, adds={}, datas={}):
        params, data = TinyDict.split(datas)

        model = params.model

        id = params.id or False
        ids = params.selection or params.ids or []

        if params.view_type == 'form':
            #TODO: save current record
            ids = (id or []) and [id]

        if id and not ids:
            ids = [id]

        if len(ids):
            from openerp.controllers import actions
            return actions.execute_by_keyword(name, adds=adds, model=model, id=id, ids=ids, report_type='pdf')
        else:
            raise common.message(_("No record selected!"))
Beispiel #19
0
    def do_action(self, name, adds={}, datas={}):
        params, data = TinyDict.split(datas)

        model = params.model
        context = params._terp_context or {}
        ids = data.get('ids') or []

        ctx = rpc.session.context.copy()
        ctx.update(context)

        if ids:
            ids = [int(id) for id in ids.split(',')]

        id = (ids or False) and ids[0]

        if len(ids):
            from openerp.controllers import actions
            return actions.execute_by_keyword(name, adds=adds, model=model, id=id, ids=ids, context=ctx, report_type='pdf')
        else:
            raise common.message(_("No record selected!"))
Beispiel #20
0
    def index(self, model, id):

        id = int(id)

        if id:
            ctx = {}
            ctx.update(rpc.session.context.copy())

            action = rpc.session.execute('object', 'execute', 'ir.attachment', 'action_get', ctx)

            action['domain'] = [('res_model', '=', model), ('res_id', '=', id)]
            ctx['default_res_model'] = model
            ctx['default_res_id'] = id
            action['context'] = ctx

            return actions.execute(action)
        else:
            raise common.message(_('No record selected! You can only attach to existing record...'))

        return True
Beispiel #21
0
    def do_action(self, name, adds={}, datas={}):
        params, data = TinyDict.split(datas)

        model = params.model
        context = params._terp_context or {}
        ids = data.get('ids') or []

        ctx = rpc.session.context.copy()
        ctx.update(context)

        if ids:
            ids = [int(id) for id in ids.split(',')]

        id = (ids or False) and ids[0]

        if len(ids):
            from openerp.controllers import actions
            return actions.execute_by_keyword(name, adds=adds, model=model, id=id, ids=ids, context=ctx, report_type='pdf')
        else:
            raise common.message(_("No record selected!"))
Beispiel #22
0
    def save(self, translate='fields', **kw):
        params, data = TinyDict.split(kw)
        
        ctx = {}
        ctx = params.context or {}
        ctx.update(rpc.session.context.copy())
        params['context'] = ustr(ctx)
        
        if translate == 'fields':
            if not params.id:
                raise common.message(_("You need to save the resource before adding translations."))

            for lang, value in data.items():

                context = copy.copy(ctx)
                context['lang'] = adapt_context(lang)

                for name, val in value.items():
                    if isinstance(val, basestring):
                        val = [val]

                    for v in val:
                        rpc.session.execute('object', 'execute', params.model, 'write', [params.id], {name : v}, context)

        if translate == 'labels':
            for lang, value in data.items():
                for name, val in value.items():
                    rpc.session.execute('object', 'execute', params.model, 'write_string', False, [lang], {name: val})

        if translate == 'relates':
            for lang, value in data.items():
                for name, val in value.items():
                    rpc.session.execute('object', 'execute', params.models[name], 'write', [int(name)], {'name': val}, {'lang': lang})

        if translate == 'view':
            for lang, value in data.items():
                for id, val in value.items():
                    rpc.session.execute('object', 'execute', 'ir.translation', 'write', [int(id)], {'value': val})

        return self.index(translate=translate, _terp_model=params.model, _terp_id=params.id, ctx=params.context)
Beispiel #23
0
    def index(self, model, id):

        id = int(id)

        if id:
            ctx = {}
            ctx.update(rpc.session.context.copy())

            action = rpc.session.execute('object', 'execute', 'ir.attachment',
                                         'action_get', ctx)

            action['domain'] = [('res_model', '=', model), ('res_id', '=', id)]
            ctx['default_res_model'] = model
            ctx['default_res_id'] = id
            action['context'] = ctx

            return actions.execute(action)
        else:
            raise common.message(
                _('No record selected! You can only attach to existing record...'
                  ))

        return True
Beispiel #24
0
        if not isinstance(fields, list):
            fields = [fields]

        for line in data:
            try:
                datas.append(
                    map(lambda x: x.decode(csvcode).encode('utf-8'), line))
            except:
                datas.append(
                    map(lambda x: x.decode('latin').encode('utf-8'), line))
        try:
            res = rpc.session.execute('object', 'execute', params.model,
                                      'import_data', fields, datas)
        except Exception, e:
            raise common.warning(ustr(e), _('XML-RPC error!'))
        if res[0] >= 0:
            raise common.message(_('Imported %d objects!') % (res[0], ))
        else:
            d = ''
            for key, val in res[1].items():
                d += ('\t%s: %s\n' % (ustr(key), ustr(val)))
            error = _(
                'Unable to import this record:\n%s\nError Message:\n%s\n\n%s'
            ) % (d, res[2], res[3])
            raise common.message(unicode(error))

        return self.imp(**kw)


# vim: ts=4 sts=4 sw=4 si et
Beispiel #25
0
    ctx = dict(data.get('context', {}), **rpc.session.context)
    actions = None
    if 'id' in data:
        try:
            id = data.get('id', False)
            if (id != False): id = int(id)
            actions = rpc.session.execute('object', 'execute', 'ir.values',
                                          'get', 'action', keyword,
                                          [(data['model'], id)], False, ctx)
            actions = map(lambda x: x[2], actions)
        except rpc.RPCException, e:
            raise e

    keyact = {}
    for action in actions:
        keyact[action['name']] = action

    keyact.update(adds)

    if not keyact:
        raise common.message(_('No action defined!'))

    if len(keyact) == 1:
        key = keyact.keys()[0]
        return execute(keyact[key], **data)
    else:
        return Selection().create(keyact, **data)


# vim: ts=4 sts=4 sw=4 si et
Beispiel #26
0
        data = list(csv.reader(input, quotechar=str(csvdel), delimiter=str(csvsep)))[int(csvskip):]
        datas = []
        #if csv_data['combo']:

        if not isinstance(fields, list):
            fields = [fields]

        for line in data:
            try:
                datas.append(map(lambda x:x.decode(csvcode).encode('utf-8'), line))
            except:
                datas.append(map(lambda x:x.decode('latin').encode('utf-8'), line))
        try:
            res = rpc.session.execute('object', 'execute', params.model, 'import_data', fields, datas)
        except Exception, e:
            raise common.warning(ustr(e), _('XML-RPC error!'))
        if res[0]>=0:
            raise common.message(_('Imported %d objects!') % (res[0],))
        else:
            d = ''
            for key,val in res[1].items():
                d+= ('\t%s: %s\n' % (ustr(key),ustr(val)))
            error = _('Unable to import this record:\n%s\nError Message:\n%s\n\n%s') % (d,res[2],res[3])
            raise common.message(unicode(error))

        return self.imp(**kw)


# vim: ts=4 sts=4 sw=4 si et