Python odoo.SUPERUSER_ID Examples

The following are 15 code examples of odoo.SUPERUSER_ID(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module odoo , or try the search function .
Example #1
Source File: openupgrade_80.py    From openupgradelib with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_last_post_for_model(cr, uid, ids, model_pool):
    """
    Given a set of ids and a model pool, return a dict of each object ids with
    their latest message date as a value.
    To be called in post-migration scripts

    :param cr: database cursor
    :param uid: user id, assumed to be openerp.SUPERUSER_ID
    :param ids: ids of the model in question to retrieve ids
    :param model_pool: orm model pool, assumed to be from pool.get()
    :return: a dict with ids as keys and with dates as values
    """
    if type(ids) is not list:
        ids = [ids]
    res = {}
    for obj in model_pool.browse(cr, uid, ids):
        message_ids = obj.message_ids
        if message_ids:
            res[obj.id] = sorted(
                message_ids, key=lambda x: x.date, reverse=True)[0].date
        else:
            res[obj.id] = False
    return res 
Example #2
Source File: __init__.py    From Odoo-12-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def add_book_hook(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    book_data1 = {'name': 'Book 1', 'date_release': fields.Date.today()}
    book_data2 = {'name': 'Book 2', 'date_release': fields.Date.today()}
    env['library.book'].create([book_data1, book_data2]) 
Example #3
Source File: env.py    From click-odoo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def OdooEnvironment(database, rollback=False, **kwargs):
    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.tools.parse_version(
                odoo.release.version
            ) < odoo.tools.parse_version("10.0"):
                odoo.modules.registry.RegistryManager.delete(database)
            else:
                odoo.modules.registry.Registry.delete(database)
            odoo.sql_db.close_db(database) 
Example #4
Source File: http.py    From odoo-dingtalk-connector with GNU General Public License v3.0 5 votes vote down vote up
def render(self):
        """ Renders the Response's template, returns the result
        """
        env = request.env(user=self.uid or request.uid or odoo.SUPERUSER_ID)
        self.qcontext['request'] = request
        return env["ir.ui.view"].render_template(self.template, self.qcontext) 
Example #5
Source File: translate.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def _get_translation(self, source):
        res = source
        cr = None
        is_new_cr = False
        try:
            frame = inspect.currentframe()
            if frame is None:
                return source
            frame = frame.f_back
            if not frame:
                return source
            frame = frame.f_back
            if not frame:
                return source
            lang = self._get_lang(frame)
            if lang:
                cr, is_new_cr = self._get_cr(frame)
                if cr:
                    # Try to use ir.translation to benefit from global cache if possible
                    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
                    res = env['ir.translation']._get_source(None, ('code',), lang, source)
                else:
                    _logger.debug('no context cursor detected, skipping translation for "%r"', source)
            else:
                _logger.debug('no translation language detected, skipping translation for "%r" ', source)
        except Exception:
            _logger.debug('translation went wrong for "%r", skipped', source)
                # if so, double-check the root/base translations filenames
        finally:
            if cr and is_new_cr:
                cr.close()
        return res 
Example #6
Source File: translate.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def load_language(cr, lang):
    """ Loads a translation terms for a language.
    Used mainly to automate language loading at db initialization.

    :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE')
    :type lang: str
    """
    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
    installer = env['base.language.install'].create({'lang': lang})
    installer.lang_install() 
Example #7
Source File: cli.py    From anthem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _build_odoo_env(self, odoo_args):
        odoo.tools.config.parse_config(odoo_args)
        dbname = odoo.tools.config['db_name']
        odoo.tools.config['workers'] = 0
        odoo.tools.config['xmlrpc'] = False
        if not dbname:
            argparse.ArgumentParser().error(
                "please provide a database name though Odoo options (either "
                "-d or an Odoo configuration file)"
            )
        logging.getLogger(odoo_logger).setLevel(logging.ERROR)
        odoo.service.server.start(preload=[], stop=True)

        # odoo.service.server.start() modifies the SIGINT signal by its own
        # one which in fact prevents us to stop anthem with Ctrl-c.
        # Restore the default one.
        signal.signal(signal.SIGINT, signal.default_int_handler)
        odoo_version = odoo.release.version_info[0]
        # On saas versions this will be "saas-XX" where XX is the odoo version
        if not isinstance(odoo_version, int):
            odoo_version = int(
                odoo_version.lstrip(string.ascii_letters + '-~')
            )
        if odoo_version > 9:
            registry = odoo.modules.registry.Registry(dbname)
        else:
            registry = odoo.modules.registry.RegistryManager.get(dbname)
        cr = registry.cursor()
        uid = odoo.SUPERUSER_ID
        Environment.reset()
        context = Environment(cr, uid, {})['res.users'].context_get()
        return Environment(cr, uid, context) 
Example #8
Source File: openupgrade_80.py    From openupgradelib with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_aliases(
        cr, registry, model_name, set_parent_thread_id,
        alias_defaults=None, defaults_id_key=False):
    """
    Update a model's aliases according to how they are configured
    in the model's create() method.

    :param model_name: The name of the model whose aliases are to be updated. \
    The model_id is also set as the aliases' alias_parent_model_id.
    :param set_parent_thread_id': When set, set the ids of the resources as \
    their alias' alias_parent_thread_id
    :param alias_defaults: Static dictionary, recorded as a string on each \
    alias
    :param defaults_id_key: When defined, add this key to each alias' \
    defaults dictionary with the resource id as its value.
    """
    model_id = registry['ir.model'].search(
        cr, SUPERUSER_ID, [('model', '=', model_name)])[0]
    vals = {'alias_parent_model_id': model_id}
    if defaults_id_key and alias_defaults is None:
        alias_defaults = {}
    res_ids = registry[model_name].search(
        cr, SUPERUSER_ID, [], context={'active_test': False})
    for res in registry[model_name].browse(
            cr, SUPERUSER_ID, res_ids):
        if set_parent_thread_id:
            vals['alias_parent_thread_id'] = res.id
        if defaults_id_key:
            alias_defaults[defaults_id_key] = res.id
        if alias_defaults is not None:
            vals['alias_defaults'] = str(alias_defaults)
        res.alias_id.write(vals) 
Example #9
Source File: oauth_signin_3rd.py    From weodoo with MIT License 4 votes vote down vote up
def signin_3rd(self, **kw):
        state = json.loads(kw['state'])
        dbname = state['d']
        provider = state['p']
        context = state.get('c', {})
        registry = registry_get(dbname)
        with registry.cursor() as cr:
            try:
                env = api.Environment(cr, SUPERUSER_ID, context)
                credentials = env['res.users'].sudo().auth_oauth_third(provider, kw)
                cr.commit()
                action = state.get('a')
                menu = state.get('m')
                redirect = werkzeug.url_unquote_plus(state['r']) if state.get('r') else False
                url = '/web'
                if redirect:
                    url = redirect
                elif action:
                    url = '/web#action=%s' % action
                elif menu:
                    url = '/web#menu_id=%s' % menu
                if credentials[0]==-1:
                    from .controllers import gen_id
                    credentials[1]['oauth_provider_id'] = provider
                    qr_id = gen_id(credentials[1])
                    redirect = base64.urlsafe_b64encode(redirect.encode('utf-8')).decode('utf-8')
                    url = '/corp/bind?qr_id=%s&redirect=%s'%(qr_id, redirect)
                else:
                    return login_and_redirect(*credentials, redirect_url=url)
            except AttributeError:
                import traceback;traceback.print_exc()
                # auth_signup is not installed
                _logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,))
                url = "/web/login?oauth_error=1"
            except AccessDenied:
                import traceback;traceback.print_exc()
                # oauth credentials not valid, user could be on a temporary session
                _logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
                url = "/web/login?oauth_error=3"
                redirect = werkzeug.utils.redirect(url, 303)
                redirect.autocorrect_location_header = False
                return redirect
            except Exception as e:
                # signup error
                _logger.exception("OAuth2: %s" % str(e))
                url = "/web/login?oauth_error=2"

        return set_cookie_and_redirect(url) 
Example #10
Source File: translate.py    From odoo13-x64 with GNU General Public License v3.0 4 votes vote down vote up
def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None):
    """Populates the ir_translation table."""
    if verbose:
        _logger.info('loading translation file for language %s', lang)

    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, context or {})
    Lang = env['res.lang']
    Translation = env['ir.translation']

    try:
        if not Lang.search_count([('code', '=', lang)]):
            # lets create the language with locale information
            Lang.load_lang(lang=lang, lang_name=lang_name)

        # now, the serious things: we read the language file
        fileobj.seek(0)
        reader = TranslationFileReader(fileobj, fileformat=fileformat)

        # read the rest of the file
        irt_cursor = Translation._get_import_cursor()

        def process_row(row):
            """Process a single PO (or POT) entry."""
            # dictionary which holds values for this line of the csv file
            # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
            #  'src': ..., 'value': ..., 'module':...}
            dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value',
                                 'comments', 'imd_model', 'imd_name', 'module'))
            dic['lang'] = lang
            dic.update(row)

            # do not import empty values
            if not env.context.get('create_empty_translation', False) and not dic['value']:
                return

            if dic['type'] == 'code' and module_name:
                dic['module'] = module_name

            irt_cursor.push(dic)

        # First process the entries from the PO file (doing so also fills/removes
        # the entries from the POT file).
        for row in reader:
            process_row(row)

        irt_cursor.finish()
        Translation.clear_caches()
        if verbose:
            _logger.info("translation file loaded successfully")

    except IOError:
        iso_lang = get_iso_codes(lang)
        filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
        _logger.exception("couldn't read translation file %s", filename) 
Example #11
Source File: session.py    From anybox.recipe.odoo with GNU Affero General Public License v3.0 4 votes vote down vote up
def open(self, db=None, with_demo=False):
        """Load the database

        Loading an empty database in Odoo has the side effect of installing
        the ``base`` module. Whether to loading demo data or not has therefore
        to be decided right away.

        :param db: database name. If not specified, the same cascading of
                   defaults as Odoo mainstream will be applied:
                   configuration file, psycopg2/lipq defaults.
        :param with_demo: controls the loading of demo data for all
                          module installations triggered by this call to
                          :meth:`open` and further uses of :meth:`load_modules`
                          on this :class:`Session` instance:

                          * if ``True``, demo data will uniformly be loaded
                          * if ``False``, no demo data will be loaded
                          * if ``None``, demo data will be loaded according to
                            the value of ``without_demo`` in configuration

                          In all cases, the behaviour will stay consistent
                          until the next call of ``open()``, but the
                          implementation does not protect against any race
                          conditions in Odoo internals.
        """
        if db is None:
            db = config['db_name']
        if not db:
            db = ''  # expected value expected by Odoo to start defaulting.

        cnx = odoo.sql_db.db_connect(db)
        cr = cnx.cursor()
        self.is_initialization = not(odoo.modules.db.is_initialized(cr))
        cr.close()

        startup.check_root_user()
        if not os.environ.get('ENABLE_POSTGRES_USER'):
            startup.check_postgres_user()
        odoo.netsvc.init_logger()

        saved_without_demo = config['without_demo']
        if with_demo is None:
            with_demo = config['without_demo']

        config['without_demo'] = not with_demo
        self.with_demo = with_demo

        if version_info[0] <= 10:
            self._registry = Registry.get(
                db, update_module=False)
        else:
            # Form Odoo 11.0: no get method available
            self._registry = Registry(db)
        config['without_demo'] = saved_without_demo
        self.init_cursor()
        self.uid = SUPERUSER_ID
        self.init_environments()
        self.context = self.env['res.users'].context_get()
        self.env = odoo.api.Environment(self.cr, self.uid, self.context) 
Example #12
Source File: openupgrade.py    From openupgradelib with GNU Affero General Public License v3.0 4 votes vote down vote up
def add_xmlid(cr, module, xmlid, model, res_id, noupdate=False):
    """
    Adds an entry in ir_model_data. Typically called in the pre script.
    One usage example is when an entry has been add in the XML and there is
    a high probability that the user has already created the entry manually.
    For example, a currency was added in the XML data of the base module
    in OpenERP 6 but the user had already created this missing currency
    by hand in it's 5.0 database. In order to avoid having 2 identical
    currencies (which is in fact blocked by an sql_constraint), you have to
    add the entry in ir_model_data before the upgrade.
    """
    # Check if the XMLID doesn't already exists
    cr.execute(
        "SELECT id FROM ir_model_data WHERE module=%s AND name=%s "
        "AND model=%s",
        (module, xmlid, model))
    already_exists = cr.fetchone()
    if already_exists:
        return False
    else:
        logged_query(
            cr,
            "INSERT INTO ir_model_data (create_uid, create_date, "
            "write_uid, write_date, date_init, date_update, noupdate, "
            "name, module, model, res_id) "
            "VALUES (%s, (now() at time zone 'UTC'), %s, "
            "(now() at time zone 'UTC'), (now() at time zone 'UTC'), "
            "(now() at time zone 'UTC'), %s, %s, %s, %s, %s)", (
                SUPERUSER_ID, SUPERUSER_ID, noupdate,
                xmlid, module, model, res_id))
        return True 
Example #13
Source File: openupgrade.py    From openupgradelib with GNU Affero General Public License v3.0 4 votes vote down vote up
def update_workflow_workitems(cr, pool, ref_spec_actions):
    """Find all the workflow items from the target state to set them to
    the wanted state.

    When a workflow action is removed, from model, the objects whose states
    are in these actions need to be set to another to be able to continue the
    workflow properly.

    Run in pre-migration

    :param ref_spec_actions: list of tuples with couple of workflow.action's
        external ids. The first id is replaced with the second.
    :return: None

    .. versionadded:: 7.0
    """
    workflow_workitems = pool['workflow.workitem']
    ir_model_data_model = pool['ir.model.data']

    for (target_external_id, fallback_external_id) in ref_spec_actions:
        target_activity = ir_model_data_model.get_object(
            cr, SUPERUSER_ID,
            target_external_id.split(".")[0],
            target_external_id.split(".")[1],
        )
        fallback_activity = ir_model_data_model.get_object(
            cr, SUPERUSER_ID,
            fallback_external_id.split(".")[0],
            fallback_external_id.split(".")[1],
        )
        ids = workflow_workitems.search(
            cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
        )
        if ids:
            logger.info(
                "Moving %d items in the removed workflow action (%s) to a "
                "fallback action (%s): %s",
                len(ids), target_activity.name, fallback_activity.name, ids
            )
            workflow_workitems.write(
                cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
            ) 
Example #14
Source File: openupgrade.py    From openupgradelib with GNU Affero General Public License v3.0 4 votes vote down vote up
def warn_possible_dataloss(cr, pool, old_module, fields):
    """
    Use that function in the following case:
    if a field of a model was moved from a 'A' module to a 'B' module.
    ('B' depend on 'A'),
    This function will test if 'B' is installed.
    If not, count the number of different value and possibly warn the user.
    Use orm, so call from the post script.

    :param old_module: name of the old module
    :param fields: list of dictionary with the following keys:
        'table' : name of the table where the field is.
        'field' : name of the field that are moving.
        'new_module' : name of the new module

    .. versionadded:: 7.0
    """
    module_obj = pool.get('ir.module.module')
    for field in fields:
        module_ids = module_obj.search(
            cr, SUPERUSER_ID, [
                ('name', '=', field['new_module']),
                ('state', 'in', ['installed', 'to upgrade', 'to install'])
            ])
        if not module_ids:
            cr.execute(
                "SELECT count(*) FROM (SELECT %s from %s group by %s) "
                "as tmp" % (
                    field['field'], field['table'], field['field']))
            row = cr.fetchone()
            if row[0] == 1:
                # not a problem, that field wasn't used.
                # Just a loss of functionality
                logger.info(
                    "Field '%s' from module '%s' was moved to module "
                    "'%s' which is not installed: "
                    "No dataloss detected, only loss of functionality"
                    % (field['field'], old_module, field['new_module']))
            else:
                # there is data loss after the migration.
                message(
                    cr, old_module, None, None,
                    "Field '%s' was moved to module "
                    "'%s' which is not installed: "
                    "There were %s distinct values in this field.",
                    field['field'], field['new_module'], row[0]) 
Example #15
Source File: openupgrade.py    From openupgradelib with GNU Affero General Public License v3.0 4 votes vote down vote up
def deactivate_workflow_transitions(cr, model, transitions=None):
    """
    Disable workflow transitions for workflows on a given model.
    This can be necessary for automatic workflow transitions when writing
    to an object via the ORM in the post migration step.
    Returns a dictionary to be used on reactivate_workflow_transitions

    :param model: the model for which workflow transitions should be \
    deactivated
    :param transitions: a list of ('module', 'name') xmlid tuples of \
    transitions to be deactivated. Don't pass this if there's no specific \
    reason to do so, the default is to deactivate all transitions

    .. versionadded:: 7.0
    """
    transition_ids = []
    if transitions:
        data_obj = registry.get(cr.dbname)['ir.model.data']
        for module, name in transitions:
            try:
                transition_ids.append(
                    data_obj.get_object_reference(
                        cr, SUPERUSER_ID, module, name)[1])
            except ValueError:
                continue
    else:
        cr.execute(
            '''select distinct t.id
            from wkf w
            join wkf_activity a on a.wkf_id=w.id
            join wkf_transition t
                on t.act_from=a.id or t.act_to=a.id
            where w.osv=%s''', (model,))
        transition_ids = [i for i, in cr.fetchall()]
    cr.execute(
        'select id, condition from wkf_transition where id in %s',
        (tuple(transition_ids),))
    transition_conditions = dict(cr.fetchall())
    cr.execute(
        "update wkf_transition set condition = 'False' WHERE id in %s",
        (tuple(transition_ids),))
    return transition_conditions