def test_base_suspend_security(self): # tests are called before register_hook self.env['ir.rule']._register_hook() user_id = self.env.ref('base.user_demo').id other_company = self.env['res.company'].create({ 'name': 'other company', # without this, a partner is created and mail's constraint on # notify_email kicks in 'partner_id': self.env.ref('base.partner_demo').id, }) # be sure what we try is forbidden with self.assertRaises(exceptions.AccessError): with mute_logger('openerp.addons.base.ir.ir_model'): self.env.ref('base.user_root').sudo(user_id).name = 'test' with self.assertRaises(exceptions.AccessError): with mute_logger('openerp.addons.base.ir.ir_model'): other_company.sudo(user_id).name = 'test' # this tests ir.model.access self.env.ref('base.user_root').sudo(user_id).suspend_security().write({ 'name': 'test'}) self.assertEqual(self.env.ref('base.user_root').name, 'test') self.assertEqual(self.env.ref('base.user_root').write_uid.id, user_id) # this tests ir.rule other_company.sudo(user_id).suspend_security().write({'name': 'test'}) self.assertEqual(other_company.name, 'test') self.assertEqual(other_company.write_uid.id, user_id) # this tests if _normalize_args conversion works self.env['res.users'].browse( self.env['res.users'].suspend_security().env.uid)
def _procure_calculation_all(self, cr, uid, ids, context=None): """ @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary """ with Environment.manage(): proc_obj = self.pool.get('procurement.order') #As this function is in a new thread, i need to open a new cursor, because the old one may be closed new_cr = self.pool.cursor() scheduler_cron_id = self.pool['ir.model.data'].get_object_reference(new_cr, SUPERUSER_ID, 'procurement', 'ir_cron_scheduler_action')[1] # Avoid to run the scheduler multiple times in the same time try: with tools.mute_logger('openerp.sql_db'): new_cr.execute("SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron_id,)) except Exception: _logger.info('Attempt to run procurement scheduler aborted, as already running') new_cr.rollback() new_cr.close() return {} user = self.pool.get('res.users').browse(new_cr, uid, uid, context=context) comps = [x.id for x in user.company_ids] for comp in comps: proc_obj.run_scheduler(new_cr, uid, use_new_cursor=new_cr.dbname, company_id = comp, context=context) #close the new cursor new_cr.close() return {}
def test_04_test_overlapp(self): """Test overlapping agreement for same supplier constraint""" start_date = self.now - timedelta(days=10) start_date = start_date.strftime(DEFAULT_SERVER_DATE_FORMAT) end_date = self.now + timedelta(days=10) end_date = end_date.strftime(DEFAULT_SERVER_DATE_FORMAT) self.agreement_model.create({ 'supplier_id': self.supplier_id, 'product_id': self.product_id, 'start_date': start_date, 'end_date': end_date, 'draft': False, 'delay': 5, 'quantity': 20 }) start_date = self.now - timedelta(days=2) start_date = start_date.strftime(DEFAULT_SERVER_DATE_FORMAT) end_date = self.now + timedelta(days=2) end_date = end_date.strftime(DEFAULT_SERVER_DATE_FORMAT) # XXX disable this test to work around odoo/odoo#3056 if False: with mute_logger(): with self.assertRaises(Exception): self.agreement_model.create({ 'supplier_id': self.supplier_id, 'product_id': self.product_id, 'start_date': start_date, 'end_date': end_date, 'draft': False, 'delay': 5, 'quantity': 20 })
def test_04_test_overlap(self): start_date = date.today() - timedelta(days=10) end_date = date.today() + timedelta(days=10) self.agreement_model.create({ 'portfolio_id': self.portfolio.id, 'product_id': self.product.id, 'start_date': fields.Date.to_string(start_date), 'end_date': fields.Date.to_string(end_date), 'draft': False, 'delay': 5, 'quantity': 20, }) start_date = date.today() - timedelta(days=2) end_date = date.today() + timedelta(days=2) with mute_logger(): with self.assertRaises(Exception): self.agreement_model.create({ 'portfolio_id': self.portfolio.id, 'product_id': self.product.id, 'start_date': fields.Date.to_string(start_date), 'end_date': fields.Date.to_string(end_date), 'draft': False, 'delay': 5, 'quantity': 20, })
def update_records(model, src, field_model='model', field_id='res_id', context=None): proxy = self.pool.get(model) if proxy is None: return domain = [(field_model, '=', 'res.partner'), (field_id, '=', src.id)] ids = proxy.search(cr, openerp.SUPERUSER_ID, domain, context=context) try: with mute_logger('openerp.sql_db'), cr.savepoint(): return proxy.write(cr, openerp.SUPERUSER_ID, ids, {field_id: dst_partner.id}, context=context) except psycopg2.Error: # updating fails, most likely due to a violated unique constraint # keeping record with nonexistent partner_id is useless, better delete it return proxy.unlink(cr, openerp.SUPERUSER_ID, ids, context=context)
def _procure_calculation_all(self, cr, uid, ids, context=None): """ @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary """ proc_obj = self.pool.get('procurement.order') #As this function is in a new thread, i need to open a new cursor, because the old one may be closed new_cr = pooler.get_db(cr.dbname).cursor() scheduler_cron_id = self.pool['ir.model.data'].get_object_reference(new_cr, SUPERUSER_ID, 'procurement', 'ir_cron_scheduler_action')[1] # Avoid to run the scheduler multiple times in the same time try: with tools.mute_logger('openerp.sql_db'): new_cr.execute("SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron_id,)) except Exception: _logger.info('Attempt to run procurement scheduler aborted, as already running') new_cr.rollback() new_cr.close() return {} for proc in self.browse(new_cr, uid, ids, context=context): proc_obj.run_scheduler(new_cr, uid, automatic=proc.automatic, use_new_cursor=new_cr.dbname,\ context=context) #close the new cursor new_cr.close() return {}
def create_pageview(self, vals, test=False): # returns True if the operation in the db was successful, False otherwise lead_id = vals.get('lead_id', 0) user_id = vals.get('user_id') url = vals.get('url', '') view_date = fields.Datetime.now() with self.pool.cursor() as pv_cr: if test: pv_cr = self._cr pv_cr.execute(''' UPDATE website_crm_pageview SET view_date=%s WHERE lead_id=%s AND url=%s RETURNING id; ''', (view_date, lead_id, url)) fetch = pv_cr.fetchone() if fetch: return True else: # update failed try: with tools.mute_logger('openerp.sql_db'): pv_cr.execute(''' INSERT INTO website_crm_pageview (lead_id, user_id, url, view_date) SELECT %s,%s,%s,%s RETURNING id; ''', (lead_id, user_id, url, view_date)) fetch = pv_cr.fetchone() if fetch: # a new pageview has been created, a message is posted url = html_escape(url) body = '<a href="%s" target="_blank"><b>%s</b></a>' % (url, url) ctx = dict(self._context, mail_notify_noemail=True) self.pool['crm.lead'].message_post(self._cr, SUPERUSER_ID, [lead_id], body=body, subject="Page visited", context=ctx) return True except IntegrityError: return False
def update(self, user_presence=True): """ Register the given presence of the current user, and trigger a im_status change if necessary. The status will not be sent if not necessary. :param user_presence : True, if the user (self._uid) is still detected using its browser. :type user_presence : boolean """ presence = self.search([('user_id', '=', self._uid)], limit=1) # set the default values send_notification = True values = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'status': presence and presence.status or 'offline' } # update the user or a create a new one if not presence: # create a new presence for the user values['status'] = 'online' values['user_id'] = self._uid self.create(values) else: # write the user presence if necessary values['status'] = 'online' if user_presence else 'away' send_notification = presence.status != values['status'] # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): presence.write(values) # avoid TransactionRollbackError self.env.cr.commit() # TODO : check if still necessary # notify if the status has changed if send_notification: # TODO : add user_id to the channel tuple to allow using user_watch in controller presence self.env['bus.bus'].sendone((self._cr.dbname, 'bus.presence'), {'id': self.env.user.partner_id.id, 'im_status': values['status']}) # check for disconnected users self.check_users_disconnection() return True
def update(self, inactivity_period): """ Updates the last_poll and last_presence of the current user :param inactivity_period: duration in milliseconds """ presence = self.search([('user_id', '=', self._uid)], limit=1) # compute last_presence timestamp last_presence = datetime.datetime.now() - datetime.timedelta( milliseconds=inactivity_period) values = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), } # update the presence or a create a new one if not presence: # create a new presence for the user values['user_id'] = self._uid values['last_presence'] = last_presence.strftime( DEFAULT_SERVER_DATETIME_FORMAT) self.create(values) else: # update the last_presence if necessary, and write values if datetime.datetime.strptime( presence.last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < last_presence: values['last_presence'] = last_presence.strftime( DEFAULT_SERVER_DATETIME_FORMAT) # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): presence.write(values) # avoid TransactionRollbackError self.env.cr.commit() # TODO : check if still necessary
def _procure_calculation_all(self, cr, uid, ids, context=None): """ @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary """ with Environment.manage(): proc_obj = self.pool.get('procurement.order') #As this function is in a new thread, i need to open a new cursor, because the old one may be closed new_cr = self.pool.cursor() # Avoid to run the scheduler multiple times in the same time try: with tools.mute_logger('openerp.sql_db'): new_cr.execute("SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron_id,)) except Exception: _logger.info('Attempt to run procurement scheduler aborted, as already running') new_cr.rollback() new_cr.close() return {} user = self.pool.get('res.users').browse(new_cr, uid, uid, context=context) comps = [x.id for x in user.company_ids] for comp in comps: proc_obj.run_scheduler(new_cr, uid, use_new_cursor=new_cr.dbname, company_id = comp, context=context) #close the new cursor new_cr.close() return {}
def test_faulty_ccp_at_bank(self): company = self.env.ref('base.main_company') self.assertTrue(company) partner = self.env.ref('base.main_partner') self.assertTrue(partner) with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.bank = self.env['res.bank'].create( { 'name': 'BCV', 'ccp': '2342342343423', 'bic': '234234', 'clearing': '234234', } ) self.bank_account = self.env['res.partner.bank'].create( { 'partner_id': partner.id, 'owner_name': partner.name, 'street': partner.street, 'city': partner.city, 'zip': partner.zip, 'state': 'bvr', 'bank': self.bank.id, 'bank_name': self.bank.name, 'bank_bic': self.bank.bic, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', } )
def _default_location(self, cr, uid, ids, context=None): try: location = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock') with mute_logger('openerp.osv.orm'): location.check_access_rule('read', context=context) location_id = location.id except (ValueError, orm.except_orm), e: return False
def test_constraint_adherent_number(self): with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.env['res.partner.bank'].create({ 'partner_id': self.partner.id, 'acc_number': '12312123', 'bvr_adherent_num': 'Wrong bvr adherent number', })
def _default_stock_location(self, cr, uid, context=None): try: location_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock_quality', 'stock_location_quality') with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) except (orm.except_orm, ValueError): location_id = False return location_id
def test_constraint_ccp(self): with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.env['res.partner.bank'].create({ 'partner_id': self.partner.id, 'bank_id': self.bank.id, 'acc_number': 'R 12312123', 'ccp': '520-54025-54054', })
def _default_location(self, cr, uid, ids, context=None): location = self.pool.get("ir.model.data").xmlid_to_object(cr, uid, "stock.stock_location_stock") if not location.exists(): return False try: with mute_logger("openerp.osv.orm"): location.check_access_rule("read", context=context) location_id = location.id except (ValueError, orm.except_orm), e: return False
def _update_rel_records(self, model_to_update='', mtu_fn_rel_model='model', mtu_fn_rel_id='res_id', rel_model='frst.personemail', rel_rec_keep_id=None, rel_rec_remove_id=None): """ This method is intended to update models with special relations. These relations consist of two fields in the model_to_update that hold the relation model name and the related record id. E.g.: in 'ir.attachments' are the fields 'res_model' (char) and 'res_id' (int) that can hold a relation to any model in odoo with just these two fields. This is an alternative implementation to avoid a dedicated m2o field for any model that needs to be linked. WARNING: Sometimes a third field (e.g.: 'res_name') is also in the model_to_update. This is no problem if the field is updated automatically when the res_id or res_model field changes! Just make sure to check if it is. :param model_to_update: model_to_update - The model where we need to update some fields :param mtu_fn_rel_model: Field-name containing the related-model-name in the model_to_update :param mtu_fn_rel_id: Field-name containing the related-record-id in the model_to_update :param rel_model: Name of the related model :param keep_id: ID of the related record that will be kept (destination) :param remove_id: ID of the related record that will be removed/exchanged (source) :return: """ cr = self.env.cr # Get the update model object as SUPERUSER try: update_model_obj = self.env[model_to_update].sudo() except KeyError: update_model_obj = None if update_model_obj is None: return # Find all records where the related record must be changed domain = [(mtu_fn_rel_model, '=', rel_model), (mtu_fn_rel_id, '=', rel_rec_remove_id)] records_to_update = update_model_obj.search(domain) # Update the records logger.info( "FSO MERGE: Update the special-rel-field '%s' in the model '%s' to the value: %s" "" % (mtu_fn_rel_id, records_to_update._name, rel_rec_keep_id)) try: with mute_logger('openerp.sql_db'), cr.savepoint(): return records_to_update.write( {mtu_fn_rel_id: rel_rec_keep_id}) except psycopg2.Error: logger.error( "FSO MERGE: Update failed for special-rel-field records %s! Keeping records linked to " "a nonexistent record is useless, better delete them." % records_to_update.ids) return records_to_update.unlink()
def _default_location_source(self, cr, uid, context=None): mod_obj = self.pool.get('ir.model.data') location_source_id = 'stock_location_customers' try: source_location = mod_obj.get_object_reference(cr, uid, 'stock', location_source_id) with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule(cr, uid, [source_location[1]], 'read', context=context) except (orm.except_orm, ValueError): source_location = False return source_location[1]
def test_stock_orderpoint_wrong_uom(self): with mute_logger('openerp.sql_db'): with self.assertRaises(ValidationError): self.env['stock.warehouse.orderpoint'].create({ 'warehouse_id': self.warehouse.id, 'location_id': self.location_stock.id, 'product_id': self.productA.id, 'product_max_qty': 24, 'product_min_qty': 12, 'procure_uom_id': self.uom_kg.id, })
def update(self, user_presence=True): """ Register the given presence of the current user, and trigger a im_status change if necessary. The status will not be written or sent if not necessary. :param user_presence : True, if the user (self._uid) is still detected using its browser. :type user_presence : boolean """ presence = self.search([('user_id', '=', self._uid)], limit=1) # set the default values send_notification = True values = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'status': presence and presence.status or 'offline' } # update the user or a create a new one if not presence: # create a new presence for the user values['status'] = 'online' values['user_id'] = self._uid self.create(values) else: # write the user presence if necessary if user_presence: values['last_presence'] = time.strftime( DEFAULT_SERVER_DATETIME_FORMAT) values['status'] = 'online' else: threshold = datetime.datetime.now() - datetime.timedelta( seconds=AWAY_TIMER) if datetime.datetime.strptime( presence.last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < threshold: values['status'] = 'away' send_notification = presence.status != values['status'] # write only if the last_poll is passed TIMEOUT, or if the status has changed delta = datetime.datetime.utcnow() - datetime.datetime.strptime( presence.last_poll, DEFAULT_SERVER_DATETIME_FORMAT) if delta > datetime.timedelta( seconds=TIMEOUT) or send_notification: # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): presence.write(values) # avoid TransactionRollbackError self.env.cr.commit() # TODO : check if still necessary # notify if the status has changed if send_notification: # TODO : add user_id to the channel tuple to allow using user_watch in controller presence self.env['bus.bus'].sendone((self._cr.dbname, 'im_chat.presence'), { 'id': self._uid, 'im_status': values['status'] }) # gc : disconnect the users having a too old last_poll. 1 on 100 chance to do it. if random.random() < 0.01: self.check_users_disconnection() return True
def _default_location_source(self, cr, uid, context=None): mod_obj = self.pool.get('ir.model.data') location_source_id = 'stock_location_customers' try: source_location = mod_obj.get_object_reference( cr, uid, 'stock', location_source_id) with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule( cr, uid, [source_location[1]], 'read', context=context) except (orm.except_orm, ValueError): source_location = False return source_location[1]
def test_07_check_decrements_price(self): """Decrements price in product""" self.prod.write({'standard_price': 10000.0}) self.execute_cron_test() old = self.prod.standard_price ctx = {'active_id': self.prod.id} wiz = self.wizard_obj.with_context(ctx).create({}) with mute_logger( 'openerp.addons.product_extended_variants.wizard.wizard_price' ): wiz.with_context({}).execute_cron([self.prod.id]) self.assertNotEquals(old, self.prod.standard_price, 'No updated standard price')
def update(self, cr, uid, presence=True, context=None): """ register the poll, and change its im status if necessary. It also notify the Bus if the status has changed. """ presence_ids = self.search(cr, uid, [('user_id', '=', uid)], context=context) presences = self.browse(cr, uid, presence_ids, context=context) # set the default values send_notification = True vals = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'status': presences and presences[0].status or 'offline' } # update the user or a create a new one if not presences: vals['status'] = 'online' vals['user_id'] = uid self.create(cr, uid, vals, context=context) else: if presence: vals['last_presence'] = time.strftime( DEFAULT_SERVER_DATETIME_FORMAT) vals['status'] = 'online' else: threshold = datetime.datetime.now() - datetime.timedelta( seconds=AWAY_TIMER) if datetime.datetime.strptime( presences[0].last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < threshold: vals['status'] = 'away' send_notification = presences[0].status != vals['status'] # write only if the last_poll is passed TIMEOUT, or if the status has changed delta = datetime.datetime.now() - datetime.datetime.strptime( presences[0].last_poll, DEFAULT_SERVER_DATETIME_FORMAT) if (delta > datetime.timedelta(seconds=TIMEOUT) or send_notification): # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): self.write(cr, uid, presence_ids, vals, context=context) # avoid TransactionRollbackError cr.commit() # notify if the status has changed if send_notification: self.pool['bus.bus'].sendone(cr, uid, (cr.dbname, 'im_chat.presence'), { 'id': uid, 'im_status': vals['status'] }) # gc : disconnect the users having a too old last_poll. 1 on 100 chance to do it. if random.random() < 0.01: self.check_users_disconnection(cr, uid, context=context) return True
def _default_ubicacion_destino_id(self, cr, uid, context=None): location_xml_id = 'stock_location_customers' mod_obj = self.pool.get('ir.model.data') location_id = False if location_xml_id: try: location_model, location_id = mod_obj.get_object_reference( cr, uid, 'stock', location_xml_id) with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule( cr, uid, [location_id], 'read', context=context) except (orm.except_orm, ValueError): location_id = False return location_id
def update_records(model, src, field_model='model', field_id='res_id'): if model not in self.env: return recs = self.env[model].sudo().search([(field_model, '=', records._name), (field_id, '=', src.id)]) try: with mute_logger('openerp.sql_db'), self.env.cr.savepoint(): return recs.write({field_id: target.id}) except psycopg2.Error: # updating fails, most likely due to a violated unique # constraint keeping record with nonexistent record is useless, # better delete it return recs.unlink()
def update(self, user_presence=True): """ Register the given presence of the current user, and trigger a im_status change if necessary. The status will not be written or sent if not necessary. :param user_presence : True, if the user (self._uid) is still detected using its browser. :type user_presence : boolean """ presence = self.search([("user_id", "=", self._uid)], limit=1) # set the default values send_notification = True values = { "last_poll": time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), "status": presence and presence.status or "offline", } # update the user or a create a new one if not presence: # create a new presence for the user values["status"] = "online" values["user_id"] = self._uid self.create(values) else: # write the user presence if necessary if user_presence: values["last_presence"] = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) values["status"] = "online" else: threshold = datetime.datetime.now() - datetime.timedelta(seconds=AWAY_TIMER) if datetime.datetime.strptime(presence.last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < threshold: values["status"] = "away" send_notification = presence.status != values["status"] # write only if the last_poll is passed TIMEOUT, or if the status has changed delta = datetime.datetime.utcnow() - datetime.datetime.strptime( presence.last_poll, DEFAULT_SERVER_DATETIME_FORMAT ) if delta > datetime.timedelta(seconds=TIMEOUT) or send_notification: # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger("openerp.sql_db"): presence.write(values) # avoid TransactionRollbackError self.env.cr.connection.commit() # TODO : check if still necessary # notify if the status has changed if ( send_notification ): # TODO : add user_id to the channel tuple to allow using user_watch in controller presence self.env["bus.bus"].sendone( (self._cr.dbname, "bus.presence"), {"id": self._uid, "im_status": values["status"]} ) # gc : disconnect the users having a too old last_poll. 1 on 100 chance to do it. if random.random() < 0.01: self.check_users_disconnection() return True
def _default_location_source(self, cr, uid, context=None): """ Gets default location for source location @return: locaion id or False """ mod_obj = self.pool.get('ir.model.data') location_id = False location_xml_id = 'location_ajuste_inventario' if location_xml_id: try: location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock_ajuste', location_xml_id) with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context) except (orm.except_orm, ValueError): location_id = False return location_id
def test_03_date_orderconstraint(self): """Test that date order is checked""" start_date = date.today() - timedelta(days=40) end_date = date.today() + timedelta(days=30) with mute_logger('openerp.sql_db'): with self.assertRaises(Exception): self.agreement_model.create({ 'portfolio_id': self.portfolio.id, 'product_id': self.product.id, 'start_date': end_date, 'end_date': start_date, 'draft': False, 'delay': 5, 'quantity': 20, })
def test_faulty_ccp_at_bank(self): with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.bank.write({ 'ccp': '2342342343423', }) self.env['res.partner.bank'].create({ 'partner_id': self.partner.id, 'bank_id': self.bank.id, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', })
def test_custom_view_validation(self): Views = self.registry('ir.ui.view') model = 'ir.actions.act_url' validate = partial(Views._validate_custom_views, self.cr, self.uid, model) # validation of a single view vid = self._insert_view(**{ 'name': 'base view', 'model': model, 'priority': 1, 'arch': """<?xml version="1.0"?> <tree string="view"> <field name="url"/> </tree> """, }) self.assertTrue(validate()) # single view # validation of a inherited view self._insert_view(**{ 'name': 'inherited view', 'model': model, 'priority': 1, 'inherit_id': vid, 'arch': """<?xml version="1.0"?> <xpath expr="//field[@name='url']" position="before"> <field name="name"/> </xpath> """, }) self.assertTrue(validate()) # inherited view # validation of a bad inherited view self._insert_view(**{ 'name': 'bad inherited view', 'model': model, 'priority': 2, 'inherit_id': vid, 'arch': """<?xml version="1.0"?> <xpath expr="//field[@name='url']" position="after"> <field name="bad"/> </xpath> """, }) with mute_logger('openerp.osv.orm', 'openerp.addons.base.ir.ir_ui_view'): self.assertFalse(validate()) # bad inherited view
def read(self, fields=None, load='_classic_read'): results = super(IrActionsActWindow, self).read(fields, load) # Evaluate context value with user localdict = { 'active_model': unquote('active_model'), 'active_id': unquote('active_id'), 'active_ids': unquote('active_ids'), 'uid': unquote('uid'), 'context': unquote('context'), 'user': self.env.user, } for res in results: if 'context' in res: try: with tools.mute_logger("openerp.tools.safe_eval"): res['context'] = tools.ustr(eval(res['context'], localdict)) except: continue return results
def create_pageview(self, vals, test=False): # returns True if the operation in the db was successful, False otherwise lead_id = vals.get('lead_id', 0) user_id = vals.get('user_id') url = vals.get('url', '') view_date = fields.Datetime.now() with self.pool.cursor() as pv_cr: if test: pv_cr = self._cr pv_cr.execute( ''' UPDATE website_crm_pageview SET view_date=%s WHERE lead_id=%s AND url=%s RETURNING id; ''', (view_date, lead_id, url)) fetch = pv_cr.fetchone() if fetch: return True else: # update failed try: with tools.mute_logger('openerp.sql_db'): pv_cr.execute( ''' INSERT INTO website_crm_pageview (lead_id, user_id, url, view_date) SELECT %s,%s,%s,%s RETURNING id; ''', (lead_id, user_id, url, view_date)) fetch = pv_cr.fetchone() if fetch: # a new pageview has been created, a message is posted url = html_escape(url) body = '<a href="%s" target="_blank"><b>%s</b></a>' % ( url, url) ctx = dict(self._context, mail_notify_noemail=True) self.pool['crm.lead'].message_post( self._cr, SUPERUSER_ID, [lead_id], body=body, subject="Page visited", context=ctx) return True except IntegrityError: return False
def _default_location_source(self, cr, uid, context=None): """ Gets default location for source location @return: locaion id or False """ mod_obj = self.pool.get('ir.model.data') picking_type = context.get('picking_type') location_id = False location_xml_id = 'location_composicion' if location_xml_id: try: location_model, location_id = mod_obj.get_object_reference( cr, uid, 'product_composition', location_xml_id) with tools.mute_logger('openerp.osv.orm'): self.pool.get('stock.location').check_access_rule( cr, uid, [location_id], 'read', context=context) except (orm.except_orm, ValueError): location_id = False return location_id
def test_03_date_orderconstraint(self): """Test that date order is checked""" start_date = self.now - timedelta(days=40) start_date = start_date.strftime(DEFAULT_SERVER_DATE_FORMAT) end_date = self.now + timedelta(days=30) end_date = end_date.strftime(DEFAULT_SERVER_DATE_FORMAT) # XXX for some reason this is assertRaises is not affected by # odoo/odoo#3056. The next one in this file is. with mute_logger('openerp.sql_db'): with self.assertRaises(Exception): self.agreement_model.create({ 'supplier_id': self.supplier_id, 'product_id': self.product_id, 'start_date': end_date, 'end_date': start_date, 'draft': False, 'delay': 5, 'quantity': 20 })
def has_button_import(self, falsify=False): """ Verify that the button is either visible or invisible. After the adjacent button is loaded, allow for a second for the asynchronous call to finish and update the visibility """ code = """ window.setTimeout(function () { if (%s$('.oe_list_button_import').is(':visible')) { console.log('ok'); } else { console.log('error'); }; }, 1000); """ % ('!' if falsify else '') link = '/web#action=%s' % self.env.ref('base.action_res_users').id with mute_logger('openerp.addons.base.res.res_users'): # Mute debug log about failing row lock upon user login self.phantom_js( link, code, "$('button.oe_list_add').length", login=self.env.user.login)
def update(self, cr, uid, presence=True, context=None): """ register the poll, and change its im status if necessary. It also notify the Bus if the status has changed. """ presence_ids = self.search(cr, uid, [('user_id', '=', uid)], context=context) presences = self.browse(cr, uid, presence_ids, context=context) # set the default values send_notification = True vals = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'status' : presences and presences[0].status or 'offline' } # update the user or a create a new one if not presences: vals['status'] = 'online' vals['user_id'] = uid self.create(cr, uid, vals, context=context) else: if presence: vals['last_presence'] = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) vals['status'] = 'online' else: threshold = datetime.datetime.now() - datetime.timedelta(seconds=AWAY_TIMER) if datetime.datetime.strptime(presences[0].last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < threshold: vals['status'] = 'away' send_notification = presences[0].status != vals['status'] # write only if the last_poll is passed TIMEOUT, or if the status has changed delta = datetime.datetime.now() - datetime.datetime.strptime(presences[0].last_poll, DEFAULT_SERVER_DATETIME_FORMAT) if (delta > datetime.timedelta(seconds=TIMEOUT) or send_notification): # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): self.write(cr, uid, presence_ids, vals, context=context) # avoid TransactionRollbackError cr.commit() # notify if the status has changed if send_notification: self.pool['bus.bus'].sendone(cr, uid, (cr.dbname,'im_chat.presence'), {'id': uid, 'im_status': vals['status']}) # gc : disconnect the users having a too old last_poll. 1 on 100 chance to do it. if random.random() < 0.01: self.check_users_disconnection(cr, uid, context=context) return True
def get_scheduler_is_running(self): new_cr = self.pool.cursor() scheduler_cron_id = self.pool['ir.model.data'].get_object_reference( new_cr, SUPERUSER_ID, 'procurement', 'ir_cron_scheduler_action')[1] # Avoid to run the scheduler multiple times in the same time try: with tools.mute_logger('openerp.sql_db'): new_cr.execute( "SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron_id, )) except Exception: _logger.info( 'Attempt to run procurement scheduler aborted, as already running' ) new_cr.rollback() new_cr.close() raise osv.except_osv( 'Error!', 'Attempt to run procurement scheduler aborted, as already running' ) return {}
def test_faulty_ccp_at_bank(self): company = self.env.ref('base.main_company') self.assertTrue(company) partner = self.env.ref('base.main_partner') self.assertTrue(partner) with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.bank = self.env['res.bank'].create({ 'name': 'BCV', 'ccp': '2342342343423', 'bic': '234234', 'clearing': '234234', }) self.bank_account = self.env['res.partner.bank'].create({ 'partner_id': partner.id, 'owner_name': partner.name, 'street': partner.street, 'city': partner.city, 'zip': partner.zip, 'state': 'bvr', 'bank': self.bank.id, 'bank_name': self.bank.name, 'bank_bic': self.bank.bic, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', })
def update(self, inactivity_period): """ Updates the last_poll and last_presence of the current user :param inactivity_period: duration in milliseconds """ presence = self.search([('user_id', '=', self._uid)], limit=1) # compute last_presence timestamp last_presence = datetime.datetime.now() - datetime.timedelta(milliseconds=inactivity_period) values = { 'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), } # update the presence or a create a new one if not presence: # create a new presence for the user values['user_id'] = self._uid values['last_presence'] = last_presence.strftime(DEFAULT_SERVER_DATETIME_FORMAT) self.create(values) else: # update the last_presence if necessary, and write values if datetime.datetime.strptime(presence.last_presence, DEFAULT_SERVER_DATETIME_FORMAT) < last_presence: values['last_presence'] = last_presence.strftime(DEFAULT_SERVER_DATETIME_FORMAT) # Hide transaction serialization errors, which can be ignored, the presence update is not essential with tools.mute_logger('openerp.sql_db'): presence.write(values) # avoid TransactionRollbackError self.env.cr.commit() # TODO : check if still necessary
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): ids_int = isinstance(ids, (int, long)) if ids_int: ids = [ids] results = super(IrActionsActWindow, self).read(cr, uid, ids, fields, context, load) # Evaluate context value with user localdict = { 'active_model': unquote('active_model'), 'active_id': unquote('active_id'), 'active_ids': unquote('active_ids'), 'uid': unquote('uid'), 'context': unquote('context'), 'user': self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context), } for res in results: if 'context' in res: try: with tools.mute_logger("openerp.tools.safe_eval"): res['context'] = tools.ustr( eval(res['context'], localdict)) except: continue return results[0] if ids_int else results
def _update_foreign_keys(self, cr, uid, src_partners, dst_partner, context=None): _logger.debug('_update_foreign_keys for dst_partner: %s for src_partners: %r', dst_partner.id, list(map(operator.attrgetter('id'), src_partners))) # find the many2one relation to a partner proxy = self.pool.get('res.partner') self.get_fk_on(cr, 'res_partner') # ignore two tables for table, column in cr.fetchall(): if 'base_partner_merge_' in table: continue partner_ids = tuple(map(int, src_partners)) query = "SELECT column_name FROM information_schema.columns WHERE table_name LIKE '%s'" % (table) cr.execute(query, ()) columns = [] for data in cr.fetchall(): if data[0] != column: columns.append(data[0]) query_dic = { 'table': table, 'column': column, 'value': columns[0], } if len(columns) <= 1: # unique key treated query = """ UPDATE "%(table)s" as ___tu SET %(column)s = %%s WHERE %(column)s = %%s AND NOT EXISTS ( SELECT 1 FROM "%(table)s" as ___tw WHERE %(column)s = %%s AND ___tu.%(value)s = ___tw.%(value)s )""" % query_dic for partner_id in partner_ids: cr.execute(query, (dst_partner.id, partner_id, dst_partner.id)) else: try: with mute_logger('openerp.sql_db'), cr.savepoint(): query = 'UPDATE "%(table)s" SET %(column)s = %%s WHERE %(column)s IN %%s' % query_dic cr.execute(query, (dst_partner.id, partner_ids,)) if column == proxy._parent_name and table == 'res_partner': query = """ WITH RECURSIVE cycle(id, parent_id) AS ( SELECT id, parent_id FROM res_partner UNION SELECT cycle.id, res_partner.parent_id FROM res_partner, cycle WHERE res_partner.id = cycle.parent_id AND cycle.id != cycle.parent_id ) SELECT id FROM cycle WHERE id = parent_id AND id = %s """ cr.execute(query, (dst_partner.id,)) except psycopg2.Error: # updating fails, most likely due to a violated unique constraint # keeping record with nonexistent partner_id is useless, better delete it query = 'DELETE FROM %(table)s WHERE %(column)s = %%s' % query_dic cr.execute(query, (partner_id,))