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 create(self, saved=False): tg_errors = None proxy = rpc.RPCProxy('res.users') action_id = proxy.action_get({}) action = rpc.RPCProxy('ir.actions.act_window').read([action_id], False, rpc.get_session().context)[0] view_ids=[] if action.get('views', []): view_ids=[x[0] for x in action['views']] elif action.get('view_id', False): view_ids=[action['view_id'][0]] params = TinyDict() params.id = rpc.get_session().uid params.ids = [params.id] params.model = 'res.users' params.view_type = 'form' params.view_mode = ['form'] params.view_ids = view_ids params.string = _('Preferences') params.editable = True form = self.create_form(params, tg_errors) return dict(form=form, params=params, editable=True, saved=saved)
def create(self, saved=False): tg_errors = None proxy = rpc.RPCProxy("res.users") action_id = proxy.action_get({}) action = rpc.RPCProxy("ir.actions.act_window").read([action_id], False, rpc.session.context)[0] view_ids = [] if action.get("views", []): view_ids = [x[0] for x in action["views"]] elif action.get("view_id", False): view_ids = [action["view_id"][0]] params = TinyDict() params.id = rpc.session.uid params.ids = [params.id] params.model = "res.users" params.view_type = "form" params.view_mode = ["form"] params.view_ids = view_ids params.string = _("Preferences") params.editable = True form = self.create_form(params, tg_errors) return dict(form=form, params=params, editable=True, saved=saved)
def mini(self, year, month, forweek=False): params = TinyDict() params.year = year params.month = month params.forweek = forweek day = tc.utils.Day(params.year, params.month, 1) minical = tc.widgets.MiniCalendar(day, forweek=params.forweek, highlight=False) return minical.render()
def index(self, model, active=False): params = TinyDict() params.model = 'workflow' params.view_mode = ['tree'] params.domain = [('osv', '=', model)] screen = tw.screen.Screen(params, selectable=1) screen.widget.pageable = False return dict(screen=screen, model=model, active=active)
def index(self, model): params = TinyDict() params.model = 'ir.ui.view' params.view_mode = ['tree'] params.domain = [('model', '=', model)] screen = tw.screen.Screen(params, selectable=1) screen.widget.pageable = False return dict(screen=screen, model=model)
def edit(self, model=None, id=False, **kw): params = TinyDict() params.model = model params.id = id id = params.id if not id: res = rpc.RPCProxy('ir.model').search([('model', '=', params.model)]) id = (res or False) and res[0] return super(NewModel, self).edit(model='ir.model', id=id)
def execute_wizard(name, **datas): """Executes given wizard with the given data @param name: name of the wizard @param datas: datas @return: wizard view (mostly XHTML code) """ params = TinyDict() params.name = name params.datas = datas params.state = 'init' return Wizard().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 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 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) 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 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 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 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 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_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 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 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 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 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 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 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 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 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_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 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 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 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 action(self, **kw): params, data = TinyDict.split(kw) context_menu = kw.get('context_menu') or False 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 {} action = {} if data.get('datas'): action = eval(data.get('datas')) type = action.get('type') act_id = params.action 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'], context)['type'] tmp_ctx = dict(context) if action_type == 'ir.actions.report.xml': # avoid reading large binary values that we won't even care about tmp_ctx['bin_size'] = True action = rpc.session.execute('object', 'execute', action_type, 'read', act_id, False, tmp_ctx) if domain: if isinstance(domain, basestring): domain = eval(domain) domain.extend(expr_eval(action.get('domain', '[]'), context)) action['domain'] = ustr(domain) if context.get('search_view'): context.pop('search_view') action['form_context'] = context or {} import actions return actions.execute(action, model=params.model, id=id, ids=ids, report_type='pdf', context_menu=context_menu)
def save(self, translate='fields', **kw): params, data = TinyDict.split(kw) ctx = dict((params.context or {}), **rpc.session.context) 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)
def action(self, **kw): params, data = TinyDict.split(kw) action = params.data if not action: return self.do_action('tree_but_action', datas=kw) from openerp.controllers import actions ids = params.selection or [] id = (ids or False) and ids[0] return actions.execute(action, model=params.model, id=id, ids=ids, report_type='pdf')
def _make_record(self, parent=None): parent = parent or self for wid in parent.iter_member_widgets(): if isinstance(wid, TinyInputWidget ) and wid.name and not wid.name.endswith('/'): self[wid.name] = wid.get_value() elif isinstance(wid, TinyWidget) and len(wid.member_widgets): self._make_record(wid) params, data = TinyDict.split(self) return data
def duplicate(self, **kw): params, data = TinyDict.split(kw) id = params.id ctx = params.context model = params.model proxy = rpc.RPCProxy(model) try: new_id = proxy.copy(id, {}, ctx) except Exception: pass return dict(id=new_id)
def get_matched(self, model, text, limit=10, **kw): params, data = TinyDict.split(kw) ctx = dict(rpc.session.context, **(params.context or {})) try: return { 'values': rpc.RPCProxy(model).name_search(text, (params.domain or []), 'ilike', ctx, int(limit)), 'error': None } except Exception, e: return {'error': ustr(e), 'values': False}
def save_binary_data(self, _fname='file.dat', **kw): params, data = TinyDict.split(kw) cherrypy.response.headers[ 'Content-Disposition'] = 'filename="%s"' % _fname if params.datas: form = params.datas['form'] res = form.get(params.field) return base64.decodestring(res) proxy = rpc.RPCProxy(params.model) res = proxy.read([params.id], [params.field], rpc.session.context) return base64.decodestring(res[0][params.field])
def save(self, datas, **kwargs): params, data = TinyDict.split(cherrypy.session['params']) ctx = dict(rpc.session.context, default_res_model=params.model, default_res_id=params.id, active_id=False, active_ids=[]) attachment_id = rpc.RPCProxy('ir.attachment').create( { 'name': datas.filename, 'datas': base64.encodestring(datas.file.read()), 'datas_fname': datas.filename, }, ctx) return {'id': attachment_id, 'name': datas.filename}
def multiple_groupby(self, model, name, grp_domain, group_by, view_id, view_type, parent_group, group_level, groups, no_leaf, **kw): grp_domain = ast.literal_eval(grp_domain) view = cache.fields_view_get(model, view_id, view_type, rpc.session.context.copy()) group_by = ast.literal_eval(group_by) domain = grp_domain group_level = ast.literal_eval(group_level) groups = ast.literal_eval(groups) # build a new TinyDict to correctly handle _terp_* params params = TinyDict(**kw) editable = params.editable selectable = params.selectable or 2 context = params.context or {} context.update({ 'group_by_no_leaf': int(no_leaf), 'group_by': group_by, '__domain': domain }) # we force offset to 0, as in group_by mode only 'limit' have an effect # (offset pagination in only for base grouping - which is handled by ListGroup) offset = 0 limit = params.limit or 20 args = { 'editable': editable, 'view_mode': ['tree', 'form', 'calendar', 'graph'], 'nolinks': 1, 'group_by_ctx': group_by, 'selectable': selectable, 'multiple_group_by': True, 'sort_key': kw.get('sort_key'), 'offset': offset, 'limit': limit, 'sort_order': kw.get('sort_order') } listgrp = listgroup.MultipleGroup(name, model, view, ids=None, domain=domain, parent_group=parent_group, group_level=group_level, groups=groups, context=context, **args) return listgrp.render()
def switch_o2m(self, **kw): params, data = TinyDict.split(kw) current = params.chain_get(params.source or '') or params current.view_type = params.source_view_type current.ids = current.ids or [] if not current.id and current.ids: current.id = current.ids[0] try: frm = self.create_form(params) wid = frm.screen.get_widgets_by_name(params.source)[0] except Exception, e: return 'ERROR: ' + str(e)
def delete(self, **kw): params, data = TinyDict.split(kw) error = None ctx = rpc.session.context.copy() ctx.update(params.context or {}) ctx = context_with_concurrency_info(ctx, params.concurrency_info) proxy = rpc.RPCProxy(params.model) try: proxy.unlink([params.id], ctx) except Exception, e: error = ustr(e)
def default(self, id, model, view_id, domain, context): params = TinyDict() try: view_id = int(view_id) except: view_id = False params.ids = id params.view_ids = [view_id] params.model = model params.domain = domain params.context = context or {} return self.create(params)
def link(self, pad_name): params, data = TinyDict.split(cherrypy.session['params']) ctx = dict(rpc.session.context, default_res_model=params.model, default_res_id=params.id, active_id=False, active_ids=[]) pad_name = pad_name.decode('utf8') pad_link = self.make_url(pad_name) attachment_id = rpc.RPCProxy('ir.attachment').create( { 'name': pad_name, 'url': pad_link, 'type': 'url' }, ctx) return {'id': attachment_id, 'name': pad_name, 'url': pad_link}
def gantt_reorder(self, **kw): params, data = TinyDict.split(kw) id = params.id ids = params.ids or [] model = params.model level = params.level level_value = params.level_value fields = cache.fields_get(model, [], rpc.session.context) proxy = rpc.RPCProxy(model) if id and level and level_value: try: proxy.write([id], {level['link']: level_value}) except Exception, e: return dict(error=ustr(e))
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 save(self, **kw): params, data = TinyDict.split(kw) data = {} ds = tc.utils.parse_datetime(params.starts) de = tc.utils.parse_datetime(params.ends) data[params.fields['date_start']['name']] = format.parse_datetime( ds.timetuple()) if 'date_stop' in params.fields: data[params.fields['date_stop']['name']] = format.parse_datetime( de.timetuple()) 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 ctx = rpc.session.context.copy() ctx.update(params.context or {}) ctx = tools.context_with_concurrency_info(ctx, params.concurrency_info) error = None info = {} proxy = rpc.RPCProxy(params.model) try: res = proxy.write([params.id], data, ctx) info = proxy.read([params.id], ['__last_update'])[0]['__last_update'] info = {'%s,%s' % (params.model, params.id): info} except Exception, e: error = ustr(e)
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)
def save(self, terp_save_only=False, **kw): params, data = TinyDict.split(kw) # remember the current page (tab) of notebooks cherrypy.session['remember_notebooks'] = True # 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) params.ids = (params.ids or []) + [int(id)] params.id = int(id) params.count += 1 else: ctx = tools.context_with_concurrency_info( params.context, params.concurrency_info) id = proxy.write([params.id], data, ctx) current = params.chain_get(params.source or '') button = (params.button or False) and True params.load_counter = 1 if current and current.id and not button: params.load_counter = 2 # perform button action if params.button: res = self.button_action(params) if res: return res if current: current.id = None if not params.id: params.id = int(id) elif not button: params.editable = False if not current and not button: params.load_counter = 2 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) parent_context = self.context_get(params.parent_context) or {} if 'group_by' in parent_context: if isinstance(params.group_by, str): parent_context['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 remove(self, **kw): params, data = TinyDict.split(kw) error = None proxy = rpc.RPCProxy(params.model) if params.ids: try: ctx = tools.context_with_concurrency_info( params.context, params.concurrency_info) if isinstance(params.ids, list): res = proxy.unlink(params.ids, ctx) else: res = proxy.unlink([params.ids], ctx) if params.model == 'res.request': ids, ids2 = rpc.RPCProxy(params.model).request_get() cherrypy.session['terp_requests'] = (ids, ids2) return dict(msg=_('%s request(s)') % len(ids)) except Exception, e: error = ustr(e)
def namelist(self, **kw): params, data = TinyDict.split(kw) ctx = dict((params.context or {}), **rpc.session.context) 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 = [(f['name'], res.get(f['name'])) for f in fields] return dict(name_list=name_list)
def exp(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): if params.view_ids[i]: views[view] = params.view_ids[i] proxy = rpc.RPCProxy('ir.exports') new_list = [] headers = [{'string': 'Name', 'name': 'name', 'type': 'char'}] tree = tw.treegrid.TreeGrid('export_fields', model=params.model, headers=headers, url='/impex/get_fields', field_parent='relation', context=ctx, views=views) tree.show_headers = False view = proxy.fields_view_get(False, 'tree', ctx) new_list = tw.listgrid.List(name='_terp_list', model='ir.exports', view=view, ids=None, domain=[('resource', '=', params.model)], context=ctx, selectable=1, editable=False, pageable=False) return dict(new_list=new_list, model=params.model, ids=params.ids, ctx=ctx, search_domain=params.search_domain, source=params.source, tree=tree)
def change_default_get(self, **kw): params, data = TinyDict.split(kw) ctx = rpc.session.context.copy() ctx.update(params.context or {}) model = params.model field = params.caller.split('/')[-1] value = params.value or False proxy = rpc.RPCProxy('ir.values') values = proxy.get('default', '%s=%s' % (field, value), [(model, False)], False, ctx) data = {} for index, fname, value in values: data[fname] = value return dict(value=data)
def action_submenu(self, **kw): params, data = TinyDict.split(kw) import actions act_id = rpc.session.execute('object', 'execute', 'ir.model.data', 'search', [('name', '=', params.action_id)]) res_model = rpc.session.execute('object', 'execute', 'ir.model.data', 'read', act_id, ['res_id']) res = rpc.session.execute('object', 'execute', 'ir.actions.act_window', 'read', res_model[0]['res_id'], False) if res: return actions.execute(res, model=params.model, id=params.id, context=rpc.session.context.copy())
def get(self, **kw): params, data = TinyDict.split(kw) error = None error_field = None model = params.model record = kw.get('record') record = eval(record) proxy = rpc.RPCProxy(model) data = {} res = proxy.fields_get(False, rpc.session.context) all_values = {} errors = [] for k, v in record.items(): values = {} for key, val in v.items(): for field in val: fld = { 'value': val[field], 'type': res[field].get('type') } if fld['type'] == 'many2many': fld['type'] = 'char' datas = {field: fld} try: TinyForm(**datas).to_python() except TinyFormError, e: errors.append({e.field: ustr(e)}) except Exception, e: errors.append({field: ustr(e)}) datas['rec'] = field datas['rec_val'] = fld['value'] datas['type'] = fld['type'] values[key] = datas
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 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 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!"))
def action(self, **kw): params, data = TinyDict.split(kw) button = TinyDict() button.model = params.model button.id = params.id button.name = params.action button.btype = params.kind params.button = button fobj = form.Form() error = "" try: res = fobj.button_action(params) except Exception, e: error = str(e)
def get(self, **kw): params, data = TinyDict.split(kw) params.ids = None source = (params.source or '') and str(params.source) params.view_type = 'form' if source == '_terp_list': params.view_type = 'tree' if params.search_domain: params.domain += params.search_domain # default_get context current = params.chain_get(source) if current and params.source_default_get: current.context = current.context or {} current.context.update(params.source_default_get) if params.wiz_id: res = wizard.Wizard().execute(params) frm = res['form'] else: frm = form.Form().create_form(params) wid = frm.screen.get_widgets_by_name(source, kind=tw.listgrid.List)[0] ids = wid.ids count = wid.count if params.edit_inline: wid.edit_inline = params.edit_inline info = {} if params.concurrency_info: for m, v in getattr(cherrypy.request, 'terp_concurrency_info', {}).items(): for i, d in v.items(): info['%s,%s' % (m, i)] = d return dict(ids=ids, count=count, view=ustr(wid.render()), info=info)