def post_init_hook(cr, registry): """Put domain in partner access rule and copy company_id as the default value in new field company_ids.""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) # Change access rule rule = env.ref('base.res_partner_rule') rule.write({ 'active': True, 'domain_force': ("['|', ('company_ids', 'in', user.company_id.ids)," " ('company_id', '=', False)]"), }) # Copy company values partner_model = env['res.partner'] groups = partner_model.read_group([], ['company_id'], ['company_id']) for group in groups: if group['company_id']: partners = partner_model.search(group['__domain']) partners.write( {'company_ids': [(6, 0, [group['company_id'][0]])]})
def is_buffer_table_empty(self, buffer_table=None): """ return True - if buffer table is empty False - if buffer table is not empty """ with api.Environment.manage(): env = api.Environment(self.pool.cursor(), SUPERUSER_ID, self.env.context) buffer_table = buffer_table if buffer_table != None else self.table_name env.cr.execute("SELECT count(*) FROM " + buffer_table) res = int(env.cr.fetchone()[0]) if not env.cr.closed: env.cr.close() if res == 0: return True else: return False
def _ProcessMailThread(self, idthread, composer_values, rest_ids): new_cr = sql_db.db_connect(self.env.cr.dbname).cursor() uid, context = self.env.uid, self.env.context with api.Environment.manage(): self.env = api.Environment(new_cr, uid, context) try: _logger.info('Begin Thread %s Send email %s' % (idthread, len(rest_ids))) composer = self.env['mail.compose.message'].with_context( active_ids=rest_ids).create(composer_values) composer.with_context(active_ids=rest_ids).send_mail( auto_commit=True) _logger.info('End Thread %s Send email %s' % (idthread, len(rest_ids))) finally: new_cr.close()
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): if not context: context = {} if context.get('overdue_filter'): env = api.Environment(cr, uid, context) report_date = fields.Datetime.context_timestamp( env['res.partner'], datetime.now()).date() report_date = report_date.strftime('%Y-%m-%d') company = env.user.company_id account_select = 'all' partner_ids = super(ResPartner, self).search( cr, uid, args, context=context) overdue_partners, open_moves = self._get_overdue_partners( cr, uid, report_date, company.id, partner_ids, account_select, context=context) args.append(('id', 'in', overdue_partners._ids)) return super(ResPartner, self).search( cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count)
def set_default_map_settings(cr, registry): """Method called as post-install script The default method on the field can't be used, because it would be executed before loading map_website_data.xml, so it would not be able to set a value""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) user_model = env['res.users'] users = user_model.search([('context_map_website_id', '=', False)]) logger.info('Updating user settings for maps...') users.write({ 'context_map_website_id': user_model._default_map_website().id, 'context_route_map_website_id': (user_model._default_route_map_website().id), }) # Update the starting partner this way that is faster cr.execute(""" UPDATE res_users SET context_route_start_partner_id = partner_id WHERE context_route_start_partner_id IS NULL; """)
def update_be_reportscheme(self, cr, uid, ids, context=None): if not context: context = {} self.env = api.Environment(cr, uid, context) note = self._update_be_reportscheme() if note: self.write(cr, uid, ids[0], {'note': note}) view = self.env.ref( 'l10n_be_coa_multilang.update_be_reportscheme_result_view') return { 'name': _('Results'), 'res_id': ids[0], 'view_type': 'form', 'view_mode': 'form', 'res_model': 'l10n_be.update_be_reportscheme', 'view_id': False, 'target': 'new', 'views': [(view.id, 'form')], 'type': 'ir.actions.act_window' } else: return {'type': 'ir.actions.act_window_close'}
def post_init_hook(cr, registry): """Copy payment mode from partner to the new field at contract.""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) m_contract = env['account.analytic.account'] contracts = m_contract.search([ ('payment_mode_id', '=', False), ]) if contracts: _logger.info('Setting payment mode: %d contracts' % len(contracts)) for contract in contracts: payment_mode = contract.partner_id.payment_mode_id payment_term = contract.partner_id.property_payment_term_id position_fiscal = contract.partner_id.property_account_position_id if payment_mode: contract.payment_mode_id = payment_mode.id if payment_term: contract.payment_term_id = payment_term.id if position_fiscal: contract.position_fiscal_id = position_fiscal.id _logger.info('Setting payment mode: Done')
def post_init_hook(cr, registry): """ Create a payment group for every existint payment """ env = api.Environment(cr, SUPERUSER_ID, {}) payments = env['account.payment'].search( [('partner_id', '!=', False)]) for payment in payments: _logger.info('creating payment group for payment %s' % payment.id) env['account.payment.group'].create({ 'company_id': payment.company_id.id, 'partner_type': payment.partner_type, 'partner_id': payment.partner_id.id, 'payment_date': payment.payment_date, 'communication': payment.communication, 'payment_ids': [(4, payment.id, False)], 'state': ( payment.state in ['sent', 'reconciled'] and 'posted' or payment.state), })
def form_feedback(self, cr, uid, data, acquirer_name, context=None): # Process payment result = super(PaymentTransaction, self).form_feedback(cr, uid, data, acquirer_name, context=context) # Since this is an old-api definition we need to make the new environment ourselves env = api.Environment(cr, uid, context) # Search for corresponding web session orm_clws = env['clouder.web.session'].sudo() session = orm_clws.search([('reference', '=', data['item_number'])]) # If no session is found, skip and proceed as usual if not session: return result session = session[0] # Finding transaction tx = None tx_find_method_name = '_%s_form_get_tx_from_data' % acquirer_name if hasattr(self, tx_find_method_name): tx = getattr(self, tx_find_method_name)(cr, uid, data, context=context) if tx and tx.state in ['cancel', 'error']: # Cancel session session.write({'state', 'canceled'}) elif tx and tx.state in ['pending', 'done']: # Change session state session.write({'state': 'payment_processed'}) # Return the result from super at the end return result
def read(self, *args, **kwargs): result = read.origin(self, *args, **kwargs) # Sometimes the result is not a list but a dictionary # Also, we can not modify the current result as it will break calls result2 = result if not isinstance(result2, list): result2 = [result] read_values = dict((d['id'], d) for d in result2) # Old API if args and isinstance(args[0], sql_db.Cursor): cr, uid, ids = args[0], args[1], args[2] if isinstance(ids, (int, long)): ids = [ids] # If the call came from auditlog itself, skip logging: # avoid logs on `read` produced by auditlog during internal # processing: read data of relevant records, 'ir.model', # 'ir.model.fields'... (no interest in logging such operations) if kwargs.get('context', {}).get('auditlog_disabled'): return result env = api.Environment(cr, uid, {'auditlog_disabled': True}) rule_model = env['auditlog.rule'] rule_model.sudo().create_logs( env.uid, self._name, ids, 'read', read_values) # New API else: # If the call came from auditlog itself, skip logging: # avoid logs on `read` produced by auditlog during internal # processing: read data of relevant records, 'ir.model', # 'ir.model.fields'... (no interest in logging such operations) if self.env.context.get('auditlog_disabled'): return result self = self.with_context(auditlog_disabled=True) rule_model = self.env['auditlog.rule'] rule_model.sudo().create_logs( self.env.uid, self._name, self.ids, 'read', read_values) return result
def fn_post_init_hook(cr, registry): from openerp import api, SUPERUSER_ID env = api.Environment(cr,SUPERUSER_ID,context={}) model_obj = env['stock.warehouse'] warehouses = model_obj.search([('shop_id', '=', False)]) #search for existed warehouses #convert them in compatible type for wh in warehouses: values = {'name': wh.name} shop_id = env['eyekraft.shop'].create(values) values = {'shop_id': shop_id.id} wh.write(values) if wh.partner_id: partner_to_delete = wh.shop_id.partner_id wh.shop_id.partner_id = wh.partner_id partner_to_delete.sudo().unlink() #search for partners available for 'snippet_google_partner' module #and create warehouses with corresponding partners linked #to show on native module map partner_model = env['res.partner'] partners_to_stock = partner_model.search([('category_id','!=',False), ('partner_latitude','!=',False), ('partner_longitude','!=',False), ('partner_longitude','!=',False), ('date_localization','!=',False), ]) i = 1 for partner in partners_to_stock: values = {'name': partner.name,'code':'x_'+str(i)} warehouse = model_obj.create(values) warehouse.public = True warehouse.shop_id.foreign_partner = True partner_to_delete = warehouse.shop_id.partner_id warehouse.shop_id.partner_id = partner partner_to_delete.sudo().unlink() i += 1
def migrate(cr, version): env = api.Environment(cr, SUPERUSER_ID, {}) migrate_update_module(cr) migrate_create_temp_table(cr) migrate_cancel_reason(env) migrate_old_value(cr) openupgrade.drop_columns(cr, [("agreement_agreement", "old_cancel_reason_id")]) migrate_update_base_cancel_reason_config(env) if openupgrade.table_exists(env.cr, "agreement_cancel_reason"): openupgrade.logged_query( cr, """ DROP TABLE agreement_cancel_reason CASCADE """, ) if openupgrade.table_exists(env.cr, "temp_cancel_reason"): openupgrade.logged_query( cr, """ DROP TABLE temp_cancel_reason """, )
def post_init_hook(cr, registry): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) # ACTION 1: Match existing contacts contact_model = env['mail.mass_mailing.contact'] partner_model = env['res.partner'] contacts = contact_model.search([('email', '!=', False)]) _logger.info('Trying to match %d contacts to partner by email', len(contacts)) for contact in contacts: partners = partner_model.search( [('email', '=ilike', contact.email)], limit=1) if partners: contact.write({'partner_id': partners.id}) # ACTION 2: Match existing statistics stat_model = env['mail.mail.statistics'] stats = stat_model.search([ ('model', '!=', False), ('res_id', '!=', False), ]) _logger.info('Trying to link %d mass mailing statistics to partner', len(stats)) stats.partner_link()
def post_init_hook(cr, registry): """Change to second alias all the existing project aliases that point to issues. """ with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) alias_obj = env['mail.alias'] issue_model = env['ir.model'].search([('model', '=', 'project.issue')]) for project in env['project.project'].search([]): if project.alias_model == 'project.issue': alias_name = project.alias_name project.alias_id.alias_name = False project.second_alias_name = alias_name else: # Search for an existing alias in the system alias = alias_obj.search( [('alias_parent_thread_id', '=', project.id), ('alias_model_id', '=', issue_model.id)], limit=1) if alias: project.with_context(no_check=True).write({ 'second_alias_id': alias.id, 'second_alias_name': alias.alias_name, })
def setUp(self): super(TestDefaultQuantOwner, self).setUp() self.partner = self.env.ref('stock.res_partner_company_1') self.company = self.env.ref('stock.res_company_1') self.chic_user = self.env['res.users'].create({ "partner_id": self.partner.id, "company_id": self.company.id, "company_ids": [(4, self.company.id), (4, self.partner.company_id.id)], "login": "******", "name": "my user", "groups_id": [(4, self.ref('base.group_user')), (4, self.ref('stock.group_stock_manager')), (4, self.ref('base.group_sale_manager'))] }) self.env.ref('product.product_product_9').company_id = self.company.id self.chic_env = api.Environment(self.cr, self.chic_user.id, {}) self.product = self.chic_env.ref('product.product_product_9') self.Quant = self.chic_env['stock.quant']
def post_init_hook(cr, registry): """Put domain in product access rule and copy company_id as the default value in new field company_ids.""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) # Change access rule rule = env.ref('product.product_comp_rule') rule.write({ 'active': True, 'domain_force': ("['|', ('company_ids', 'in', user.company_id.ids)," " ('company_id', '=', False)]"), }) # Copy company values template_model = env['product.template'] groups = template_model.read_group([], ['company_id'], ['company_id']) for group in groups: if not group['company_id']: continue templates = template_model.search(group['__domain']) templates.write( {'company_ids': [(6, 0, [group['company_id'][0]])]})
def run(self): """ Run the process for each attachment metadata """ for attachment in self: with api.Environment.manage(): with openerp.registry(self.env.cr.dbname).cursor() as new_cr: new_env = api.Environment(new_cr, self.env.uid, self.env.context) attach = attachment.with_env(new_env) try: attach._run() except Exception, e: attach.env.cr.rollback() _logger.exception(unicode(e)) attach.write({ 'state': 'failed', 'state_message': unicode(e), }) attach.env.cr.commit() else: attach.write({'state': 'done'}) attach.env.cr.commit()
def authenticate(self, user, password): # stay non-authenticated if user is None: return db = get_db_name() uid = self.registry['res.users'].authenticate(db, user, password, None) env = api.Environment(self.cr, uid, {}) # self.session.authenticate(db, user, password, uid=uid) # OpenERPSession.authenticate accesses the current request, which we # don't have, so reimplement it manually... session = self.session session.db = db session.uid = uid session.login = user session.password = password session.context = env['res.users'].context_get() or {} session.context['uid'] = uid session._fix_lang(session.context) openerp.http.root.session_store.save(session)
def update_log(self, import_operation, file_name): """ It will write log for the import task """ if CSVHolder.debug: _logger.info("Function : update_log() start") result = [] with api.Environment.manage(): env = api.Environment(self.pool.cursor(), SUPERUSER_ID, self.env.context) cur = env.cr try: logger_obj = env['csv.import.logger'] result = logger_obj.write_log(import_operation, file_name) except Exception, e: if CSVHolder.debug: _logger.info("Error in log updation : " + str(e)) finally:
def onchange_date_to(self, cr, uid, ids, date_to, date_from, employee_id=[]): result = super(hr_holidays, self).onchange_date_to(cr, uid, ids, date_to, date_from) _logger.warn(result) env = api.Environment(cr, uid, {}) employee = env['hr.employee'].browse(employee_id) if employee: if date_to and not date_from: date_from = result['value'][ 'date_from'] = self._get_default_date_from( employee, date_to) if date_from and date_to and result['value'].get( 'number_of_days_temp', 2) <= 1.0: result['value'][ 'number_of_days_temp'] = self._get_number_of_days_temp( employee, date_from, date_to) return result
def migrate(cr, version): """Copy account.period to data.range only for those periods with vat statement""" if not version: return with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) date_range_model = env['date.range'] date_range_type = env['date.range.type'] env.cr.execute( """SELECT vat_statement_id, company_id, name, date_start, date_stop from account_period """) periods = env.cr.fetchall() for period in periods: # if period has vat statement if period[0]: date_range = date_range_model.search([ ('date_start', '=', period[3]), ('date_end', '=', period[4]) ]) if date_range: date_range.write({'vat_statement_id': period[0]}) else: if not date_range_type: date_range_type = env['date.range.type'].create( {'name': 'periodo fiscale'}) date_range_type.company_id = period[1] date_range_vals = { 'vat_statement_id': period[0], 'company_id': period[1], 'name': period[2], 'type_id': date_range_type.id, 'date_start': period[3], 'date_end': period[4] } date_range_model.create(date_range_vals)
def get_bank_statement(self, user, _operating_unit, _fondo_rotatorio_siif): env = api.Environment(self.cr, user, {}) journal_obj = env['account.journal'] bank_statement_obj = env['account.bank.statement'] args = [('operating_unit_id', '=', _operating_unit), ('fondo_rotatorio_siif', '=', _fondo_rotatorio_siif)] dict_byfr = {} for journal_id in journal_obj.search(args): bank_statement_id = bank_statement_obj.search( [('journal_id', '=', journal_id.id), ('state', '!=', 'draft')], order='date DESC', limit=1) if bank_statement_id: dict_byfr.setdefault( bank_statement_id.journal_id.fondo_rotatorio_siif, {'data': []}) dict_byfr[bank_statement_id.journal_id. fondo_rotatorio_siif]['data'].append({ 'journal_id': journal_id, 'bank_statement_id': bank_statement_id }) return dict_byfr
def _env_get(db, callback, tracking_id, event_type, **kw): res = 'NOT FOUND' reg = False current = http.request.db and db == http.request.db env = current and http.request.env if not env: with api.Environment.manage(): try: reg = registry(db) except OperationalError: _logger.warning("Selected BD '%s' not found", db) except: # pragma: no cover _logger.warning("Selected BD '%s' connection error", db) if reg: _logger.info("New environment for database '%s'", db) with reg.cursor() as new_cr: new_env = api.Environment(new_cr, SUPERUSER_ID, {}) res = callback(new_env, tracking_id, event_type, **kw) new_env.cr.commit() else: # make sudo when reusing environment env = env(user=SUPERUSER_ID) res = callback(env, tracking_id, event_type, **kw) return res
def _event_process(self, event): message_id = event.get('_id') event_type = event.get('event') message = event.get('msg') if not (message_id and event_type and message): return False info = "%s event for Message ID '%s'" % (event_type, message_id) metadata = message.get('metadata') db = None if metadata: db = metadata.get('odoo_db', None) # Check database selected by mandrill event if not db: _logger.info('%s: No DB selected', info) return False try: registry = openerp.registry(db) except OperationalError: _logger.info("%s: Selected BD '%s' not found", info, db) return False except: _logger.info("%s: Selected BD '%s' connection error", info, db) return False # Database has been selected, process event with registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) res = env['mail.mandrill.message'].process(message_id, event_type, event) if res: _logger.info('%s: OK', info) else: _logger.info('%s: FAILED', info) return res
def create_fiscal_classification_from_product_template(cr, registry): """Generate Fiscal Classification for each combinations of Taxes set in product""" env = api.Environment(cr, SUPERUSER_ID, {}) template_obj = env['product.template'] classification_obj = env['account.product.fiscal.classification'] classifications_keys = {} # Get all product template templates = template_obj.search( ['|', ('active', '=', False), ('active', '=', True)]) counter = 0 total = len(templates) # Associate product template to Fiscal Classifications for template in templates: counter += 1 args = [ template.company_id and template.company_id.id or False, sorted([x.id for x in template.taxes_id]), sorted([x.id for x in template.supplier_taxes_id]) ] if args not in classifications_keys.values(): _logger.info( """create new Fiscal Classification. Product templates""" """ managed %s/%s""" % (counter, total)) classification_id = classification_obj.find_or_create(*args) classifications_keys[classification_id] = args # associate product template to the new Fiscal Classification template.fiscal_classification_id = classification_id else: # associate product template to existing Fiscal Classification template.fiscal_classification_id = classifications_keys.keys()[ classifications_keys.values().index(args)]
def __init__(self, name, dialer): super(AriOdooSessionThread, self).__init__() dbname = dialer.env.cr.dbname uid = dialer.env.uid # Init new Env self.cursor = sql_db.db_connect(dbname).cursor() self.env = api.Environment(self.cursor, uid, {}) self.env.cr.autocommit(True) # Init objects with new Env self.dialer = self.env['asterisk.dialer'].browse([dialer.id]) self.session = self.env['asterisk.dialer.session'].browse( [dialer.active_session.id]) self.setName('%s-%s' % (name, self.dialer.id)) # Init ARI server = self.env['asterisk.server.settings'].browse([1]) # Get rid of unicode as ari-py does not handle it. ari_user = str(server.ari_user) ari_pass = str(server.ari_pass) ari_url = str('http://' + server.ip_addr + ':' + server.http_port) self.ari_url = ari_url self.ari_user = ari_user self.ari_pass = ari_pass # We'll initialize connection to ARI on run. self.ari_client = None
def is_table_exist(self, table_name=None): """ return True - if table exist False - if table does not exist """ with api.Environment.manage(): env = api.Environment(self.pool.cursor(), SUPERUSER_ID, self.env.context) cur = env.cr table_name = self.table_name if table_name is None else table_name try: cur.execute( "select exists(select * from information_schema.tables where table_name=%s)", (table_name, )) result = cur.fetchone()[0] # pdb.set_trace() finally: if not cur.closed: cur.close() return result
def google_map_img(self, cr, uid, ids, zoom=8, width=298, height=298, marker=None, context=None): env = api.Environment(cr, uid, context) return super(ResCompany, self).google_map_img( cr, uid, ids, zoom=zoom, width=width, height=height, marker=marker or { 'icon': env['ir.config_parameter'].get_param( 'dermanord_map_marker', 'http://wiggum.vertel.se/dn_maps_marker.png') }, context=context)
def get_pending_import_request(self, external_task=None): """ We can get the pending import list using that function """ with api.Environment.manage(): env = api.Environment(self.pool.cursor(), SUPERUSER_ID, self.env.context) cur = env.cr try: data = [] sel_col = 'details.id "details_id",details.import_col_count "db_count"' sel_col += ', details.import_class "class", details.import_func "func"' sel_col += ', logger.id, logger.import_operation' sel_col += ', logger.import_progress' sel_col += ', logger.import_sdate, logger.import_fdate' sel_col += ', logger.import_file_name' from_tab = ' csv_import_logger logger, csv_importer_details details' if external_task is not None: where_cond = ' logger.id = details.import_req_id AND logger.id = ' + str( external_task) else: where_cond = ' logger.id = details.import_req_id AND logger.import_progress = 0 ' query = 'SELECT ' + sel_col + " FROM " + from_tab + " WHERE " + where_cond cur.execute(query) recs = cur.dictfetchall() finally: if not env.cr.closed: env.cr.close() return recs
def get_access_action(self, cr, uid, id, context): """ Instead of the classic form view, redirect to the online quote for portal users that have access to a confirmed order. """ # TDE note: read access on sale order to portal users granted to followed sale orders env = api.Environment(cr, uid, context) record = env[self._name].browse(id) if record.state == 'cancel' or ( record.state == 'draft' and not env.context.get('mark_so_as_sent')): return super(SaleOrder, self).get_access_action(cr, uid, id, context) if env.user.share or env.context.get('force_website'): try: self.check_access_rule(cr, uid, id, 'read', context) except exceptions.AccessError: pass else: return { 'type': 'ir.actions.act_url', 'url': '/my/orders/%s' % id, 'target': 'self', 'res_id': id, } return super(SaleOrder, self).get_access_action(cr, uid, id, context)