def dump(ctx, db_name, s3_file): config = ( ctx.obj['config'] ) from odooku.backends import get_backend from odoo.api import Environment from odoo.service.db import dump_db s3_backend = get_backend('s3') with tempfile.TemporaryFile() as t: with Environment.manage(): dump_db(db_name, t) t.seek(0) if s3_file: s3_backend.client.upload_fileobj(t, s3_backend.bucket, s3_file) else: # Pipe to stdout while True: chunk = t.read(CHUNK_SIZE) if not chunk: break sys.stdout.write(chunk)
def restore(ctx, db_name, copy, s3_file): config = ( ctx.obj['config'] ) if update: config['update']['all'] = 1 from odooku.backends import get_backend from odoo.api import Environment from odoo.service.db import restore_db s3_backend = get_backend('s3') with tempfile.NamedTemporaryFile(delete=False) as t: if s3_file: s3_backend.client.download_fileobj(s3_backend.bucket, s3_file, t) else: # Read from stdin while True: chunk = sys.stdin.read(CHUNK_SIZE) if not chunk: break t.write(chunk) t.close() with Environment.manage(): restore_db( db_name, t.name, copy=copy ) os.unlink(t.name)
def create_return_picking(self): with Environment.manage(): env_thread1 = Environment(self._cr, self._uid, self._context) for picking in self.order_id.picking_ids: if picking.picking_type_code != 'outgoing': continue moves = [] move_qty = {} for line in self.amazon_refund_line_ids: if line.amazon_order_line_id: move = env_thread1['stock.move'].search([ ('sale_line_id', '=', line.amazon_order_line_id.id), ('product_id', '=', line.product_id.id), ('picking_id', '=', picking.id) ]) moves.append(move.id) move_qty.update({move.id: line.qty_canceled}) result = env_thread1['stock.return.picking'].with_context({ 'active_id': picking.id }).default_get(fields=[ 'product_return_moves', 'move_dest_exists', 'location_id' ]) move_dest_exists = [] product_return_moves = [] # if result.get('move_dest_exists',[]): # for exist_line in result.get('move_dest_exists',[]): # if exist_line.get('move_id') in moves: # move_dest_exists.append([0,0,exist_line]) if result.get('product_return_moves', []): for move_line in result.get('product_return_moves', []): if len(move_line) == 3: if move_line[2].get('move_id') in moves: if move_qty.get( move_line[2].get('move_id'), 0.0) > 0.0: move_line[2].update({ 'quantity': move_qty.get( move_line.get('move_id'), 0.0) }) product_return_moves.append(move_line) record = env_thread1['stock.return.picking'].create({ 'picking_id': picking.id, 'move_dest_exists': move_dest_exists, 'product_return_moves': product_return_moves, 'location_id': result.get('location_id') }) result = record.create_returns() return True
def import_(ctx, language, db_name, overwrite): context = { 'overwrite': overwrite } from odoo.modules.registry import RegistryManager from odoo.api import Environment from odoo.tools import trans_load with tempfile.NamedTemporaryFile(suffix='.po', delete=False) as t: registry = RegistryManager.get(db_name) # Read from stdin while True: chunk = sys.stdin.read(CHUNK_SIZE) if not chunk: break t.write(chunk) t.close() with Environment.manage(): with registry.cursor() as cr: trans_load(cr, t.name, language, context=context) os.unlink(t.name)
def OdooEnvironment(database, rollback=False): with Environment.manage(): registry = odoo.registry(database) try: with registry.cursor() as cr: uid = odoo.SUPERUSER_ID try: ctx = Environment(cr, uid, {})["res.users"].context_get() except Exception as e: ctx = {"lang": "en_US"} # this happens, for instance, when there are new # fields declared on res_partner which are not yet # in the database (before -u) _logger.warning( "Could not obtain a user context, continuing " "anyway with a default context. Error was: %s", e, ) env = Environment(cr, uid, ctx) cr.rollback() yield env if rollback: cr.rollback() else: cr.commit() finally: if odoo.release.version_info[0] < 10: odoo.modules.registry.RegistryManager.delete(database) else: odoo.modules.registry.Registry.delete(database) odoo.sql_db.close_db(database)
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True): res = super(stock_history, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy) if 'parallel_inventory_value' in fields and 'inventory_value' in fields: context['date'] = context.get('history_date') for line in res: with Environment.manage(): # class function env = Environment(cr, uid, context) line[ 'parallel_inventory_value'] = env.user.company_id.currency_id.compute( line['inventory_value'], env.user.company_id.parallel_currency_id) return res
def assign_old_sequences(cr, registry): if not new_field_code_added: # the field was already existing before the installation of the addon return with Environment.manage(): env = Environment(cr, SUPERUSER_ID, {}) sequence_model = env['ir.sequence'] helpdesks = env['crm.helpdesk'].search([], order="id") for helpdesk in helpdesks: helpdesk.code = sequence_model.next_by_code('crm.helpdesk')
def export(ctx, language, db_name, module): modules = module or ['all'] from odoo.modules.registry import RegistryManager from odoo.api import Environment from odoo.tools import trans_export with tempfile.TemporaryFile() as t: registry = RegistryManager.get(db_name) with Environment.manage(): with registry.cursor() as cr: trans_export(language, modules, t, 'po', cr) t.seek(0) # Pipe to stdout while True: chunk = t.read(CHUNK_SIZE) if not chunk: break sys.stdout.write(chunk)
def execute(conf_attrs, dbname, uid, obj, method, *args, **kwargs): _logger.info(str([dbname, uid, obj, method, args, kwargs])) if conf_attrs and len(conf_attrs.keys()) > 1: for attr, value in conf_attrs.items(): odoo.tools.config[attr] = value with Environment.manage(): registry = Registry(dbname) cr = registry.cursor() context = 'context' in kwargs and kwargs.pop('context') or {} env = Environment(cr, uid, context) cr.autocommit(True) # odoo.api.Environment._local.environments = env try: Model = env[obj] args = list(args) _logger.info('>>> %s' % str(args)) ids = args.pop(0) if ids: target = Model.search([('id', 'in', ids)]) else: target = Model getattr(env.registry[obj], method)(target, *args, **kwargs) # Commit only when function finish # env.cr.commit() except Exception as exc: env.cr.rollback() import traceback traceback.print_exc() raise exc #try: # raise execute.retry( # queue=execute.request.delivery_info['routing_key'], # exc=exc, countdown=(execute.request.retries + 1) * 60, # max_retries=5) #except Exception as retry_exc: # raise retry_exc finally: env.cr.close() return True
def on_change_lines(self): with Environment.manage(): env_thread1 = Environment(self._cr, self._uid, self._context) amazon_refund_lines_obj = env_thread1['amazon.refund.order.lines'] for record in self: order = record.order_id vals = {} new_amazon_retrun_lines = [] for line in order.order_line: if line.product_id.type == "service": continue if line.amazon_product_id: info = { 'amazon_order_line_id': line.id, 'amazon_product_id': line.amazon_product_id.id, 'product_id': line.product_id.id, 'product_qty': line.product_uom_qty, 'price_subtotal': line.price_subtotal, 'order_line_amount': line.price_unit, 'order_line_tax': line.line_tax_amount, 'item_promotion_adjust': line.amz_promotion_discount, 'shipping_charge': line.amz_shipping_charge_ept, 'shipping_tax': line.amz_shipping_charge_tax, 'gift_wrap_charge': line.amz_gift_wrapper_charge, 'gift_wrap_tax': line.amz_gift_wrapper_tax, 'message': 'CustomerReturn' } vals.update(info) temp_refund_lines = amazon_refund_lines_obj.new(vals) retvals = amazon_refund_lines_obj._convert_to_write( temp_refund_lines._cache) new_amazon_retrun_lines.append( amazon_refund_lines_obj.create(retvals).id) self.company_id = order.warehouse_id.company_id.id self.amazon_refund_line_ids = amazon_refund_lines_obj.browse( new_amazon_retrun_lines)
def auto_workflow_process(self, auto_workflow_process_id=False, ids=[]): transaction_log_obj = self.env['transaction.log.ept'] with Environment.manage(): env_thread1 = Environment(self._cr, self._uid, self._context) sale_order_obj = env_thread1['sale.order'] sale_order_line_obj = env_thread1['sale.order.line'] account_payment_obj = env_thread1['account.payment'] workflow_process_obj = env_thread1['sale.workflow.process.ept'] if not auto_workflow_process_id: work_flow_process_records = workflow_process_obj.search([]) else: work_flow_process_records = workflow_process_obj.browse( auto_workflow_process_id) if not work_flow_process_records: return True for work_flow_process_record in work_flow_process_records: if not ids: orders = sale_order_obj.search([ ('auto_workflow_process_id', '=', work_flow_process_record.id), ('state', 'not in', ('done', 'cancel', 'sale')), ('invoice_status', '!=', 'invoiced') ]) #('invoiced','=',False) else: orders = sale_order_obj.search([ ('auto_workflow_process_id', '=', work_flow_process_record.id), ('id', 'in', ids) ]) if not orders: continue for order in orders: if order.invoice_status and order.invoice_status == 'invoiced': continue if work_flow_process_record.validate_order: try: order.action_confirm() order.write( {'confirmation_date': order.date_order}) except Exception as e: transaction_log_obj.create({ 'message': "Error while confirm Sale Order %s\n%s" % (order.name, e), 'mismatch_details': True, 'type': 'sales' }) order.state = 'draft' continue if work_flow_process_record.invoice_policy == 'delivery': continue if not work_flow_process_record.invoice_policy and not sale_order_line_obj.search( [('product_id.invoice_policy', '!=', 'delivery'), ('order_id', 'in', order.ids)]): continue if not order.invoice_ids: if work_flow_process_record.create_invoice: try: order.action_invoice_create() except Exception as e: transaction_log_obj.create({ 'message': "Error while Create invoice for Order %s\n%s" % (order.name, e), 'mismatch_details': True, 'type': 'invoice' }) continue if work_flow_process_record.validate_invoice: for invoice in order.invoice_ids: try: invoice.action_invoice_open() except Exception as e: transaction_log_obj.create({ 'message': "Error while open Invoice for Order %s\n%s" % (order.name, e), 'mismatch_details': True, 'type': 'invoice' }) continue if work_flow_process_record.register_payment: if invoice.residual: # Create Invoice and Make Payment vals = { 'journal_id': work_flow_process_record.journal_id.id, 'invoice_ids': [(6, 0, [invoice.id])], 'communication': invoice.reference, 'currency_id': invoice.currency_id.id, 'payment_type': 'inbound', 'partner_id': invoice.commercial_partner_id.id, 'amount': invoice.residual, 'payment_method_id': work_flow_process_record. inbound_payment_method_id.id, # 'payment_method_id':work_flow_process_record.journal_id.inbound_payment_method_ids.id, 'partner_type': 'customer' } try: new_rec = account_payment_obj.create( vals) new_rec.post() except Exception as e: transaction_log_obj.create({ 'message': "Error while Validating Invoice for Order %s\n%s" % (order.name, e), 'mismatch_details': True, 'type': 'invoice' }) continue return True
def auto_create_sale_orders(self, limit=20, start_from=None): """ Method for asynchronous inter-company sale order creation from purchase order. Args: limit (int, optional): The maximum number of orders to process in given run. start_from (date, optional): The date from which to start processing orders. """ start_from = f"AND po.date_order > '{ start_from }'" if start_from else '' self.env.cr.execute(sql_po_so % { 'limit': limit, 'start_from': start_from }) orders = self.env['purchase.order'].sudo().browse( [r[0] for r in self.env.cr.fetchall()]) _logger.info(f'Creating SOs for { len(orders) } purchase orders') i = 0 errors = [] for order in orders: i += 1 po_id = order.id po_name = order.name po_origin = order.origin dest_company = order.find_company_from_partner(order.partner_id) if dest_company: try: with Environment.manage(): with registry(self.env.cr.dbname).cursor() as new_cr: context = dict(self.env.context) context.update({'force_company': dest_company.id}) new_env = api.Environment(new_cr, self.env.uid, context) new_env.user.update({ 'company_id': dest_company }) # Avoid multi-company exceptions so = order.with_env( new_env)._inter_company_create_sale_order( dest_company) _logger.info( f'Sale order { so.name } created for: [{ i }]' f' { po_name } / origin: { po_origin } ({ po_id })' ) except Exception as e: _logger.exception( f'Error during automatic sale order creation for: { po_name } ({ po_id }) / origin: { po_origin }' ) if not isinstance(e, SerializationFailure) \ and not isinstance(e, DeadlockDetected) \ and not isinstance(e, OperationalError): errors.append((po_id, repr(e))) else: partner = order.partner_id msg = f'The partner "{ partner.display_name }" ({ partner.id }) is not an internal company!' _logger.info(msg) errors.append(po_id, msg) if errors: vals = '' for e in errors: vals += ', ' if vals else '' vals += f"({ e[0] }, %s)" self.env.cr.execute( f""" UPDATE purchase_order AS po SET inter_company_error = err.msg FROM (VALUES { vals }) AS err(id, msg) WHERE po.id = err.id """, tuple(e[1] for e in errors))
def post_init_hook(cr, _): with Environment.manage(): env = Environment(cr, SUPERUSER_ID, {}) env["ir.config_parameter"].sudo().set_param( "product.product_pricelist_setting", "advanced")
def mfa_login_post(self, *args, **kwargs): """Process MFA login attempt Overview: * Try to find a user based on the MFA login token. If this doesn't work, redirect to the password login page with an error message * Validate the confirmation code provided by the user. If it's not valid, redirect to the previous login step with an error message * Generate a long-term MFA login token for the user and log the user in using the token * Build a trusted device cookie and add it to the response if the trusted device option was checked * Redirect to the provided URL or to '/web' if one was not given """ # sudo() is required because there is no request.env.uid (likely since # there is no user logged in at the start of the request) user_model_sudo = request.env['res.users'].sudo() device_model_sudo = user_model_sudo.env['res.users.device'] config_model_sudo = user_model_sudo.env['ir.config_parameter'] token = request.params.get('mfa_login_token') try: user = user_model_sudo.user_from_mfa_login_token(token) except (MfaTokenInvalidError, MfaTokenExpiredError) as exception: return http.local_redirect( '/web/login', query={ 'redirect': request.params.get('redirect'), 'error': exception.message, }, keep_hash=True, ) confirmation_code = request.params.get('confirmation_code') if not user.validate_mfa_confirmation_code(confirmation_code): return http.local_redirect( '/auth_totp/login', query={ 'redirect': request.params.get('redirect'), 'error': _('Your confirmation code is not correct. Please try' ' again.'), 'mfa_login_token': token, }, keep_hash=True, ) # These context managers trigger a safe commit, which persists the # changes right away and is needed for the auth call with Environment.manage(): with registry(request.db).cursor() as temp_cr: temp_env = Environment(temp_cr, SUPERUSER_ID, request.context) temp_user = temp_env['res.users'].browse(user.id) temp_user.generate_mfa_login_token(60 * 24 * 30) token = temp_user.mfa_login_token request.session.authenticate(request.db, user.login, token, user.id) request.params['login_success'] = True redirect = request.params.get('redirect') if not redirect: redirect = '/web' response = http.redirect_with_hash(redirect) if not isinstance(response, WerkzeugResponse): response = Response(response) if request.params.get('remember_device'): device = device_model_sudo.create({'user_id': user.id}) secret = config_model_sudo.get_param('database.secret') device_cookie = JsonSecureCookie({'device_id': device.id}, secret) cookie_lifetime = timedelta(days=30) cookie_exp = datetime.utcnow() + cookie_lifetime device_cookie = device_cookie.serialize(cookie_exp) cookie_key = 'trusted_devices_%d' % user.id sec_config = config_model_sudo.get_param('auth_totp.secure_cookie') security_flag = sec_config != '0' response.set_cookie( cookie_key, device_cookie, max_age=cookie_lifetime.total_seconds(), expires=cookie_exp, httponly=True, secure=security_flag, ) return response
def post_init_hook(cr, _): with Environment.manage(): env = Environment(cr, SUPERUSER_ID, {}) env["hr.employee"]._install_employee_firstname()
def create_refund(self): with Environment.manage(): env_thread1 = Environment(self._cr, self._uid, self._context) #sale_order_obj=env_thread1['sale.order'] for record in self: account_invoice_line_obj = env_thread1['account.invoice.line'] journal_id = record.journal_id and record.journal_id.id inv_date = record.date_ept or fields.Date.context_today(self) payment_term = record.order_id.payment_term_id or False invoice_vals = { 'name': record.order_id.name or '', 'origin': account_invoice_line_obj.name, 'type': 'out_refund', 'reference': record.order_id.client_order_ref or record.order_id.name, 'account_id': record.order_id.partner_id.property_account_receivable_id. id, 'partner_id': record.order_id.partner_invoice_id.id, 'journal_id': journal_id, 'currency_id': record.order_id.pricelist_id.currency_id.id, 'comment': record.order_id.note, 'payment_term_id': payment_term.id, 'fiscal_position_id': record.order_id.fiscal_position_id.id or record.order_id.partner_id.property_account_position_id.id, 'company_id': record.company_id.id, 'amazon_instance_id': self.instance_id.id, 'user_id': record._uid or False, 'date_invoice': inv_date, 'team_id': record.order_id.team_id and record.order_id.team_id.id, } invoice = env_thread1['account.invoice'].create(invoice_vals) record.invoice_id = invoice.id for line in record.amazon_refund_line_ids: name = line.amazon_order_line_id.name invoice_id = invoice.id account = env_thread1[ 'account.invoice.line'].get_invoice_line_account( 'out_refund', line.product_id, record.order_id.fiscal_position_id, record.company_id) quantity = line.product_qty price_unit = round( line.total_refund / quantity, self.env['decimal.precision'].precision_get( 'Product Price')) uom_id = line.amazon_order_line_id.product_uom.id vals = { 'product_id': line.product_id.id, 'name': name, 'invoice_id': invoice_id, 'account_id': account.id, 'price_unit': price_unit, 'quantity': quantity, 'uom_id': uom_id, } new_record = account_invoice_line_obj.new(vals) new_record._onchange_product_id() retval = new_record._convert_to_write( {name: new_record[name] for name in new_record._cache}) retval.update({ 'price_unit': price_unit, 'quantity': quantity, 'uom_id': uom_id, }) account_invoice_line_obj.create(retval) return True
def wrapper(self, *args, **kwargs): with Environment.manage(): with cursor(self._cr.dbname, serialized=serialized) as new_cr: return method(self.with_env(self.env(cr=new_cr)), *args, **kwargs)