def create(self, vals): vals['state'] = 'done' rule = super(AuditRule, self).create(vals) rule.update_rule() if self._register_hook(rule.id): RegistryManager.signal_registry_change(self.env.cr.dbname) return rule
def create(self, cr, user, vals, context=None): if context is None: context = {} if context and context.get('bve'): vals['state'] = 'base' res = super(IrModel, self).create(cr, user, vals, context) if vals.get('state', 'base') == 'bve': vals['state'] = 'manual' # add model in registry self.instanciate(cr, user, vals['model'], context) self.pool.setup_models(cr, partial=(not self.pool.ready)) RegistryManager.signal_registry_change(cr.dbname) # Following commented line (write method) is not working anymore # as in Odoo V9 a new orm constraint is restricting the modification # of the state while updating ir.model # self.write(cr, user, [res], {'state': 'manual'}) q = ("""UPDATE ir_model SET state = 'manual' WHERE id = """ + str(res)) cr.execute(q) return res
def create(self, cr, user, vals, context=None): if context is None: context = {} if context and context.get('bve'): vals['state'] = 'base' res = super(IrModel, self).create(cr, user, vals, context) if vals.get('state', 'base') == 'bve': vals['state'] = 'manual' # add model in registry self.instanciate(cr, user, vals['model'], context) self.pool.setup_models(cr, partial=(not self.pool.ready)) # update database schema # model = self.pool[vals['model']] # ctx = dict( # context, # field_name=vals['name'], # field_state='manual', # select=vals.get('select_level', '0'), # update_custom_fields=True) RegistryManager.signal_registry_change(cr.dbname) self.write(cr, user, [res], {'state': 'manual'}) return res
def create(self, vals): vals['state'] = 'done' rule = super(AuditRule, self).create(vals) rule.update_rule() if self._register_hook(rule.id): RegistryManager.signal_registry_change(self.env.cr.dbname) return rule
def _update_registry(self, cr, uid, context=None): """ Update the registry after a modification on action rules. """ if self.pool.ready: # for the sake of simplicity, simply force the registry to reload cr.commit() openerp.api.Environment.reset() RegistryManager.new(cr.dbname) RegistryManager.signal_registry_change(cr.dbname)
def clear_cache(self, cr): """clear cache and update models. Notify other workers to restart their registry.""" self.precision_get.clear_cache(self) env = openerp.api.Environment(cr, SUPERUSER_ID, {}) for model in self.pool.values(): for field in model._fields.values(): if field.type == 'float': field._setup_digits(env) RegistryManager.signal_registry_change(cr.dbname)
def clear_cache(self, cr): """clear cache and update models. Notify other workers to restart their registry.""" self.precision_get.clear_cache(self) env = openerp.api.Environment(cr, SUPERUSER_ID, {}) for model in self.pool.values(): for field in model._fields.values(): if field.type == 'float': field._setup_digits(env) RegistryManager.signal_registry_change(cr.dbname)
def create(self, cr, user, vals, context=None): if 'model_id' in vals: model_data = self.pool['ir.model'].browse(cr, user, vals['model_id']) vals['model'] = model_data.model if context is None: context = {} if vals.get('ttype', False) == 'selection': if not vals.get('selection', False): raise UserError( _('For selection fields, the Selection Options must be given!' )) self._check_selection(cr, user, vals['selection'], context=context) res = super(HrPerformanceFields, self).create(cr, user, vals, context) if vals.get('state', 'manual') == 'manual': if not vals['name'].startswith('x_'): raise UserError( _("Custom fields must have a name that starts with 'x_' !") ) if vals.get('relation', False) and not self.pool['ir.model'].search( cr, user, [('model', '=', vals['relation'])]): raise UserError( _("Model %s does not exist!") % vals['relation']) if vals.get('ttype', False) == 'one2many': if not self.search(cr, user, [('model_id', '=', vals['relation']), ('name', '=', vals['relation_field']), ('ttype', '=', 'many2one')]): raise UserError( _("Many2one %s on model %s does not exist!") % (vals['relation_field'], vals['relation'])) self.pool.clear_manual_fields() if vals['model'] in self.pool: # setup models; this re-initializes model in registry self.pool.setup_models(cr, partial=(not self.pool.ready)) # update database schema model = self.pool[vals['model']] ctx = dict(context, update_custom_fields=True) model._auto_init(cr, ctx) model._auto_end(cr, ctx) # actually create FKs! RegistryManager.signal_registry_change(cr.dbname) return res
def _update_models(self, models=None): update = False if not models: models = dict([ (checklist.model_id, checklist) for checklist in self.with_context(active_test=True).search([]) ]) for model, checklist in models.iteritems(): if model.model not in self.env.registry.models: continue if checklist: update |= self._patch_model_decoration(model.model) else: update |= self._revert_model_decoration(model.model) if update: if self.pool.ready: RegistryManager.signal_registry_change(self._cr.dbname) self.clear_caches()
def unlink(self, cr, user, ids, context=None): # Prevent manual deletion of module columns if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] if not context.get(MODULE_UNINSTALL_FLAG) and \ any(field.state != 'manual' for field in self.browse(cr, user, ids, context)): raise UserError( _("This column contains module data and cannot be removed!")) self._drop_column(cr, user, ids, context) res = super(HrPerformanceFields, self).unlink(cr, user, ids, context) if not context.get(MODULE_UNINSTALL_FLAG): # The field we just deleted might be inherited, and the registry is # inconsistent in this case; therefore we reload the registry. cr.commit() api.Environment.reset() RegistryManager.new(cr.dbname) RegistryManager.signal_registry_change(cr.dbname) return res
def create(self, vals): if self._context and self._context.get('bve'): vals['state'] = 'base' res = super(IrModel, self).create(vals) # this sql update is necessary since a write method here would # be not working (an orm constraint is restricting the modification # of the state field while updating ir.model) q = ("""UPDATE ir_model SET state = 'manual' WHERE id = """ + str(res.id)) self.env.cr.execute(q) # update registry if self._context.get('bve'): # setup models; this reloads custom models in registry self.pool.setup_models(self._cr, partial=(not self.pool.ready)) # signal that registry has changed RegistryManager.signal_registry_change(self.env.cr.dbname) return res
def action_create(self): def _get_fields_info(fields_data): fields_info = [] for field_data in fields_data: field = self.env['ir.model.fields'].browse(field_data["id"]) vals = { "table": self.env[field.model_id.model]._table, "table_alias": field_data["table_alias"], "select_field": field.name, "as_field": "x_" + field_data["name"], "join": False, "model": field.model_id.model } if field_data.get("join_node"): vals.update({"join": field_data["join_node"]}) fields_info.append(vals) return fields_info def _build_query(): info = _get_fields_info(json.loads(self.data)) fields = [("{}.{}".format(f["table_alias"], f["select_field"]), f["as_field"]) for f in info if 'join_node' not in f] tables = set([(f["table"], f["table_alias"]) for f in info]) join_nodes = [(f["table_alias"], f["join"], f["select_field"]) for f in info if f["join"] is not False] table_name = self.model_name.replace(".", "_") tools.drop_view_if_exists(self.env.cr, table_name) basic_fields = [("t0.id", "id"), ("t0.write_uid", "write_uid"), ("t0.write_date", "write_date"), ("t0.create_uid", "create_uid"), ("t0.create_date", "create_date")] q = """CREATE or REPLACE VIEW %s as ( SELECT %s FROM %s WHERE %s )""" % (table_name, ','.join([ "{} AS {}".format(f[0], f[1]) for f in basic_fields + fields ]), ','.join([ "{} AS {}".format(t[0], t[1]) for t in list(tables) ]), " AND ".join( ["{}.{} = {}.id".format(j[0], j[2], j[1]) for j in join_nodes] + ["TRUE"])) self.env.cr.execute(q) def _prepare_field(field_data): if not field_data["custom"]: field = self.env['ir.model.fields'].browse(field_data["id"]) vals = { "name": "x_" + field_data["name"], "complete_name": field.complete_name, 'model': self.model_name, 'relation': field.relation, "field_description": field_data.get("description", field.field_description), "ttype": field.ttype, "selection": field.selection, "size": field.size, 'state': "manual" } if field.ttype == 'selection' and not field.selection: model_obj = self.env[field.model_id.model] selection = model_obj._columns[field.name].selection selection_domain = str(selection) vals.update({"selection": selection_domain}) return vals def _prepare_object(): return { 'name': self.name, 'model': self.model_name, 'field_id': [(0, 0, _prepare_field(field)) for field in json.loads(self.data) if 'join_node' not in field] } def _build_object(): res_id = self.env['ir.model'].sudo().create(_prepare_object()) return res_id # read access def group_ids_with_access(model_name, access_mode): self.env.cr.execute( '''SELECT g.id FROM ir_model_access a JOIN ir_model m ON (a.model_id=m.id) JOIN res_groups g ON (a.group_id=g.id) LEFT JOIN ir_module_category c ON (c.id=g.category_id) WHERE m.model=%s AND a.active IS True AND a.perm_''' + access_mode, (model_name, )) return [x[0] for x in self.env.cr.fetchall()] def _build_access_rules(obj): info = json.loads(self.data) models = list(set([f["model"] for f in info])) read_groups = set.intersection(*[ set(group_ids_with_access(model, 'read')) for model in models ]) for group in read_groups: self.env['ir.model.access'].sudo().create({ 'name': 'read access to ' + self.model_name, 'model_id': obj.id, 'group_id': group, 'perm_read': True, }) # edit access for group in self.group_ids: self.env['ir.model.access'].sudo().create({ 'name': 'read access to ' + self.model_name, 'model_id': obj.id, 'group_id': group.id, 'perm_read': True, 'perm_write': True, }) return self.model_name = "x_bve." + ''.join([ x for x in self.name.lower() if x.isalnum() ]).replace("_", ".").replace(" ", ".") _build_query() obj = _build_object() _build_access_rules(obj) self.env.cr.commit() from openerp.modules.registry import RegistryManager self.env.registry = RegistryManager.new(self.env.cr.dbname) RegistryManager.signal_registry_change(self.env.cr.dbname) self.pool = self.env.registry view_id = self.pool.get('ir.ui.view').create( self.env.cr, SUPERUSER_ID, { 'name': "Analysis", 'type': 'graph', 'model': self.model_name, 'priority': 16, 'arch': """<?xml version="1.0"?> <graph string="Analysis" type="pivot" stacked="True"> {} </graph> """.format("".join(self._create_graph_view())) }, context={}) view_ids = [view_id] action_vals = { 'name': self.name, 'res_model': self.model_name, 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'graph', 'view_id': view_ids and view_ids[0] or 0, 'context': "{'service_name': '%s'}" % self.name, } act_window = self.env['ir.actions.act_window'] action_id = act_window.sudo().create(action_vals) self.write({ 'action_id': action_id.id, 'view_id': view_id, 'state': 'created' }) return True
def clear_cache(self, cr): """clear cache and update models. Notify other workers to restart their registry.""" self.precision_get.clear_cache(self) RegistryManager.signal_registry_change(cr.dbname)
def write(self, cr, user, ids, vals, context=None): if context is None: context = {} #For the moment renaming a sparse field or changing the storing system is not allowed. This may be done later if 'serialization_field_id' in vals or 'name' in vals: for field in self.browse(cr, user, ids, context=context): if 'serialization_field_id' in vals and field.serialization_field_id.id != vals[ 'serialization_field_id']: raise UserError( _('Changing the storing system for field "%s" is not allowed.' ) % field.name) if field.serialization_field_id and (field.name != vals['name']): raise UserError( _('Renaming sparse field "%s" is not allowed') % field.name) # if set, *one* column can be renamed here column_rename = None # names of the models to patch patched_models = set() if vals and ids: # check selection if given if vals.get('selection'): self._check_selection(cr, user, vals['selection'], context=context) for item in self.browse(cr, user, ids, context=context): if item.state != 'manual': raise UserError( _('Properties of base fields cannot be altered in this manner! ' 'Please modify them through Python code, ' 'preferably through a custom addon!')) if vals.get('model_id', item.model_id.id) != item.model_id.id: raise UserError( _("Changing the model of a field is forbidden!")) if vals.get('ttype', item.ttype) != item.ttype: raise UserError( _("Changing the type of a field is not yet supported. " "Please drop it and create it again!")) obj = self.pool.get(item.model) field = getattr(obj, '_fields', {}).get(item.name) if vals.get('name', item.name) != item.name: # We need to rename the column if column_rename: raise UserError( _('Can only rename one field at a time!')) if vals['name'] in obj._fields: raise UserError( _('Cannot rename field to %s, because that field already exists!' ) % vals['name']) if vals.get( 'state', 'manual' ) == 'manual' and not vals['name'].startswith('x_'): raise UserError( _('New field name must still start with x_ , because it is a custom field!' )) if '\'' in vals['name'] or '"' in vals[ 'name'] or ';' in vals['name']: raise ValueError('Invalid character in column name') column_rename = (obj._table, item.name, vals['name'], item.index) # We don't check the 'state', because it might come from the context # (thus be set for multiple fields) and will be ignored anyway. if obj is not None and field is not None: patched_models.add(obj._name) # These shall never be written (modified) for column_name in ('model_id', 'model', 'state'): if column_name in vals: del vals[column_name] res = super(HrPerformanceFields, self).write(cr, user, ids, vals, context=context) self.pool.clear_manual_fields() if column_rename: # rename column in database, and its corresponding index if present table, oldname, newname, index = column_rename cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (table, oldname, newname)) if index: cr.execute( 'ALTER INDEX "%s_%s_index" RENAME TO "%s_%s_index"' % (table, oldname, table, newname)) if column_rename or patched_models: # setup models, this will reload all manual fields in registry self.pool.setup_models(cr, partial=(not self.pool.ready)) if patched_models: # update the database schema of the models to patch ctx = dict(context, update_custom_fields=True) for model_name in patched_models: obj = self.pool[model_name] obj._auto_init(cr, ctx) obj._auto_end(cr, ctx) # actually create FKs! if column_rename or patched_models: RegistryManager.signal_registry_change(cr.dbname) return res
def write(self, vals): res = super(AuditRule, self).write(vals) self.update_rule() if self._register_hook(self._ids): RegistryManager.signal_registry_change(self.env.cr.dbname) return res
def write(self, vals): res = super(AuditRule, self).write(vals) self.update_rule() if self._register_hook(self._ids): RegistryManager.signal_registry_change(self.env.cr.dbname) return res
def write(self, vals): res = super(AccountDaysOverdue, self).write(vals) if self.pool['account.move.line']._register_hook(self.env.cr): RegistryManager.signal_registry_change( self.env.cr.dbname) return res