def create(self, cr, user, vals, context=None): if 'model_id' in vals: model_data = self.pool.get('ir.model').browse(cr, user, vals['model_id']) vals['model'] = model_data.model if context is None: context = {} if context and context.get('manual',False): vals['state'] = 'manual' if vals.get('ttype', False) == 'selection': if not vals.get('selection',False): raise except_orm(_('Error'), _('For selection fields, the Selection Options must be given!')) self._check_selection(cr, user, vals['selection'], context=context) res = super(ir_model_fields,self).create(cr, user, vals, context) try: if vals.get('state','base') == 'manual': if not vals['name'].startswith('x_'): raise except_orm(_('Error'), _("Custom fields must have a name that starts with 'x_' !")) if vals.get('relation',False) and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['relation'])]): raise except_orm(_('Error'), _("Model %s does not exist!") % vals['relation']) if self.pool.get(vals['model']): self.pool.get(vals['model']).__init__(self.pool, cr) #Added context to _auto_init for special treatment to custom field for select_level ctx = context.copy() ctx.update({'field_name':vals['name'],'field_state':'manual','select':vals.get('select_level','0'),'update_custom_fields':True}) self.pool.get(vals['model'])._auto_init(cr, ctx) except Exception, e: # we have to behave like _validate() and never let the dirty data in the db. cr.rollback() raise
def _call_completed(self, cr, uid, data, context): debug(data) if data["form"]["user_id"] == uid and not data["form"]["call_summary"]: raise except_orm("Incomplete", "Please Provide Call Summary") if data["form"]["allocated_user_group_id"] and data["form"]["allocated_user_id"]: raise except_orm("Call Error!", "Both UserGroup And User Cannot Be Selected") if data["form"]["user_id"] != uid: if data["form"]["allocated_user_group_id"]: raise except_orm("Warning", "You Cannot Select the Group") data["form"]["allocated_user_id"] = data["form"]["user_id"] else: if not data["form"]["allocated_user_group_id"] and not data["form"]["allocated_user_id"]: raise except_orm("Call Error!", "Only one can be selected") person = pooler.get_pool(cr.dbname).get("cmc.person").browse(cr, uid, int(data["ids"][0])) user = pooler.get_pool(cr.dbname).get("res.users").browse(cr, uid, uid) data["form"]["call_date_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") data["form"]["call_person_type"] = "agent" data["form"]["state"] = "closed" if not data["form"]["client_id"]: data["form"]["calling_about"] = "Self" else: cr.execute("select display_name from cmc_person where id=%d" % (data["form"]["client_id"])) d = cr.fetchone() data["form"]["calling_about"] = d[0] call_id = ( pooler.get_pool(cr.dbname) .get("cmc.call.history") .create(cr, uid, data["form"], {"wizard": True, "person": person, "user": user}) ) return {}
def check_constraints(self, cr, uid, ids, context=None): # _constraints are too slow if isinstance(ids, (int, long)): ids = [ids] for line in self.browse(cr, uid, ids, context): if line.depreciation_date < line.asset_id.purchase_date: raise orm.except_orm( _('Error'), _('Depreciation date must be after purchase date!')) if line.depreciation_type == 'exceptional': cr.execute( "SELECT id FROM account_period WHERE state='draft' AND date_start <= %s AND date_stop >= %s AND company_id = %s", (line.depreciation_date, line.depreciation_date, line.company_id.id)) res = cr.fetchall() if not res: raise orm.except_orm( _('Error'), _('Depreciation date must be in current fiscal year!')) if line.depreciation_value > line.asset_id.purchase_value: raise orm.except_orm( _('Error'), _('Depreciation value cannot be bigger than gross value!')) if line.book_value > line.book_value_wo_exceptional: raise orm.except_orm( _('Error'), _('Book value with exceptional depreciations cannot be superior to book value ' 'without exceptional depreciations, nor inferior to salvage value!' )) return True
def _save(self, cr, uid, data, context): debug("<<<SAVE ACTION WIZARD>>") debug(data) debug(context) if not data['form']['enquiry_details']: raise except_orm('Warning','Please Provide Action Details') debug(context.get('from')) if context.get('from',False) == 'call history': en = pooler.get_pool(cr.dbname).get('cmc.call.history').browse(cr, uid, int(data['id'])) person=en.person_id debug('CHECKSD') else: id_id=int(data['id']) person = pooler.get_pool(cr.dbname).get('cmc.person').browse(cr, uid, id_id) if data['form']['allocated_user_id'] and data['form']['allocated_user_group_id']: raise except_orm('Warning','Please Select One Allocation') user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid) data['form']['state'] = 'pending' data['form']['person_id']=person.id debug(data['form']['person_id']) if data['form']['allocated_user_id'] == uid: data['form']['allocated_user_id']=data['form']['user_id'] enquiry_id = pooler.get_pool(cr.dbname).get('cmc.enquiry').create(cr, uid, data['form']) return data['form']
def _render_tab(self, cr, uid, export_file, template_part, localdict): """Render the output of this template in a tabular format""" template = [] try: delimiter = eval(export_file.delimiter) except TypeError: delimiter = export_file.delimiter # Header & Footer if getattr(export_file, template_part): template.append(self._render(cr, uid, export_file, template_part, localdict)) # Header with fieldnames if template_part == 'header' and export_file.fieldnames_in_header: template.append(delimiter.join((tools.ustr(column.name) for column in export_file.column_ids))) if export_file.extension == 'xls': _render_func = _render_data else: _render_func = _render_unicode # Body if template_part == 'body': sub_objects = localdict['object'] if export_file.refer_to_underlying_object: sub_objects = eval(export_file.records, localdict) if not isinstance(sub_objects, list): sub_objects = [sub_objects] for index, sub_object in enumerate(sub_objects): localdict['line_number'] = index + 1 localdict['object'] = sub_object line = [] for column in export_file.column_ids: try: column_value = _render_func(column.value or '', localdict) if column.default_value and not column_value: column_value = _render_func(column.default_value, localdict) if column.column_validator: validation = eval(column.column_validator, localdict) if not validation: try: exception_msg = _render_unicode(column.exception_msg, localdict) except Exception: exception_msg = column.exception_msg raise except_orm(_('Error'), exception_msg) column_value = tools.ustr(column_value) if column_value: if column.min_width: column_value = getattr(column_value, column.justify)(column.min_width, tools.ustr(column.fillchar)) if column.max_width: column_value = column_value[:column.max_width] if not column.not_string and export_file.extension != 'xls' and export_file.quotechar: try: quotechar = export_file.quotechar and eval(export_file.quotechar) or '' except TypeError: quotechar = export_file.quotechar column_value = '%(quotechar)s%(column_value)s%(quotechar)s' % { 'column_value': quotechar and column_value.replace(quotechar, "\\" + quotechar) or column_value, 'quotechar': quotechar, } line.append(column_value) except Exception, e: raise except_orm(_('Error'), 'column %s: %s' % (column.name, e)) template.append(delimiter.join(line))
def state_update(self, cr, uid, ids, newstate, states_to_update, context={}, level=100): if level<1: raise orm.except_orm(_('Error'), _('Recursion error in modules dependencies !')) demo = False for module in self.browse(cr, uid, ids): mdemo = False for dep in module.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _("You try to install the module '%s' that depends on the module:'%s'.\nBut this module is not available in your system.") % (module.name, dep.name,)) ids2 = self.search(cr, uid, [('name','=',dep.name)]) if dep.state != newstate: mdemo = self.state_update(cr, uid, ids2, newstate, states_to_update, context, level-1,) or mdemo else: od = self.browse(cr, uid, ids2)[0] mdemo = od.demo or mdemo for web_mod in module.web_dependencies_id: if web_mod.state == 'unknown': raise orm.except_orm(_('Error'), _("You try to install the module '%s' that depends on the module:'%s'.\nBut this module is not available in your system.") % (module.name, dep.name,)) ids2 = self.pool.get('ir.module.web').search(cr, uid, [('module','=',web_mod.name)]) self.pool.get('ir.module.web').button_install(cr, uid, ids2) terp = self.get_module_info(module.name) try: self._check_external_dependencies(terp) except Exception, e: raise orm.except_orm(_('Error'), _('Unable %s the module "%s" because an external dependencie is not met: %s' % (newstate, module.name, e.args[0]))) if not module.dependencies_id: mdemo = module.demo if module.state in states_to_update: self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo}) demo = demo or mdemo
def _get_move_line_vals(self, cr, uid, taxes, amount_excl_tax, journal_type, default=None, context=None): lines = [] for tax_info in self.compute_all(cr, uid, taxes, amount_excl_tax, 1.0)['taxes']: if tax_info['amount']: tax_line_vals = (default or {}).copy() tax_line_vals.update({ 'tax_code_id': tax_info['tax_code_id'], 'tax_amount': tax_info['amount'] * tax_info['_refund' in journal_type and 'ref_base_sign' or 'base_sign'], }) debit, credit = 0.0, tax_info['amount'] if tax_info['amount'] < 0.0: debit, credit = abs(credit), abs(debit) if journal_type in ('purchase_refund', 'sale'): if not tax_info['account_collected_id']: raise orm.except_orm(_('Error'), _('Please indicate a collected tax account for %s!') % tax_info['name']) tax_line_vals.update({ 'account_id': tax_info['account_collected_id'], 'debit': debit, 'credit': credit, }) elif journal_type in ('purchase', 'sale_refund'): if not tax_info['account_paid_id']: raise orm.except_orm(_('Error'), _('Please indicate a paid tax account for %s!') % tax_info['name']) tax_line_vals.update({ 'account_id': tax_info['account_paid_id'], 'debit': credit, 'credit': debit, }) lines.append(tax_line_vals) return lines
def _save(self,cr,uid,data,context): if data['form']['user_id'] == uid and not data['form']['call_summary']: raise except_orm('Incomplete','Please Provide Call Summary') if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Both UserGroup And User Cannot Be Selected') if data['form']['user_id'] != uid : if data['form']['allocated_user_group_id'] : raise except_orm('Warning','You Cannot Select the Group') data['form']['allocated_user_id']=data['form']['user_id'] else: if not data['form']['allocated_user_group_id'] and not data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Only one can be selected') person= pooler.get_pool(cr.dbname).get('cmc.person').browse(cr, uid,int(data['ids'][0])) user= pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid,uid) data['form']['call_date_time'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S') data['form']['call_person_type'] = 'agent' data['form']['state'] = 'allocated' if not data['form']['client_id']: data['form']['calling_about']='Self' else: cr.execute('select display_name from cmc_person where id=%d' %(data['form']['client_id'])) d=cr.fetchone() data['form']['calling_about']=d[0] call_id = pooler.get_pool(cr.dbname).get('cmc.call.history').create(cr, uid, data['form'], {'wizard':True, 'person': person, 'user':user}) return {}
def _check_history_lines(self, cr, uid, ids, context=None): """ Constrain fucntion to prohibit user from making teo operation at a time and prohibit user to make any operation on zero value asset. @return: True or raise message """ for hst in self.browse(cr, uid, ids, context=context): intial = self.search(cr, uid, [('asset_id', '=', hst.asset_id.id), ('type', '=', 'initial'), ('id', '!=', hst.id)], context=context) if hst.type == 'initial': if intial: raise orm.except_orm( _('Warrning'), _('Sorry the Intial value has already been intered you can not repeat this process!' )) return True else: msg=not intial and 'Sorry no intial value for this asset please set it first to complate this process !' or \ self.search(cr, uid, [('asset_id','=',hst.asset_id.id),('state','=','draft'),('id','!=',hst.id)], context=context) and\ hst.state not in ('reversed','posted') and 'Sorry you need to post draft prosess first to complate this process !' or\ hst.asset_id.purchase_value==0.0 and hst.asset_id.value_residual==0.0 and \ 'Sorry you can not undergone any process over this asset ' or '' if msg: raise orm.except_orm(_('Warrning'), msg) return True
def button_upgrade(self, cr, uid, ids, context=None): depobj = self.pool.get('ir.module.module.dependency') todo = self.browse(cr, uid, ids, context=context) self.update_list(cr, uid) i = 0 while i<len(todo): mod = todo[i] i += 1 if mod.state not in ('installed','to upgrade'): raise orm.except_orm(_('Error'), _("Can not upgrade module '%s'. It is not installed.") % (mod.name,)) self.check_external_dependencies(mod.name, 'to upgrade') iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context) for dep in depobj.browse(cr, uid, iids, context=context): if dep.module_id.state=='installed' and dep.module_id not in todo: todo.append(dep.module_id) ids = map(lambda x: x.id, todo) self.write(cr, uid, ids, {'state':'to upgrade'}, context=context) to_install = [] for mod in todo: for dep in mod.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,)) if dep.state == 'uninstalled': ids2 = self.search(cr, uid, [('name','=',dep.name)]) to_install.extend(ids2) self.button_install(cr, uid, to_install, context=context) return dict(ACTION_DICT, name=_('Upgrade'))
def get_collection(self, collection): try: db = self.connection[tools.config['mongodb_name']] collection = db[collection] except AutoReconnect as ar_e: max_tries = 5 count = 0 while count < max_tries: try: logger.notifyChannel('MongoDB', netsvc.LOG_WARNING, 'trying to reconnect...') con = self.mongo_connect() db = con[tools.config['mongodb_name']] collection = db[collection] break except AutoReconnect: count += 1 sleep(0.5) if count == 4: raise except_orm('MongoDB connection error', ar_e) except Exception, e: raise except_orm('MongoDB connection error', e)
def get_collection(self, collection): try: db = self.connection[tools.config['mongodb_name']] collection = db[collection] except AutoReconnect: max_tries = 5 count = 0 while count < max_tries: try: logger.notifyChannel('MongoDB', netsvc.LOG_WARNING, 'trying to reconnect...') con = self.mongo_connect() db = con[tools.config['mongodb_name']] collection = db[collection] break except AutoReconnect: count += 1 sleep(0.5) if count == 4: raise except_orm('MongoDB connection error', e) except Exception, e: raise except_orm('MongoDB connection error', e)
def _data_set(self, cr, uid, id, name, value, args=None, context=None): if not value: filename = self.browse(cr, uid, id, context).store_fname try: os.unlink(os.path.join(self._get_filestore(cr), filename)) except: pass cr.execute('update ir_attachment set store_fname=NULL WHERE id=%s', (id,) ) return True #if (not context) or context.get('store_method','fs')=='fs': try: path = self._get_filestore(cr) if not os.path.isdir(path): try: os.makedirs(path) except: raise except_orm(_('Permission Denied !'), _('You do not permissions to write on the server side.')) flag = None # This can be improved for dirs in os.listdir(path): if os.path.isdir(os.path.join(path,dirs)) and len(os.listdir(os.path.join(path,dirs)))<4000: flag = dirs break flag = flag or create_directory(path) filename = random_name() fname = os.path.join(path, flag, filename) fp = file(fname,'wb') v = base64.decodestring(value) fp.write(v) filesize = os.stat(fname).st_size cr.execute('update ir_attachment set store_fname=%s,store_method=%s,file_size=%s where id=%s', (os.path.join(flag,filename),'fs',len(v),id)) return True except Exception,e : raise except_orm(_('Error!'), str(e))
def create(self, cr, user, vals, context=None): if 'model_id' in vals: model_data = self.pool.get('ir.model').browse(cr, user, vals['model_id']) vals['model'] = model_data.model if context is None: context = {} if context and context.get('manual',False): vals['state'] = 'manual' if vals.get('ttype', False) == 'selection': if not vals.get('selection',False): raise except_orm(_('Error'), _('For selection fields, the Selection Options must be given!')) self._check_selection(cr, user, vals['selection'], context=context) res = super(ir_model_fields,self).create(cr, user, vals, context) if vals.get('state','base') == 'manual': if not vals['name'].startswith('x_'): raise except_orm(_('Error'), _("Custom fields must have a name that starts with 'x_' !")) if vals.get('relation',False) and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['relation'])]): raise except_orm(_('Error'), _("Model %s does not exist!") % vals['relation']) if self.pool.get(vals['model']): self.pool.get(vals['model']).__init__(self.pool, cr) #Added context to _auto_init for special treatment to custom field for select_level ctx = context.copy() ctx.update({'field_name':vals['name'],'field_state':'manual','select':vals.get('select_level','0'),'update_custom_fields':True}) self.pool.get(vals['model'])._auto_init(cr, ctx) return res
def _check_selection(self, cr, uid, selection, context=None): try: selection_list = eval(selection) except Exception: logging.getLogger("ir.model").warning( "Invalid selection list definition for fields.selection", exc_info=True ) raise except_orm( _("Error"), _( "The Selection Options expression is not a valid Pythonic expression." "Please provide an expression in the [('key','Label'), ...] format." ), ) check = True if not (isinstance(selection_list, list) and selection_list): check = False else: for item in selection_list: if not (isinstance(item, (tuple, list)) and len(item) == 2): check = False break if not check: raise except_orm( _("Error"), _("The Selection Options expression is must be in the [('key','Label'), ...] format!") ) return True
def _check_selection(self, cr, uid, selection, context=None): try: selection_list = eval(selection) except Exception: _logger.warning( 'Invalid selection list definition for fields.selection', exc_info=True) raise except_orm(_('Error'), _("The Selection Options expression is not a valid Pythonic expression." \ "Please provide an expression in the [('key','Label'), ...] format.")) check = True if not (isinstance(selection_list, list) and selection_list): check = False else: for item in selection_list: if not (isinstance(item, (tuple, list)) and len(item) == 2): check = False break if not check: raise except_orm( _('Error'), _("The Selection Options expression is must be in the [('key','Label'), ...] format!" )) return True
def create(self, cr, uid, vals, context=None): if context is None: context = {} res = super(account_external_invoice, self).create(cr, uid,vals, context=context) to_move_ctx=context.copy(); to_move_ctx.update(vals) #self.create_movement(cr, uid, context=to_move_ctx, name='') return res try: print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" res = super(account_external_invoice, self).create(cr, uid,vals, context=context) to_move_ctx=context.copy(); to_move_ctx.update(vals) self.create_movement(cr, uid, context=to_move_ctx, name='') """for inv_id, name in self.name_get(cr, uid, [res], context=context): ctx = context.copy() if vals.get('type', 'in_invoice') in ('out_invoice', 'out_refund'): ctx = self.get_log_context(cr, uid, context=ctx) message = _("Invoice '%s' is waiting for validation.") % name self.log(cr, uid, inv_id, message, context=ctx)""" return res except Exception, e: print vars(e) if '"journal_id" viol' in e.args[0]: raise orm.except_orm(_('Configuration Error!'), _('There is no Accounting Journal of type Sale/Purchase defined!')) else: raise orm.except_orm(_('Unknown Error'), str(e))
def _save(self, cr, uid, data, context): id = int(data['id']) if context.get('from',False) == 'call history': call_browse=pooler.get_pool(cr.dbname).get('cmc.call.hisoty').browse(cr, uid, id) person_id=call_browse.person_id.id else: person_id=id if data['form']['user_id'] == uid and not data['form']['call_summary']: raise except_orm('Incomplete','Please Provide Call Summary') if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Both UserGroup And User Cannot Be Selected') if data['form']['user_id'] != uid : if data['form']['allocated_user_group_id'] : raise except_orm('Warning','You Cannot Select the Group') data['form']['allocated_user_id']=data['form']['user_id'] else: if not data['form']['allocated_user_group_id'] and not data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Only one can be selected') debug("At Time of saving") debug(data) if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']: raise except_orm('Enquiry Error!', 'Both UserGroup And User Cannot Be Selected') person = pooler.get_pool(cr.dbname).get('cmc.person').browse(cr, uid, person_id) user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid) data['form']['call_date_time'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S') data['form']['call_person_type'] = 'client' data['form']['state'] = 'allocated' data['form']['agent_id'] = None data['form']['calling_about']='Self' call_id = pooler.get_pool(cr.dbname).get('cmc.call.history').create(cr, uid, data['form'], {'wizard':True, 'person': person, 'user':user}) return {}
def button_upgrade(self, cr, uid, ids, context=None): depobj = self.pool.get('ir.module.module.dependency') todo = self.browse(cr, uid, ids, context=context) self.update_list(cr, uid) i = 0 while i<len(todo): mod = todo[i] i += 1 if mod.state not in ('installed','to upgrade'): raise orm.except_orm(_('Error'), _("Can not upgrade module '%s'. It is not installed.") % (mod.name,)) self.check_external_dependencies(mod.name, 'to upgrade') iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context) for dep in depobj.browse(cr, uid, iids, context=context): if dep.module_id.state=='installed' and dep.module_id not in todo: todo.append(dep.module_id) ids = map(lambda x: x.id, todo) self.write(cr, uid, ids, {'state':'to upgrade'}, context=context) to_install = [] for mod in todo: for dep in mod.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,)) if dep.state == 'uninstalled': ids2 = self.search(cr, uid, [('name','=',dep.name)]) to_install.extend(ids2) self.button_install(cr, uid, to_install, context=context) return True
def state_update(self, cr, uid, ids, newstate, states_to_update, context=None, level=100, res={}): if level<1: raise orm.except_orm(_('Error'), _('Recursion error in modules dependencies !')) demo = False for module in self.browse(cr, uid, ids): mdemo = False for dep in module.dependencies_id: if dep.name not in res: res[dep.name] = mdemo if dep.state == 'unknown': raise orm.except_orm(_('Error'), _("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,)) ids2 = self.search(cr, uid, [('name','=',dep.name)]) if dep.state != newstate: mdemo = self.state_update(cr, uid, ids2, newstate, states_to_update, context, level-1, res=res) or mdemo else: od = self.browse(cr, uid, ids2)[0] mdemo = od.demo or mdemo res[dep.name] = mdemo else: mdemo = res[dep.name] self.check_external_dependencies(module.name, newstate) if not module.dependencies_id: mdemo = module.demo if module.state in states_to_update: self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo}) demo = demo or mdemo return demo
def _call_completed(self, cr, uid, data, context): if data['form']['user_id'] == uid and not data['form']['call_summary']: raise except_orm('Incomplete','Please Provide Call Summary') if data['form']['allocated_user_group_id'] and data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Both UserGroup And User Cannot Be Selected') if data['form']['user_id'] != uid : if data['form']['allocated_user_group_id'] : raise except_orm('Warning','You Cannot Select the Group') data['form']['allocated_user_id']=data['form']['user_id'] else: if not data['form']['allocated_user_group_id'] and not data['form']['allocated_user_id']: raise except_orm('Call Error!', 'Only one can be selected') person = pooler.get_pool(cr.dbname).get('cmc.person').browse(cr, uid, int(data['ids'][0])) user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid) debug(data) if data['form']['user_id'] == uid and not data['form']['call_summary']: raise except_orm('Incomplete','Please Provide Call Summary') data['form']['call_date_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') data['form']['call_person_type'] = 'client' data['form']['agent_id'] = None data['form']['calling_about']='Self' data['form']['state'] = 'closed' call_id = pooler.get_pool(cr.dbname).get('cmc.call.history').create(cr, uid, data['form'], {'wizard':True, 'person': person, 'user':user}) return {}
def _can_output(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] for asset in self.browse(cr, uid, ids, context=None): if asset.state != 'close': raise orm.except_orm(_('Error'), _('You cannot output an asset not already disposed!')) if asset.is_out: raise orm.except_orm(_('Error'), _('You cannot output an asset already out!'))
def _can_validate(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] for asset in self.browse(cr, uid, ids, context): if asset.category_id.asset_in_progress or not asset.in_service_date: raise orm.except_orm(_('Error'), _('You cannot validate an asset in progress or an asset without in-service date!')) if asset.state == 'draft': raise orm.except_orm(_('Error'), _('Please confirm this asset before validating it!'))
def _can_confirm_asset_sale(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] for asset in self.browse(cr, uid, ids, context=None): if asset.state not in ('confirm', 'open'): raise orm.except_orm(_('Error'), _('You cannot dispose a %s asset') % dict(ASSET_STATES)[asset.state]) if asset.sale_type == 'scrapping' and asset.sale_value: raise orm.except_orm(_('Error'), _("Scrapping value must be null"))
def _can_cancel_asset_purchase(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] for asset in self.browse(cr, uid, ids, context): if asset.state == 'cancel': raise orm.except_orm(_('Error'), _('You cannot cancel a canceled asset!')) if asset.state == 'close': raise orm.except_orm(_('Error'), _('You cannot cancel a disposed asset!'))
def set_context(self, objects, data, ids, report_type=None): for obj in objects: if obj.state == ('draft'): raise orm.except_orm(_('Warning!'), _("You cannot print report , this course not approved yet")) if obj.state == 'rejected': raise orm.except_orm(_('Warning!'), _("You cannot print report , this course is rejected")) if obj.state == 'done': raise orm.except_orm(_('Warning!'), _("You cannot print report , this course already done")) return super(public_relations, self).set_context(objects, data, ids, report_type=report_type)
def _auto_init(self, cr, context=None): self._field_create(cr, context=context) logger = netsvc.Logger() db = mdbpool.get_db() #Create the model counters document in order to #have incremental ids the way postgresql does collection = db['counters'] if not collection.find({'_id': self._table}).count(): vals = {'_id': self._table, 'counter': 1} collection.save(vals) collection = db[self._table] #Create index for the id field collection.ensure_index([('id', pymongo.ASCENDING)], deprecated_unique=None, ttl=300, unique=True) # Create auto indexs if field has select=True in field definition # like PostgreSQL created_idx = [ x['key'][0][0] for x in collection.index_information().values() if 'key' in x and len(x['key']) == 1 ] for field_name, field_obj in self._columns.iteritems(): if getattr(field_obj, 'select', False): if field_name not in created_idx: collection.ensure_index(field_name) if db.error(): raise except_orm('MongoDB create id field index error', db.error()) #Update docs with new default values if they do not exist #If we find at least one document with this field #we assume that the field is present in the collection def_fields = filter(lambda a: not collection.find_one( {a: {'$exists': True}}), self._defaults.keys()) if len(def_fields): logger.notifyChannel('orm', netsvc.LOG_INFO, 'setting default value for \ %s of collection %s' % (def_fields, self._table)) def_values = self.default_get(cr, 1, def_fields) collection.update({}, {'$set': def_values}, upsert=False, manipulate=False, safe=True, multi=True) if db.error(): raise except_orm('MongoDB update defaults error', db.error())
def _auto_init(self, cr, context=None): self._field_create(cr, context=context) logger = netsvc.Logger() db = mdbpool.get_db() #Create the model counters document in order to #have incremental ids the way postgresql does collection = db['counters'] if not collection.find({'_id': self._table}).count(): vals = {'_id': self._table, 'counter': 1} collection.save(vals) collection = db[self._table] #Create index for the id field collection.ensure_index([('id', pymongo.ASCENDING)], deprecated_unique=None, ttl=300, unique=True) # Create auto indexs if field has select=True in field definition # like PostgreSQL created_idx = [ x['key'][0][0] for x in collection.index_information().values() if 'key' in x and len(x['key']) == 1 ] for field_name, field_obj in self._columns.iteritems(): if getattr(field_obj, 'select', False): if field_name not in created_idx: collection.ensure_index(field_name) if db.error(): raise except_orm('MongoDB create id field index error', db.error()) #Update docs with new default values if they do not exist #If we find at least one document with this field #we assume that the field is present in the collection def_fields = filter( lambda a: not collection.find_one({a: { '$exists': True }}), self._defaults.keys()) if len(def_fields): logger.notifyChannel( 'orm', netsvc.LOG_INFO, 'setting default value for \ %s of collection %s' % (def_fields, self._table)) def_values = self.default_get(cr, 1, def_fields) collection.update({}, {'$set': def_values}, upsert=False, manipulate=False, safe=True, multi=True) if db.error(): raise except_orm('MongoDB update defaults error', db.error())
def _get_move_line_vals(self, cr, uid, taxes, amount_excl_tax, journal_type, default=None, context=None): lines = [] for tax_info in self.compute_all(cr, uid, taxes, amount_excl_tax, 1.0)['taxes']: if tax_info['amount']: tax_line_vals = (default or {}).copy() tax_line_vals.update({ 'tax_code_id': tax_info['tax_code_id'], 'tax_amount': tax_info['amount'] * tax_info['_refund' in journal_type and 'ref_base_sign' or 'base_sign'], }) debit, credit = 0.0, tax_info['amount'] if tax_info['amount'] < 0.0: debit, credit = abs(credit), abs(debit) if journal_type in ('purchase_refund', 'sale'): if not tax_info['account_collected_id']: raise orm.except_orm( _('Error'), _('Please indicate a collected tax account for %s!' ) % tax_info['name']) tax_line_vals.update({ 'account_id': tax_info['account_collected_id'], 'debit': debit, 'credit': credit, }) elif journal_type in ('purchase', 'sale_refund'): if not tax_info['account_paid_id']: raise orm.except_orm( _('Error'), _('Please indicate a paid tax account for %s!') % tax_info['name']) tax_line_vals.update({ 'account_id': tax_info['account_paid_id'], 'debit': credit, 'credit': debit, }) lines.append(tax_line_vals) return lines
def create(self, cr, uid, vals, context={}): try: res = super(hr_analytic_timesheet, self).create(cr, uid, vals, context) return res except Exception,e: if '"journal_id" viol' in e.args[0]: raise except_orm(_('ValidateError'), _('No analytic journal available for this employee.\nDefine an employee for the selected user and assign an analytic journal.')) elif '"account_id" viol' in e.args[0]: raise except_orm(_('ValidateError'), _('No analytic account defined on the project.\nPlease set one or we can not automatically fill the timesheet.')) else: raise except_orm(_('UnknownError'), str(e))
def buyer_proforma(self, cr, uid, ids, context=None): invoices = {} inv_ref = self.pool.get('account.invoice') res_obj = self.pool.get('res.partner') inv_line_obj = self.pool.get('account.invoice.line') wf_service = netsvc.LocalService('workflow') for lot in self.browse(cr, uid, ids, context=context): if not lot.obj_price>0: continue if not lot.ach_uid.id: raise orm.except_orm(_('Missed buyer !'), _('The object "%s" has no buyer assigned.') % (lot.name,)) else: partner_ref =lot.ach_uid.id res = res_obj.address_get(cr, uid, [partner_ref], ['contact', 'invoice']) contact_addr_id = res['contact'] invoice_addr_id = res['invoice'] if not invoice_addr_id: raise orm.except_orm(_('No Invoice Address'), _('The Buyer "%s" has no Invoice Address.') % (contact_addr_id,)) inv = { 'name': 'Auction proforma:' +lot.name, 'journal_id': lot.auction_id.journal_id.id, 'partner_id': partner_ref, 'type': 'out_invoice', } inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', partner_ref)['value']) inv['account_id'] = inv['account_id'] and inv['account_id'][0] inv_id = inv_ref.create(cr, uid, inv, context) invoices[partner_ref] = inv_id self.write(cr, uid, [lot.id], {'ach_inv_id':inv_id, 'state':'sold'}) #calcul des taxes taxes = map(lambda x: x.id, lot.product_id.taxes_id) taxes+=map(lambda x:x.id, lot.auction_id.buyer_costs) if lot.author_right: taxes.append(lot.author_right.id) inv_line= { 'invoice_id': inv_id, 'quantity': 1, 'product_id': lot.product_id.id, 'name': 'proforma'+'['+str(lot.obj_num)+'] '+ lot.name, 'invoice_line_tax_id': [(6, 0, taxes)], 'account_analytic_id': lot.auction_id.account_analytic_id.id, 'account_id': lot.auction_id.acc_income.id, 'price_unit': lot.obj_price, } inv_line_obj.create(cr, uid, inv_line, context) inv_ref.button_compute(cr, uid, invoices.values()) wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_proforma2', cr) return invoices.values()
def _check_before_creating_asset(self, cr, uid, lines, context=None): for field in self._unicity_fields: if len(set([str(getattr(line, field)) for line in lines])) > 1: field_name = field field_obj = self.pool.get('ir.model.fields') field_ids = field_obj.search(cr, uid, [('name', '=', field), ('model', '=', self._name)], limit=1, context=context) if field_ids: field_name = field_obj.read(cr, uid, field_ids[0], ['field_description'], context)['field_description'] raise orm.except_orm(_('Error'), _('You cannot not create an asset from invoice lines with different %s') % field_name) for line in lines: if line.invoice_id.type == 'in_refund' and not line.parenr_id: raise orm.except_orm(_('Error'), _('Please indicate a parent asset in line %s') % line.name)
def state_update(self, cr, uid, ids, newstate, states_to_update, context=None, level=100): if level < 1: raise orm.except_orm( _('Error'), _('Recursion error in modules dependencies !')) demo = False for module in self.browse(cr, uid, ids, context=context): mdemo = False for dep in module.dependencies_id: if dep.state == 'unknown': raise orm.except_orm( _('Error'), _("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system." ) % ( module.name, dep.name, )) ids2 = self.search(cr, uid, [('name', '=', dep.name)]) if dep.state != newstate: mdemo = self.state_update( cr, uid, ids2, newstate, states_to_update, context, level - 1, ) or mdemo else: od = self.browse(cr, uid, ids2)[0] mdemo = od.demo or mdemo self.check_external_dependencies(module.name, newstate) if not module.dependencies_id: mdemo = module.demo if module.state in states_to_update: self.write(cr, uid, [module.id], { 'state': newstate, 'demo': mdemo }) demo = demo or mdemo return demo
def unlink(self, cr, user, ids, context=None): for model in self.browse(cr, user, ids, context): if model.state != "manual": raise except_orm(_("Error"), _("You can not remove the model '%s' !") % (model.name,)) res = super(ir_model, self).unlink(cr, user, ids, context) pooler.restart_pool(cr.dbname) return res
def write(self, cr, uid, ids, vals, context=None): res = self.search(cr, uid, [('id', 'in', ids)]) if not len(res): return False if not self._check_duplication(cr, uid, vals, ids, 'write'): raise except_orm(_('ValidateError'), _('File name must be unique!')) result = super(ir_attachment, self).write(cr, uid, ids, vals, context=context) cr.commit() if 'no_index_content' in vals and vals['no_index_content']: self.write(cr, uid, ids, {'index_content': False}) else: try: for f in self.browse(cr, uid, ids, context=context): #if 'datas' not in vals: # vals['datas']=f.datas res = content_index(base64.decodestring(vals['datas']), f.datas_fname, f.file_type or None) super(ir_attachment, self).write(cr, uid, ids, {'index_content': res}) cr.commit() except: pass return result
def write(self, cr, user, ids, vals, context=None): db = mdbpool.get_db() collection = mdbpool.get_collection(self._table) vals = vals.copy() if not ids: return True self.pool.get('ir.model.access').check(cr, user, self._name, 'write', context=context) #Pre process date and datetime fields self.preformat_write_fields(vals) self.write_binary_gridfs_fields(vals) #Log access vals.update({'write_uid': user, 'write_date': datetime.now(), }) #bulk update with modifiers, and safe mode collection.update({'id': {'$in': ids}}, {'$set': vals}, False, False, True, True) if db.error(): raise except_orm('MongoDB update error', db.error()) return True
def recall(self,cr, uid, ids, *args): res = self.read(cr,uid,ids,['date_recall', 'name', 'info', 'step']) for r in res: if not r['date_recall']: raise orm.except_orm('ValidateError', ('Error, choose a date', 'date_recall')) for r in res: self.pool.get('campaign.partner.history').create(cr, uid, { 'name': 'Recall Later ' + str(r['date_recall']), 'info': r['info'], 'date': time.strftime('%Y-%m-%d %H:%M:%S'), 'step_id': r['step'][0], 'camp_partner_id': r['id'] }) self.pool.get('ir.cron').create(cr, uid, { 'user_id': uid, 'name': 'Campaign: Recall', 'nextcall': r['date_recall'], 'active': True, 'numbercall': 1, 'model': self._name, 'function': 'write', 'args': repr([[r['id']], {'date_recall':False, 'state':'draft'}]) }) self.write(cr, uid, ids, {'state':'wait'}) return True
def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] if vals.get('password') and not (uid == 1 and ids in (1, [1])) \ and vals.get('sso', [user for user in self.browse(cr, uid, ids, context) if user.sso]): raise orm.except_orm(_('Operation Canceled'), _('You cannot modify password for user with SSO authentification!')) return super(ResUsers, self).write(cr, uid, ids, vals, context)
def _compute_order(self, cr, user, order=None, context=None): #Parse the order of the object to addapt it to MongoDB if not order: order = self._order mongo_order = order.split(',') #If we only have one order field #it can contain asc or desc #Otherwise is not allowed if len(mongo_order) == 1: reg_expr = '^(([a-z0-9_]+|"[a-z0-9_]+")( *desc)+( *, *|))+$' order_desc = re.compile(reg_expr, re.I) if order_desc.match(mongo_order[0].strip()): return [(mongo_order[0].partition(' ')[0].strip(), pymongo.DESCENDING)] else: return [(mongo_order[0].partition(' ')[0].strip(), pymongo.ASCENDING)] else: res = [] reg_expr = '^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)+( *, *|))+$' regex_order_mongo = re.compile(reg_expr, re.I) for field in mongo_order: if regex_order_mongo.match(field.strip()): raise except_orm( _('Error'), _('Bad order declaration for model %s') % (self._name)) else: res.append((field.strip(), pymongo.ASCENDING)) return res
def download(self, cr, uid, ids, download=True, context=None): res = [] for mod in self.browse(cr, uid, ids, context=context): if not mod.url: continue match = re.search('-([a-zA-Z0-9\._-]+)(\.zip)', mod.url, re.I) version = '0' if match: version = match.group(1) if parse_version(mod.installed_version or '0') >= parse_version(version): continue res.append(mod.url) if not download: continue zip_content = urllib.urlopen(mod.url).read() fname = addons.get_module_path(str(mod.name)+'.zip', downloaded=True) try: with open(fname, 'wb') as fp: fp.write(zip_content) except Exception: _logger.exception('Error when trying to create module ' 'file %s', fname) raise orm.except_orm(_('Error'), _('Can not create the module file:\n %s') % (fname,)) terp = self.get_module_info(mod.name) self.write(cr, uid, mod.id, self.get_values_from_terp(terp)) cr.execute('DELETE FROM ir_module_module_dependency ' \ 'WHERE module_id = %s', (mod.id,)) self._update_dependencies(cr, uid, mod, terp.get('depends', [])) self._update_category(cr, uid, mod, terp.get('category', 'Uncategorized')) # Import module zimp = zipimport.zipimporter(fname) zimp.load_module(mod.name) return res
def hours_block_tree_view(self, cr, uid, ids, context): invoice_line_obj = self.pool.get('account.invoice.line') hours_block_obj = self.pool.get('account.hours.block') project = self.browse(cr, uid , ids)[0] invoice_line_ids = invoice_line_obj.search(cr, uid, [('account_analytic_id', '=', project.analytic_account_id.id)]) invoice_lines = invoice_line_obj.browse(cr, uid, invoice_line_ids) invoice_ids = [x.invoice_id.id for x in invoice_lines] res_ids = hours_block_obj.search(cr, uid, [('invoice_id','in',invoice_ids)]) domain=False if res_ids: domain = [('id', 'in', res_ids)] else: raise orm.except_orm(_('Warning'), _("No Hours Block for this project")) return { 'name': _('Hours Blocks'), 'domain': domain, 'res_model': 'account.hours.block', 'type': 'ir.actions.act_window', 'view_id': False, 'view_mode': 'tree,form', 'view_type': 'form', 'limit': 80, 'res_id' : res_ids or False, }
def set_context(self, objects, data, ids, report_type=None): for obj in objects: if not obj.dismissal_type.allowance_ids: raise orm.except_orm( _('Warning!'), _("You cannot print this report , %s doesn't have allowances" ) % (obj.dismissal_type.name)) if obj.state not in ('calculate', 'transfer'): raise orm.except_orm( _('Warning!'), _("You cannot print this report allowances not calculated yet" )) return super(end_of_service, self).set_context(objects, data, ids, report_type=report_type)
def write(self, cr, user, ids, vals, context=None): db = mdbpool.get_db() collection = mdbpool.get_collection(self._table) vals = vals.copy() if not ids: return True self.pool.get('ir.model.access').check(cr, user, self._name, 'write', context=context) #Pre process date and datetime fields self.preformat_write_fields(vals) self.write_binary_gridfs_fields(vals) #Log access vals.update({ 'write_uid': user, 'write_date': datetime.now(), }) #bulk update with modifiers, and safe mode collection.update({'id': { '$in': ids }}, {'$set': vals}, False, False, True, True) if db.error(): raise except_orm('MongoDB update error', db.error()) return True
def hours_block_tree_view(self, cr, uid, ids, context): invoice_line_obj = self.pool.get('account.invoice.line') hours_block_obj = self.pool.get('account.hours.block') project = self.browse(cr, uid, ids)[0] invoice_line_ids = invoice_line_obj.search( cr, uid, [('account_analytic_id', '=', project.analytic_account_id.id)], context=context) invoice_lines = invoice_line_obj.browse(cr, uid, invoice_line_ids) invoice_ids = [x.invoice_id.id for x in invoice_lines] res_ids = hours_block_obj.search(cr, uid, [('invoice_id', 'in', invoice_ids)], context=context) domain = False if res_ids: domain = [('id', 'in', res_ids)] else: raise orm.except_orm(_('Warning'), _("No Hours Block for this project")) return { 'name': _('Hours Blocks'), 'domain': domain, 'res_model': 'account.hours.block', 'type': 'ir.actions.act_window', 'view_id': False, 'view_mode': 'tree,form', 'view_type': 'form', 'limit': 80, 'res_id': res_ids or False, }
def check(self, cr, uid, model, mode='read', raise_exception=True, context=None): if uid == 1: # User root have all accesses # TODO: exclude xml-rpc requests return True assert mode in ['read', 'write', 'create', 'unlink'], 'Invalid access mode' if isinstance(model, browse_record): assert model._table_name == 'ir.model', 'Invalid model object' model_name = model.name else: model_name = model # osv_memory objects can be read by everyone, as they only return # results that belong to the current user (except for superuser) model_obj = self.pool.get(model_name) if isinstance(model_obj, osv.osv_memory): return True # We check if a specific rule exists cr.execute( 'SELECT MAX(CASE WHEN perm_' + mode + ' THEN 1 ELSE 0 END) ' ' FROM ir_model_access a ' ' JOIN ir_model m ON (m.id = a.model_id) ' ' JOIN res_groups_users_rel gu ON (gu.gid = a.group_id) ' ' WHERE m.model = %s ' ' AND gu.uid = %s ', ( model_name, uid, )) r = cr.fetchone()[0] if r is None: # there is no specific rule. We check the generic rule cr.execute( 'SELECT MAX(CASE WHEN perm_' + mode + ' THEN 1 ELSE 0 END) ' ' FROM ir_model_access a ' ' JOIN ir_model m ON (m.id = a.model_id) ' ' WHERE a.group_id IS NULL ' ' AND m.model = %s ', (model_name, )) r = cr.fetchone()[0] if not r and raise_exception: msgs = { 'read': _('You can not read this document! (%s)'), 'write': _('You can not write in this document! (%s)'), 'create': _('You can not create this kind of document! (%s)'), 'unlink': _('You can not delete this document! (%s)'), } raise except_orm(_('AccessError'), msgs[mode] % model_name) return r
def unlink(self, cr, user, ids, context=None): for model in self.browse(cr, user, ids, context): if model.state != 'manual': raise except_orm(_('Error'), _("You can not remove the model '%s' !") %(model.name,)) res = super(ir_model, self).unlink(cr, user, ids, context) pooler.restart_pool(cr.dbname) return res
def _compute_order(self, cr, user, order=None, context=None): #Parse the order of the object to addapt it to MongoDB if not order: order = self._order mongo_order = order.split(',') #If we only have one order field #it can contain asc or desc #Otherwise is not allowed if len(mongo_order) == 1: reg_expr = '^(([a-z0-9_]+|"[a-z0-9_]+")( *desc)+( *, *|))+$' order_desc = re.compile(reg_expr, re.I) if order_desc.match(mongo_order[0].strip()): return [(mongo_order[0].partition(' ')[0].strip(), pymongo.DESCENDING)] else: return [(mongo_order[0].partition(' ')[0].strip(), pymongo.ASCENDING)] else: res = [] reg_expr = '^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)+( *, *|))+$' regex_order_mongo = re.compile(reg_expr, re.I) for field in mongo_order: if regex_order_mongo.match(field.strip()): raise except_orm(_('Error'), _('Bad order declaration for model %s') % (self._name)) else: res.append((field.strip(), pymongo.ASCENDING)) return res
def _qty_available_search(self, cr, uid, obj, name, args, context=None): ops = [ '>', ] prod_ids = () if not len(args): return [] prod_ids = [] for a in args: operator = a[1] if operator not in ops: raise orm.except_orm( _('Error !'), _('Operator %s not suported in ' 'searches for qty_available ' '(product.product).' % operator)) if operator == '>': todos = self.search(cr, uid, [], context=context) ids = self.read(cr, uid, todos, ['qty_available'], context=context) for d in ids: if d['qty_available'] > 0: prod_ids.append(d['id']) return [('id', 'in', tuple(prod_ids))]
def _create_equipment(self, cr, uid, data, context): if context.get('from',False) == 'call history': call_browse=pooler.get_pool(cr.dbname).get('cmc.call.history').browse(cr, uid, int(data['id'])) details=False if call_browse.call_details: details=call_browse.call_details debug(details) if call_browse.client_id: person_id=call_browse.client_id.id else: raise except_orm('Warning','Following Record has no client') else: details=False person_id=int(data['id']) debug(person_id) return { 'domain': "[]", 'name': 'Create New Equipment Enquiry', 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'cmc.equipement.supply.process', 'view_id': False, 'type': 'ir.actions.act_window', 'context': {'person_id':person_id, 'details':details} }
def _validate(self, cr, uid, ids, context=None): context = context or {} lng = context.get('lang', False) or 'en_US' trans = self.pool.get('ir.translation') error_msgs = [] for constraint in self._constraints: fun, msg, fields = constraint if not fun(self, cr, uid, ids): # Check presence of __call__ directly instead of using # callable() because it will be deprecated as of Python 3.0 if hasattr(msg, '__call__'): tmp_msg = msg(self, cr, uid, ids, context=context) if isinstance(tmp_msg, tuple): tmp_msg, params = tmp_msg translated_msg = tmp_msg % params else: translated_msg = tmp_msg else: translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) or msg error_msgs.append(translated_msg) self._invalids.update(fields) if error_msgs: cr.rollback() raise except_orm(_('ValidateError'), '\n'.join(error_msgs)) else: self._invalids.clear()
def unlink_res_ids(self, cr, uid, ids, model, res_ids, context): unlink_line_ids = [] for template in self.browse(cr, uid, ids, context): if template.model != model: raise except_orm( _('Error'), _("unlink_res_ids: model(%s) does not match template model (%s, %s)" ) % (model, template.id, template.model)) export_line_ids = self.pool.get('ir.model.export.line').search( cr, uid, [ ('export_id.export_tmpl_id', '=', template.id), ('res_id', 'in', res_ids), ], context=context) if export_line_ids: real_res_ids = [ line['res_id'] for line in self.pool.get('ir.model.export.line').read( cr, uid, export_line_ids, ['res_id'], context) ] logger = SmileDBLogger(cr.dbname, 'ir.model.export.template', template.id, uid) logger.info( 'Unlinking model:%s, res_ids: %s - real_res_ids found: %s' % (model, res_ids, real_res_ids)) self.pool.get('ir.model.export.line').unlink( cr, uid, export_line_ids, context) unlink_line_ids.extend(export_line_ids) return unlink_line_ids
def _build_contexts(self, cr, uid, ids, data, context=None): if context is None: context = {} result = {} result['fiscalyear'] = 'fiscalyear_id' in data['form'] and data[ 'form']['fiscalyear_id'] or False result['chart_account_id'] = 'chart_account_id' in data[ 'form'] and data['form']['chart_account_id'] or False if data['form']['filter'] == 'filter_date': result['date_from'] = data['form']['date_from'] result['date_to'] = data['form']['date_to'] elif data['form']['filter'] == 'filter_period': if not data['form']['period_from'] or not data['form']['period_to']: raise orm.except_orm( _('Error'), _('Select a starting and an ending period')) result['period_from'] = data['form']['period_from'] result['period_to'] = data['form']['period_to'] if data['form']['period_to'] and result['period_to']: period_from = data['form'].get( 'period_from', False) and data['form']['period_from'][0] or False period_to = data['form'].get( 'period_to', False) and data['form']['period_to'][0] or False period_obj = self.pool.get('account.period') result['periods'] = period_obj.build_ctx_periods( cr, uid, period_from, period_to) return result
def set_context(self, objects, data, ids, report_type=None): for obj in objects: if obj.state != "approved": raise orm.except_orm( _('Warning!'), _('You cannot print this report for not approved mission!') ) if not obj.mission_id.company_id: raise orm.except_orm( _('Warning!'), _('You can not print. This report available only for internal missions !' )) return super(errand, self).set_context(objects, data, ids, report_type=report_type)
def unlink(self, cr, uid, ids, context=None): db = mdbpool.get_db() collection = mdbpool.get_collection(self._table) if not ids: return True if isinstance(ids, (int, long)): ids = [ids] self.pool.get('ir.model.access').check(cr, uid, self._name, 'unlink', context=context) # Remove binary fields (files in gridfs) self.unlink_binary_gridfs_fields(collection, ids) #Remove with safe mode collection.remove({'id': {'$in': ids}}, True) if db.error(): raise except_orm('MongoDB unlink error', db.error()) return True