def imp(self, error=None, records=None, success=None, **kw): params, data = TinyDict.split(kw) ctx = dict((params.context or {}), **rpc.session.context) views = {} if params.view_mode and params.view_ids: for i, view in enumerate(params.view_mode): views[view] = params.view_ids[i] headers = [{'string': 'Name', 'name': 'name', 'type': 'char'}] tree = treegrid.TreeGrid('import_fields', model=params.model, headers=headers, url=tools.url('/openerp/impex/get_fields'), field_parent='relation', views=views, context=ctx, is_importing=1) tree.show_headers = False return dict(error=error, records=records, success=success, model=params.model, source=params.source, tree=tree, fields=kw.get('fields', {}))
def show(self, model, view_id, view_type): view_id = int(view_id) params, data = TinyDict.split({'_terp_model': model, '_terp_ids' : [], '_terp_view_ids' : [view_id], '_terp_view_mode' : [view_type]}) return self.create(params)
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 previous_o2m(self, **kw): params, data = TinyDict.split(kw) if params.get('_terp_save_current_id'): ctx = dict((params.context or {}), **rpc.get_session().context) if params.id: rpc.RPCProxy(params.model).write([params.id], data, ctx) else: id = rpc.RPCProxy(params.model).create(data, ctx) params.ids.append(id) params.count += 1 current = params.chain_get(params.source or '') or params idx = -1 if current.id: # save current record if params.editable: self.save(terp_save_only=True, **kw) idx = current.ids.index(current.id) idx = idx-1 if idx == len(current.ids): idx = len(current.ids) -1 if current.ids: current.id = current.ids[idx] return self.create(params)
def button_action(self, **kw): params, data = TinyDict.split(kw) error = None reload = (params.context or {}).get('reload', False) result = {} wiz_result = None name = params.button_name btype = params.button_type id = params.id model = params.model id = (id or False) and int(id) ids = (id or []) and [id] try: if btype == 'workflow': rpc.session.execute('object', 'exec_workflow', model, name, id) elif btype == 'object': ctx = params.context or {} ctx.update(rpc.session.context.copy()) res = rpc.session.execute('object', 'execute', model, name, ids, ctx) if isinstance( res, dict) and res.get('type') == 'ir.actions.act_url': result = res elif btype == 'action': from openerp.controllers import actions action_id = int(name) action_type = actions.get_action_type(action_id) if action_type == 'ir.actions.wizard': cherrypy.session['wizard_parent_form'] = '/form' cherrypy.session['wizard_parent_params'] = params res = actions.execute_by_id(action_id, type=action_type, model=model, id=id, ids=ids) if isinstance( res, dict) and res.get('type') == 'ir.actions.act_url': result = res elif isinstance(res, basestring): wiz_result = { 'model': model, 'action_id': action_id, 'id': id } else: error = "Unallowed button type" except Exception, e: error = ustr(e)
def get_namelist(self, **kw): params, data = TinyDict.split(kw) ctx = params.context or {} ctx.update(rpc.session.context.copy()) res = [] ids = [] id = params.id res = self.get_data(params.model, ctx) ir_export = rpc.RPCProxy('ir.exports') ir_export_line = rpc.RPCProxy('ir.exports.line') field = ir_export.read(id) fields = ir_export_line.read(field['export_fields']) name_list = [] ids = [f['name'] for f in fields] for name in ids: name_list += [(name, res.get(name))] return dict(name_list=name_list)
def eval_domain_and_context(self, **kw): params, data = TinyDict.split(kw) domain = kw.get('_terp_domain', []) context = params.context or {} parent_context = dict(params.parent_context or {}, **rpc.session.context) # filter out default_* and search_default_* from context, # but not when doing a search from the 'search view' (we have to keep parent context) if params.search_mode != 'true': parent_context = self.context_get(params.parent_context) or {} # update active_id in context for links parent_context.update(active_id=params.active_id or False, active_ids=params.active_ids or []) if 'group_by' in parent_context: if isinstance(params.group_by, str): parent_context['group_by'] = cleanup_group_by( params.group_by).split(',') else: parent_context['group_by'] = params.group_by try: ctx = TinyForm(**kw).to_python() pctx = ctx except TinyFormError, e: return dict(error_field=e.field, error=ustr(e))
def moveDown(self, **kw): params, data = TinyDict.split(kw) id = params.id ids = params.ids or [] if id not in ids or ids.index(id) == len(ids) - 1: return dict() proxy = rpc.RPCProxy(params.model) ctx = rpc.session.context.copy() next_id = ids[ids.index(id) + 1] try: res = proxy.read([id, next_id], ['sequence'], ctx) records = dict([(r['id'], r['sequence']) for r in res]) cur_seq = records[id] next_seq = records[next_id] if cur_seq == next_seq: proxy.write([next_id], {'sequence': cur_seq + 1}, ctx) proxy.write([id], {'sequence': next_seq}, ctx) else: proxy.write([id], {'sequence': next_seq}, ctx) proxy.write([next_id], {'sequence': cur_seq}, ctx) return dict() except Exception, e: return dict(error=str(e))
def remove(self, **kw): params, data = TinyDict.split(kw) sc_ids = [i['id'] for i in cherrypy.session['terp_shortcuts']] error = None proxy = rpc.RPCProxy(params.model) if params.id: if params.model == 'ir.ui.view_sc' and cherrypy.session.get( 'terp_shortcuts'): for sc in cherrypy.session.get('terp_shortcuts'): for id in params.id: if id == sc['id']: cherrypy.session['terp_shortcuts'].remove(sc) try: ctx = context_with_concurrency_info(params.context, params.concurrency_info) if isinstance(params.id, list): res = proxy.unlink(params.id, ctx) for i in params.id: params.ids.remove(i) else: res = proxy.unlink([params.id], ctx) params.ids.remove(params.id) if params.model == 'res.request': ids, ids2 = rpc.RPCProxy(params.model).request_get() return dict(res_ids=ids) return dict(ids=params.ids, count=len(params.ids)) except Exception, e: error = ustr(e)
def reload_graph(self, **kw): params, data = TinyDict.split(kw) view = cache.fields_view_get(params.model, params.view_id, 'graph', params.context) if params.group_by_ctx: if isinstance(params.group_by_ctx, str): params.group_by_ctx = params.group_by_ctx.split('group_')[-1] else: params.group_by_ctx = map(lambda x: x.split('group_')[-1], params.group_by_ctx) if params.domain is None: params.domain = [] if params.search_domain: params.domain.extend(params.search_domain) if not params.group_by_ctx: params.ids = None from view_graph.widgets import _graph wid = _graph.Graph(model=params.model, view=view, view_id=params.view_id, ids=params.ids, domain=params.domain, view_mode=params.view_mode, context=params.context, group_by=params.group_by_ctx) view = ustr(wid.render()) return dict(view=view)
def export_data(self, fname, fields, import_compat=False, **kw): params, data_index = TinyDict.split(kw) proxy = rpc.RPCProxy(params.model) flds = [] for item in fields: fld = item.replace('/.id', '.id') flds.append(fld) if isinstance(fields, basestring): fields = fields.replace('/.id', '.id') flds = [fields] ctx = dict((params.context or {}), **rpc.session.context) ctx['import_comp'] = bool(int(import_compat)) domain = params.seach_domain or [] ids = params.ids or proxy.search(domain, 0, 0, 0, ctx) result = datas_read(ids, params.model, flds, context=ctx) if result.get('warning'): common.warning(unicode(result.get('warning', False)), _('Export Error')) return False result = result.get('datas', []) if import_compat: params.fields2 = flds return export_csv(params.fields2, result)
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 = map(int, ids.split(',')) id = (ids or False) and ids[0] if ids: 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"))
def import_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, fields=[], **kw): params, data = TinyDict.split(kw) content = csvfile.file.read() input = StringIO.StringIO(content) 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!'))
def reload_graph(self, **kw): params, data = TinyDict.split(kw) view = cache.fields_view_get(params.model, params.view_id, 'graph',params.context) if params.group_by_ctx: if isinstance(params.group_by_ctx, str): params.group_by_ctx = params.group_by_ctx.split('group_')[-1] else: params.group_by_ctx = map(lambda x: x.split('group_')[-1], params.group_by_ctx) if params.domain is None: params.domain = [] if params.search_domain: params.domain.extend(params.search_domain) if not params.group_by_ctx: params.ids = None from view_graph.widgets import _graph wid = _graph.Graph(model=params.model, view=view, view_id=params.view_id, ids=params.ids, domain=params.domain, view_mode = params.view_mode, context=params.context, group_by = params.group_by_ctx) view=ustr(wid.render()) return dict(view = view)
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)
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 _read_form(self, context, count, domain, filter_domain, id, ids, kw, limit, model, offset, search_data, search_domain, source, view_ids, view_mode, view_type, notebook_tab, o2m_edit=False, editable=False): """ Extract parameters for form reading/creation common to both self.edit and self.view """ params, data = TinyDict.split({ '_terp_model': model, '_terp_id': id, '_terp_ids': ids, '_terp_view_ids': view_ids, '_terp_view_mode': view_mode, '_terp_view_type': view_type, '_terp_source': source, '_terp_domain': domain, '_terp_context': context, '_terp_offset': offset, '_terp_limit': limit, '_terp_count': count, '_terp_search_domain': search_domain, '_terp_search_data': search_data, '_terp_filter_domain': filter_domain, '_terp_notebook_tab': notebook_tab }) params.o2m_edit = o2m_edit params.editable = editable params.action_id = kw.get('action_id') if kw.get('default_date'): params.context.update({'default_date': kw['default_date']}) cherrypy.request._terp_view_target = kw.get('target') if params.view_mode and 'form' not in params.view_mode: params.view_type = params.view_mode[-1] if params.view_type == 'tree': params.view_type = 'form' if not params.ids: params.offset = 0 return params
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 moveDown(self, **kw): params, data = TinyDict.split(kw) id = params.id ids = params.ids or [] if id not in ids or ids.index(id) == len(ids) - 1: return dict() proxy = rpc.RPCProxy(params.model) ctx = rpc.get_session().context.copy() next_id = ids[ids.index(id)+1] try: res = proxy.read([id, next_id], ['sequence'], ctx) records = dict([(r['id'], r['sequence']) for r in res]) cur_seq = records[id] next_seq = records[next_id] if cur_seq == next_seq: proxy.write([next_id], {'sequence': cur_seq + 1}, ctx) proxy.write([id], {'sequence': next_seq}, ctx) else: proxy.write([id], {'sequence': next_seq}, ctx) proxy.write([next_id], {'sequence': cur_seq}, ctx) return dict() except Exception, e: return dict(error=str(e))
def get_validation_schema(self): """Generate validation schema for the given Form instance. Should be used to validate form inputs with @validate decorator. @param self: and instance of Form @returns a new instance of Form with validation schema """ kw = cherrypy.request.params params, data = TinyDict.split(kw) # bypass validations, if saving from button in non-editable view if params.button and not params.editable and params.id: return None cherrypy.request.terp_validators = {} cherrypy.request.terp_data = data params.nodefault = True form = self.create_form(params) cherrypy.request.terp_form = form vals = cherrypy.request.terp_validators keys = vals.keys() for k in keys: if k not in kw: vals.pop(k) form.validator = openobject.validators.Schema(**vals) return form
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): 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"))
def index(self, **kw): params, data = TinyDict.split(kw) id = params.id model = params.model message = None tmp = {} todo = [] if id: res = rpc.session.execute('object', 'execute', model, 'perm_read', [id], rpc.session.context) for line in res: todo = [('id', _('ID')), ('create_uid', _('Creation User')), ('create_date', _('Creation Date')), ('write_uid', _('Latest Modification by')), ('write_date', _('Latest Modification Date')), ('uid', _('Owner')), ('gid', _('Group Owner')), ('level', _('Access Level'))] for (key, val) in todo: if line.get(key) and key in ('create_uid', 'write_uid', 'uid'): line[key] = line[key][1] tmp[key] = ustr(line.get(key) or '/') if not id: message = _("No resource is selected...") return dict(tmp=tmp, todo=todo, message=message)
def imp(self, **kw): params, data = TinyDict.split(kw) ctx = params.context or {} ctx.update(rpc.session.context.copy()) views = {} if params.view_mode and params.view_ids: for i, view in enumerate(params.view_mode): views[view] = params.view_ids[i] headers = [{'string': 'Name', 'name': 'name', 'type': 'char'}] tree = tw.treegrid.TreeGrid('import_fields', model=params.model, headers=headers, url='/impex/get_fields', field_parent='relation', views=views, context=ctx, is_importing=1) tree.show_headers = False return dict(model=params.model, source=params.source, tree=tree, fields=kw.get('fields', {}))
def view(self, model, id, ids=None, view_ids=None, view_mode=['form', 'tree'], source=None, domain=[], context={}, offset=0, limit=20, count=0, search_domain=None, **kw): params, data = TinyDict.split({'_terp_model': model, '_terp_id' : id, '_terp_ids' : ids, '_terp_view_ids' : view_ids, '_terp_view_mode' : view_mode, '_terp_source' : source, '_terp_domain' : domain, '_terp_context' : context, '_terp_offset': offset, '_terp_limit': limit, '_terp_count': count, '_terp_search_domain': search_domain}) params.editable = False params.view_type = 'form' cherrypy.request._terp_view_target = kw.get('target') if params.view_mode and 'form' not in params.view_mode: params.view_type = params.view_mode[-1] if params.view_type == 'tree': params.view_type = 'form' if not params.ids: params.count = 1 params.offset = 0 return self.create(params)
def get_validation_schema(self): kw = cherrypy.request.params params, datas = TinyDict.split(kw) params.state = params.state2 cherrypy.request.terp_validators = {} res = self.execute(params) form = res['form'] buttons = res.get('buttons', []) cherrypy.request.terp_form = form cherrypy.request.terp_buttons = buttons vals = cherrypy.request.terp_validators keys = vals.keys() for k in keys: if k not in kw: vals.pop(k) form.validator = validators.Schema(**vals) return form
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')
def remove(self, **kw): params, data = TinyDict.split(kw) sc_ids = [i['id'] for i in cherrypy.session['terp_shortcuts']] error = None proxy = rpc.RPCProxy(params.model) if params.id: if params.model == 'ir.ui.view_sc' and cherrypy.session.get('terp_shortcuts'): for sc in cherrypy.session.get('terp_shortcuts'): for id in params.id: if id == sc['id']: cherrypy.session['terp_shortcuts'].remove(sc) try: ctx = context_with_concurrency_info(params.context, params.concurrency_info) if isinstance(params.id, list): res = proxy.unlink(params.id, ctx) for i in params.id: params.ids.remove(i) else: res = proxy.unlink([params.id], ctx) params.ids.remove(params.id) if params.model == 'res.request': ids, ids2 = rpc.RPCProxy(params.model).request_get() return dict(res_ids = ids) return dict(ids = params.ids, count = len(params.ids)) except Exception, e: error = ustr(e)
def index(self, **kw): params, data = TinyDict.split(kw) id = params.id model = params.model message = None tmp = {} todo = [] if id: res = rpc.session.execute('object', 'execute', model, 'perm_read', [id], rpc.session.context) for line in res: todo = [ ('id', _('ID')), ('create_uid', _('Creation User')), ('create_date', _('Creation Date')), ('write_uid', _('Latest Modification by')), ('write_date', _('Latest Modification Date')), ('uid', _('Owner')), ('gid', _('Group Owner')), ('level', _('Access Level')) ] for (key,val) in todo: if line.get(key) and key in ('create_uid','write_uid','uid'): line[key] = line[key][1] tmp[key] = ustr(line.get(key) or '/') if not id: message = _("No resource is selected...") return dict(tmp=tmp, todo=todo, message=message)
def import_data(self, csvfile, csvsep, csvdel, csvcode, csvskip, fields=[], **kw): params, data = TinyDict.split(kw) res = None content = csvfile.file.read() input=StringIO.StringIO(content) limit = 0 data = [] if not (csvdel and len(csvdel) == 1): return self.imp(error={'message': _("The CSV delimiter must be a single character")}, **kw) try: for j, line in enumerate(csv.reader(input, quotechar=str(csvdel), delimiter=str(csvsep))): # If the line contains no data, we should skip it. if not line: continue if j == limit: fields = line else: data.append(line) except csv.Error, e: return self.imp( error={ 'message': ustr(e), 'title': _('File Format Error') }, **kw)
def save(self, **kw): params, data = TinyDict.split(kw) deps = False if params.deps: for n, v in params.deps.items(): deps = "%s=%s" % (n, v) break model = params.model field = params.field['name'] value = params.field['value'] click_ok = 1 field = field.split('/')[-1] proxy = rpc.RPCProxy('ir.values') res = proxy.set('default', deps, field, [(model, False)], value, True, False, False, params.you or False, True) return dict(model=params.model, click_ok=click_ok, field=params.field, deps=params.deps2, should_close=True)
def create_form(self, params, tg_errors=None): params.id = params.o2m_id params.model = params.o2m_model params.view_mode = ['form', 'tree'] params.view_type = 'form' #XXX: dirty hack to fix bug #401700 if not params.get('_terp_view_ids'): params['_terp_view_ids'] = [] # to get proper view, first generate form using the view_params vp = params.view_params form = tw.form_view.ViewForm(vp, name="view_form", action="/openo2m/save") cherrypy.request.terp_validators = {} wid = form.screen.widget.get_widgets_by_name(params.o2m)[0] # save view_params for later phazes vp = vp.make_plain('_terp_view_params/') hiddens = map(lambda x: tw.form.Hidden(name=x, default=ustr(vp[x])), vp) params.prefix = params.o2m params.views = wid.view # IE hack, get context from cookies (see o2m.js) o2m_context = {} parent_context = {} try: o2m_context = urllib.unquote(cherrypy.request.cookie['_terp_o2m_context'].value) parent_context = urllib.unquote(cherrypy.request.cookie['_terp_parent_context'].value) cherrypy.request.cookie['_terp_o2m_context']['expires'] = 0 cherrypy.response.cookie['_terp_o2m_context']['expires'] = 0 cherrypy.request.cookie['_terp_parent_context']['expires'] = 0 cherrypy.response.cookie['_terp_parent_context']['expires'] = 0 except: pass params.o2m_context = params.o2m_context or o2m_context params.parent_context = params.parent_context or parent_context ctx = params.context or {} ctx.update(params.parent_context or {}) ctx.update(params.o2m_context or {}) p, ctx = TinyDict.split(ctx) params.context = ctx or {} params.hidden_fields = [tw.form.Hidden(name='_terp_parent_model', default=params.parent_model), tw.form.Hidden(name='_terp_parent_id', default=params.parent_id), tw.form.Hidden(name='_terp_parent_context', default=ustr(params.parent_context)), tw.form.Hidden(name='_terp_o2m', default=params.o2m), tw.form.Hidden(name='_terp_o2m_id', default=params.id or None), tw.form.Hidden(name='_terp_o2m_model', default=params.o2m_model), tw.form.Hidden(name='_terp_o2m_context', default=ustr(params.o2m_context or {})), tw.form.Hidden(name=params.prefix + '/__id', default=params.id or None)] + hiddens form = tw.form_view.ViewForm(params, name="view_form", action="/openo2m/save") form.screen.string = wid.screen.string return form
def get(self, **kw): params, data = TinyDict.split(kw) field = params.field.split('/') prefix = '.'.join(field[:-1]) field = field[-1] pctx = TinyForm(**kw).to_python(safe=True) ctx = pctx.chain_get(prefix) or pctx fields = rpc.RPCProxy(params.model).fields_get(False, rpc.session.context) if field not in fields: return {} text = fields[field].get('string') deps = [] for name, attrs in fields.iteritems(): if attrs.get('change_default'): value = ctx.get(name) if value: deps.append((name, name, value, value)) return dict(text=text, deps=str(deps))
def export_data(self, fname, fields, import_compat=False, export_format='csv', **kw): params, data_index = TinyDict.split(kw) proxy = rpc.RPCProxy(params.model) flds = [] for item in fields: fld = item.replace('/.id','.id') flds.append(fld) if isinstance(fields, basestring): fields = fields.replace('/.id','.id') flds = [fields] ctx = dict((params.context or {}), **rpc.get_session().context) ctx['import_comp'] = bool(int(import_compat)) domain = params.seach_domain or [] ids = params.ids or proxy.search(domain, 0, 0, 0, ctx) result = datas_read(ids, params.model, flds, context=ctx) if result.get('warning'): common.warning(unicode(result.get('warning', False)), _('Export Error')) return False result = result.get('datas',[]) if import_compat: params.fields2 = flds if export_format == 'xls': return export_xls(params.fields2, result) else: return export_csv(params.fields2, result)
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)) params.view_type = 'tree' return self.create(params)
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')
def get_defaults(self, **kw): params, data = TinyDict.split(kw) data = {} ds = tc.utils.parse_datetime(params.starts) de = tc.utils.parse_datetime(params.ends) if 'date_stop' in params.fields: kind = params.fields['date_stop']['kind'] data[params.fields['date_stop']['name']] = format.format_datetime(de.timetuple(), kind) elif 'date_delay' in params.fields: # convert the end time in hours day_length = params.fields['day_length'] tds = time.mktime(ds.timetuple()) tde = time.mktime(de.timetuple()) n = (tde - tds) / (60 * 60) if n > day_length: d = math.floor(n / 24) h = n % 24 n = d * day_length + h data[params.fields['date_delay']['name']] = n kind = params.fields['date_start']['kind'] data[params.fields['date_start']['name']] = format.format_datetime(ds.timetuple(), kind) return data
def get(self, day, mode, **kw): params, data = TinyDict.split(kw) options = TinyDict() options.selected_day = params.selected_day day = time.strptime(day, '%Y-%m-%d') options.year = day[0] options.month = day[1] options.date1 = day options.mode = mode if params.colors: try: options.colors = eval(kw['_terp_colors']) except: pass if params.color_values: options.color_values = ustr(params.color_values).split(',') options.search_domain = params.search_domain or [] options.use_search = params.use_search if params.get('_terp_color_filters'): options.color_filters = params.color_filters params.kalendar = options form = self.create_form(params) return dict( calendar=ustr(form.screen.widget.render()), sidebar=ustr(form.sidebar.render()))
def index(self, **kw): #_terp_model, _terp_field, _terp_deps click_ok = None params, data = TinyDict.split(kw) deps = params.deps return dict(model=params.model, click_ok=click_ok, field=params.field, deps=deps, admin_profile=self.is_admin_profile())
def get(self, day, mode, **kw): params, data = TinyDict.split(kw) options = TinyDict() options.selected_day = params.selected_day day = time.strptime(day, '%Y-%m-%d') options.year = day[0] options.month = day[1] options.date1 = day options.mode = mode if params.colors: try: options.colors = eval(kw['_terp_colors']) except: pass if params.color_values: options.color_values = ustr(params.color_values).split(',') options.search_domain = params.search_domain or [] options.use_search = params.use_search if params.get('_terp_color_filters'): options.color_filters = params.color_filters params.kalendar = options form = self.create_form(params) return dict(calendar=ustr(form.screen.widget.render()), sidebar=ustr(form.sidebar.render()))
def previous_o2m(self, **kw): params, data = TinyDict.split(kw) if params.get('_terp_save_current_id'): ctx = dict((params.context or {}), **rpc.session.context) if params.id: rpc.RPCProxy(params.model).write([params.id], data, ctx) else: id = rpc.RPCProxy(params.model).create(data, ctx) params.ids.append(id) params.count += 1 current = params.chain_get(params.source or '') or params idx = -1 if current.id: # save current record if params.editable: self.save(terp_save_only=True, **kw) idx = current.ids.index(current.id) idx = idx - 1 if idx == len(current.ids): idx = len(current.ids) - 1 if current.ids: current.id = current.ids[idx] return self.create(params)
def export_data(self, fname, fields, export_as="csv", add_names=False, import_compat=False, **kw): params, data = TinyDict.split(kw) proxy = rpc.RPCProxy(params.model) if isinstance(fields, basestring): fields = [fields] ctx = params.context or {} ctx.update(rpc.session.context.copy()) ctx['import_comp'] = import_compat domain = params.seach_domain or [] ids = params.ids or proxy.search(domain, 0, 0, 0, ctx) result = datas_read(ids, params.model, fields, context=ctx) if result.get('warning', False): common.warning(unicode(result.get('warning', False)), _('Export Error!')) return False result = result.get('datas',[]) if import_compat: params.fields2 = fields if export_as == 'xls': try: import xlwt except Exception, e: raise common.warning(_('Please Install xlwt Library.\nTo create spreadsheet files compatible with MS Excel.'), _('Import Error.')) ezxf = xlwt.easyxf fp = StringIO.StringIO() wb = xlwt.Workbook() worksheet = wb.add_sheet('Sheet 1') for col in range(len(params.fields2)): worksheet.write(0, col, ustr(params.fields2[col])) col+1 heading_xf = ezxf('align: wrap yes') for data in range(len(result)): for d in range(len(result[data])): try: result[data][d] = ustr(result[data][d]) except: pass result[data][d] = re.sub("\r", " ", result[data][d]) worksheet.write(data+1, d, result[data][d], heading_xf) worksheet.col(d).width = 8000 d+1 wb.save(fp) fp.seek(0) data = fp.read() return data
def edit(self, model, id=False, type = 'false', ids=None, view_ids=None, view_mode=['form', 'tree'], source=None, domain=[], context={}, offset=0, limit=20, count=0, search_domain=None): params, data = TinyDict.split({'_terp_model': model, '_terp_id' : id, '_terp_ids' : ids, '_terp_view_ids' : view_ids, '_terp_view_mode' : view_mode, '_terp_source' : source, '_terp_domain' : domain, '_terp_context' : context, '_terp_offset': offset, '_terp_limit': limit, '_terp_count': count, '_terp_search_domain': search_domain, '_terp_bi_type': type}) params.editable = True params.view_type = 'form' if params.view_mode and 'form' not in params.view_mode: params.view_type = params.view_mode[-1] if params.view_type == 'tree': params.view_type = 'form' # On New O2M if params.source: current = TinyDict() current.id = False params[params.source] = current return self.create(params)
def eval_domain_and_context(self, **kw): params, data = TinyDict.split(kw) domain = kw.get('_terp_domain', []) context = params.context or {} parent_context = dict(params.parent_context or {}, **rpc.session.context) # filter out default_* and search_default_* from context, # but not when doing a search from the 'search view' (we have to keep parent context) if params.search_mode != 'true': parent_context = self.context_get(params.parent_context) or {} # update active_id in context for links parent_context.update( active_id=params.active_id or False, active_ids=params.active_ids or []) if 'group_by' in parent_context: if isinstance(params.group_by, str): parent_context['group_by'] = cleanup_group_by(params.group_by).split(',') else: parent_context['group_by'] = params.group_by try: ctx = TinyForm(**kw).to_python() pctx = ctx except TinyFormError, e: return dict(error_field=e.field, error=ustr(e))
def get_validation_schema(self): """Generate validation schema for the given Form instance. Should be used to validate form inputs with @validate decorator. @param self: and instance of Form @returns a new instance of Form with validation schema """ kw = cherrypy.request.params params, data = TinyDict.split(kw) # bypass validations, if saving from button in non-editable view if params.button and not params.editable and params.id: return None cherrypy.request.terp_validators = {} cherrypy.request.terp_data = data params.nodefault = True form = self.create_form(params) cherrypy.request.terp_form = form vals = cherrypy.request.terp_validators keys = vals.keys() for k in keys: if k not in kw: vals.pop(k) form.validator = validators.Schema(**vals) return form
def button_action(self, **kw): params, data = TinyDict.split(kw) error = None reload = (params.context or {}).get('reload', False) result = {} name = params.button_name btype = params.button_type ctx = dict((params.context or {}), **rpc.session.context) id = params.id model = params.model id = (id or False) and int(id) ids = (id or []) and [id] list_grid = params.list_grid or '_terp_list' try: if btype == 'workflow': res = rpc.session.execute('object', 'exec_workflow', model, name, id) if isinstance(res, dict): import actions return actions.execute(res, ids=[id]) else: return dict(reload=True, list_grid=list_grid) elif btype == 'object': ctx = params.context or {} ctx.update(rpc.session.context.copy()) if list_grid != '_terp_list': ctx['from_list_grid'] = list_grid res = rpc.session.execute('object', 'execute', model, name, ids, ctx) if isinstance(res, dict): import actions return actions.execute(res, ids=[id]) else: return dict(reload=True, list_grid=list_grid) elif btype == 'action': import actions action_id = int(name) action_type = actions.get_action_type(action_id) if action_type == 'ir.actions.wizard': cherrypy.session['wizard_parent_form'] = '/form' cherrypy.session['wizard_parent_params'] = params res = actions.execute_by_id(action_id, type=action_type, model=model, id=id, ids=ids, context=ctx or {}) if res: return res else: return dict(reload=True, list_grid=list_grid) else: return dict(error = "Unallowed button type") except Exception, e: return dict(error = ustr(e))
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)} if new_id: raise redirect(self.path + '/edit', **args) raise redirect(self.path + '/view', **args)
def save(self, **kw): params, data = TinyDict.split(kw) error = None error_field = None id = params.id or 0 id = (id > 0) and id or 0 ids = params.ids or [] model = params.parent.model if model != params.model and not params.parent.id: error = _("Parent record doesn't exists...") if error: return dict(error=error) try: proxy = rpc.RPCProxy(model) frm = TinyForm(**kw).to_python() data = {} ctx = context_with_concurrency_info(params.parent.context, params.concurrency_info) source = params.source if source and source != '_terp_list': data = frm.chain_get(source) if data is None: return dict(error_field=error_field, error=error, id=id, ids=str([int(i) for i in ids])) if '__id' in data: data.pop('__id') if 'id' in data: data.pop('id') fld = source.split('/')[-1] data = {fld : [(id and 1, id, data.copy())]} proxy.write([params.parent.id], data, ctx) if not id: all_ids = proxy.read([params.parent.id], [fld])[0][fld] new_ids = [i for i in all_ids if i not in ids] ids = all_ids if new_ids: id = new_ids[0] else: data = frm.copy() if 'id' in data: data.pop('id') if id > 0: proxy.write([id], data, ctx) else: id = proxy.create(data, params.parent.context or {}) ids = [id] + ids except TinyFormError, e: error_field = e.field error = ustr(e)
def exp(self, import_compat="1", **kw): params, data = TinyDict.split(kw) ctx = dict((params.context or {}), **rpc.get_session().context) views = {} if params.view_mode and params.view_ids: for i, view in enumerate(params.view_mode): views[view] = params.view_ids[i] exports = rpc.RPCProxy('ir.exports') headers = [{'string' : 'Name', 'name' : 'name', 'type' : 'char'}] tree = treegrid.TreeGrid('export_fields', model=params.model, headers=headers, url=tools.url('/openerp/impex/get_fields'), field_parent='relation', context=ctx, views=views, import_compat=int(import_compat)) tree.show_headers = False existing_exports = exports.read( exports.search([('resource', '=', params.model)], context=ctx), [], ctx) return dict(existing_exports=existing_exports, model=params.model, ids=params.ids, ctx=ctx, search_domain=params.search_domain, source=params.source, tree=tree, import_compat=import_compat)
def get_validation_schema(self): kw = cherrypy.request.params params, datas = TinyDict.split(kw) params.state = params.state2 cherrypy.request.terp_validators = {} res = self.execute(params) form = res["form"] buttons = res.get("buttons", []) cherrypy.request.terp_form = form cherrypy.request.terp_buttons = buttons vals = cherrypy.request.terp_validators keys = vals.keys() for k in keys: if k not in kw: vals.pop(k) form.validator = openobject.validators.Schema(**vals) return form
def get_defaults(self, **kw): params, data = TinyDict.split(kw) data = {} ds = tc.utils.parse_datetime(params.starts) de = tc.utils.parse_datetime(params.ends) if 'date_stop' in params.fields: kind = params.fields['date_stop']['kind'] data[params.fields['date_stop']['name']] = format.format_datetime( de.timetuple(), kind) elif 'date_delay' in params.fields: # convert the end time in hours day_length = params.fields['day_length'] tds = time.mktime(ds.timetuple()) tde = time.mktime(de.timetuple()) n = (tde - tds) / (60 * 60) if n > day_length: d = math.floor(n / 24) h = n % 24 n = d * day_length + h data[params.fields['date_delay']['name']] = n kind = params.fields['date_start']['kind'] data[params.fields['date_start']['name']] = format.format_datetime( ds.timetuple(), kind) return data
def create_form(self, params, tg_errors=None): params.id = params.o2m_id params.model = params.o2m_model params.view_mode = ['form', 'tree'] params.view_type = 'form' #XXX: dirty hack to fix bug #401700 if not params.get('_terp_view_ids'): params['_terp_view_ids'] = [] # to get proper view, first generate form using the view_params vp = params.view_params form = tw.form_view.ViewForm(vp, name="view_form", action="/openerp/openo2m/save") cherrypy.request.terp_validators = {} if '/' in params.o2m: params.o2m = '.'.join(params.o2m.split('/')[-1:]) wid = form.screen.widget.get_widgets_by_name(params.o2m)[0] # save view_params for later phazes vp = vp.make_plain('_terp_view_params/') hiddens = map(lambda x: tw.form.Hidden(name=x, default=ustr(vp[x])), vp) params.prefix = params.o2m params.views = wid.view params.hide_new_button = False ctx = params.context or {} ctx.update(params.parent_context or {}) ctx.update(params.o2m_context or {}) p, ctx = TinyDict.split(ctx) if ctx.get('default_name'): del ctx['default_name'] arch = params.views.get('form', {}).get('arch', False) if arch: dom = xml.dom.minidom.parseString(arch.encode('utf-8')) form_attribute = node_attributes(dom.childNodes[0]) if form_attribute.get('hide_new_button'): params.hide_new_button = expr_eval(form_attribute.get('hide_new_button', False), {'context': ctx}) params.context = ctx or {} params.hidden_fields = [tw.form.Hidden(name='_terp_parent_model', default=params.parent_model), tw.form.Hidden(name='_terp_parent_id', default=params.parent_id), tw.form.Hidden(name='_terp_parent_context', default=ustr(params.parent_context)), tw.form.Hidden(name='_terp_o2m', default=params.o2m), tw.form.Hidden(name='_terp_o2m_id', default=params.id or None), tw.form.Hidden(name='_terp_o2m_model', default=params.o2m_model), tw.form.Hidden(name='_terp_o2m_context', default=ustr(params.o2m_context or {})), tw.form.Hidden(name=params.prefix + '/__id', default=params.id or None)] + hiddens form = tw.form_view.ViewForm(params, name="view_form", action="/openerp/openo2m/save") form.screen.string = wid.screen.string return form
def exp(self, import_compat="0", **kw): params, data = TinyDict.split(kw) ctx = dict((params.context or {}), **rpc.session.context) views = {} if params.view_mode and params.view_ids: for i, view in enumerate(params.view_mode): views[view] = params.view_ids[i] export_format = data.get('export_format', 'excel') all_records = data.get('all_records', '0') if not params.ids: all_records = '1' exports = rpc.RPCProxy('ir.exports') headers = [{'string' : 'Name', 'name' : 'name', 'type' : 'char'}] tree = treegrid.TreeGrid('export_fields', model=params.model, headers=headers, url=tools.url('/openerp/impex/get_fields'), field_parent='relation', context=ctx, views=views, import_compat=int(import_compat)) tree.show_headers = False existing_exports = exports.read( exports.search([('resource', '=', params.model)], context=ctx), [], ctx) default = [] if params._terp_listheaders: default = [x.split(',',1) for x in params._terp_listheaders] elif kw.get('_terp_fields2') and kw.get('fields') and params.fields2: default = [] for i in range(0, len(kw.get('fields'))): if import_compat=='1' and '/' in kw.get('fields')[i] and kw.get('fields')[i].split('/')[-1] not in ('id', '.id'): continue default.append([kw['fields'][i], params.fields2[i]]) export_id = False if '_export_id' in kw and kw['_export_id']: export_id = int(kw['_export_id']) if params.model: proxy = rpc.RPCProxy(params.model) default = proxy.update_exported_fields(default) if params.model == 'product.product': default = [x for x in default if x[0] not in product_remove_fields] default = simplejson.dumps(default) group_by_no_leaf = ctx and ctx.get('group_by_no_leaf', False) if params.search_data and ctx and not ctx.get('group_by') and params.search_data.get('group_by_ctx'): ctx['group_by'] = params.search_data['group_by_ctx'] return dict(existing_exports=existing_exports, model=params.model, ids=params.ids, ctx=ctx, search_domain=params.search_domain, source=params.source, group_by_no_leaf=group_by_no_leaf, tree=tree, import_compat=import_compat, default=default, export_format=export_format, all_records=all_records, export_id=export_id)
def default_error_handler(self, tg_errors=None, **kw): """ Error handler for the given Form instance. @param self: an instance for Form @param tg_errors: errors """ params, data = TinyDict.split(kw) return self.create(params, tg_errors=tg_errors)
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)
def save(self, **kw): params, data = TinyDict.split(kw) error = None error_field = None id = params.id or 0 id = (id > 0) and id or 0 ids = params.ids or [] model = params.parent.model if model != params.model and not params.parent.id: error = _("Parent record doesn't exists...") if error: return dict(error=error) try: proxy = rpc.RPCProxy(model) frm = TinyForm(**kw).to_python() data = {} ctx = context_with_concurrency_info(params.parent.context, params.concurrency_info) source = params.source if source and source != '_terp_list': data = frm.chain_get(source) if '__id' in data: data.pop('__id') if 'id' in data: data.pop('id') fld = source.split('/')[-1] data = {fld: [(id and 1, id, data.copy())]} proxy.write([params.parent.id], data, ctx) if not id: all_ids = proxy.read([params.parent.id], [fld])[0][fld] new_ids = [i for i in all_ids if i not in ids] ids = all_ids if new_ids: id = new_ids[0] else: data = frm.copy() if 'id' in data: data.pop('id') if id > 0: proxy.write([id], data, ctx) else: id = proxy.create(data, params.parent.context or {}) ids = [id] + ids except TinyFormError, e: error_field = e.field error = ustr(e)
def action(self, tg_errors=None, tg_exceptions=None, **kw): if tg_exceptions: raise tg_exceptions params, datas = TinyDict.split(kw) params.datas['form'].update(datas) return self.create(params, tg_errors=tg_errors)
def index(self, **kw): #_terp_model, _terp_field, _terp_deps click_ok = None params, data = TinyDict.split(kw) deps = params.deps return dict(model=params.model, click_ok=click_ok, field=params.field, deps=deps)