Esempio n. 1
0
 def create(self, vals):
     vals['state'] = 'done'
     rule = super(AuditRule, self).create(vals)
     rule.update_rule()
     if self._register_hook(rule.id):
         RegistryManager.signal_registry_change(self.env.cr.dbname)
     return rule
Esempio n. 2
0
 def _acquire_job(self, db_name, cleanup=False):
     import odoo.addons.base as base
     acquired = base.ir.ir_cron.ir_cron._acquire_job(db_name)
     if cleanup:
         RegistryManager.delete(db_name)
         close_db(db_name)
     return acquired
Esempio n. 3
0
def new_dump_db(db_name, stream, backup_format='zip', anonymized=True):
    if anonymized:
        with RegistryManager.new(db_name).cursor() as cr:
            env = api.Environment(cr, SUPERUSER_ID, {})
            anon_query = env['ir.model.fields'].get_anonymization_query()
        if not anon_query:
            db._logger.info("No data to anonymize in database `%s`.", db_name)
        else:
            db._logger.info('Anonymize and dump database `%s`.', db_name)
            anon_db_name = '%s_anon_%s' % (db_name,
                                           time.strftime('%Y%m%d_%H%M%S'))
            db.exp_duplicate_database(db_name, anon_db_name)
            try:
                if backup_format == 'zip':
                    # To avoid to archive filestore
                    # with non-anonymized attachments
                    anon_fs = tools.config.filestore(anon_db_name)
                    shutil.rmtree(anon_fs, ignore_errors=True)
                with RegistryManager.new(anon_db_name).cursor() as cr:
                    db._logger.info('ANONYMIZE DB: %s', anon_db_name)
                    cr.execute(anon_query)
            except Exception:
                db.exp_drop(anon_db_name)
            return NewDbDump(anon_db_name, stream, backup_format)
    return native_dump_db(db_name, stream, backup_format)
Esempio n. 4
0
    def session(self):
        """ Context Manager: start a new session and ensure that the
        session's cursor is:

        * rollbacked on errors
        * commited at the end of the ``with`` context when no error occured
        * always closed at the end of the ``with`` context
        * it handles the registry signaling
        """
        with odoo.api.Environment.manage():
            db = odoo.sql_db.db_connect(self.db_name)
            session = ConnectorSession(db.cursor(),
                                       self.uid,
                                       context=self.context)

            try:
                with session.env.clear_upon_failure():
                    RegistryManager.check_registry_signaling(self.db_name)
                    yield session
                    RegistryManager.signal_caches_change(self.db_name)
            except:
                session.rollback()
                raise
            else:
                session.commit()
            finally:
                session.close()
Esempio n. 5
0
 def _update_registry(self):
     """ Update the registry after a modification on action rules. """
     if self.env.registry.ready:
         # for the sake of simplicity, simply force the registry to reload
         self._cr.commit()
         self.env.reset()
         RegistryManager.new(self._cr.dbname)
         RegistryManager.signal_registry_change(self._cr.dbname)
Esempio n. 6
0
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)
Esempio n. 7
0
    def __init__(self, dbname, model_name, res_id, uid=0):
        assert isinstance(uid, (int, long)), 'uid should be an integer'
        self._logger = logging.getLogger('smile_log')

        db = RegistryManager.get(dbname)._db
        pid = 0

        try:
            cr = db.cursor()
            cr.autocommit(True)
            cr.execute(
                "select relname from pg_class where relname='smile_log_seq'")
            if not cr.rowcount:
                cr.execute("create sequence smile_log_seq")
            cr.execute("select nextval('smile_log_seq')")
            res = cr.fetchone()
            pid = res and res[0] or 0
        finally:
            cr.close()

        self._logger_start = datetime.datetime.now()
        self._logger_args = {
            'dbname': dbname,
            'model_name': model_name,
            'res_id': res_id,
            'uid': uid,
            'pid': pid
        }
Esempio n. 8
0
 def runtests():
     registry = RegistryManager.new(db_name)
     total = (registry._assertion_report.successes +
              registry._assertion_report.failures)
     failures = registry._assertion_report.failures
     logger.info("Completed (%s) tests. %s failures." % (total, failures))
     sys.exit(1 if failures else 0)
 def __enter__(self):
     """
     Context enter function.
     Temporarily add odoo 10 server path to system path and pop afterwards.
     Import odoo 10 server from path as library.
     Init logger, registry and environment.
     Add addons path to config.
     :returns Odoo10Context: This instance
     """
     sys.path.append(self.server_path)
     from odoo import netsvc, api
     from odoo.modules.registry import RegistryManager
     from odoo.tools import trans_export, config, trans_load_data
     self.trans_export = trans_export
     self.trans_load_data = trans_load_data
     sys.path.pop()
     netsvc.init_logger()
     config['addons_path'] = (
         config.get('addons_path') + ',' + self.addons_path
     )
     registry = RegistryManager.new(self.dbname)
     self.environment_manage = api.Environment.manage()
     self.environment_manage.__enter__()
     self.cr = registry.cursor()
     return self
 def _send_asset_to_sii(self):
     for asset in self.filtered(lambda a: a.state in ['validated']):
         company = asset.company_id
         wsdl = self.env['ir.config_parameter'].get_param(
             'l10n_es_aeat_sii.wsdl_pi', False)
         port_name = 'SuministroBienesInversion'
         if company.sii_test:
             port_name += 'Pruebas'
         client = self._connect_sii(wsdl)
         serv = client.bind('siiService', port_name)
         if asset.sii_state == 'not_sent':
             tipo_comunicacion = 'A0'
         else:
             tipo_comunicacion = 'A1'
         header = asset._get_sii_header(tipo_comunicacion)
         asset_vals = {
             'sii_header_sent': json.dumps(header, indent=4),
         }
         try:
             asset_dict = asset._get_sii_asset_dict()
             asset_vals['sii_content_sent'] = json.dumps(asset_dict,
                                                         indent=4)
             res = serv.SuministroLRBienesInversion(header, asset_dict)
             res_line = res['RespuestaLinea'][0]
             if res['EstadoEnvio'] == 'Correcto':
                 asset_vals.update({
                     'sii_state': 'sent',
                     'sii_csv': res['CSV'],
                     'sii_send_failed': False,
                 })
             elif res['EstadoEnvio'] == 'ParcialmenteCorrecto' and \
                     res_line['EstadoRegistro'] == 'AceptadoConErrores':
                 asset_vals.update({
                     'sii_state': 'sent_w_errors',
                     'sii_csv': res['CSV'],
                     'sii_send_failed': True,
                 })
             else:
                 asset_vals['sii_send_failed'] = True
             asset_vals['sii_return'] = res
             send_error = False
             if res_line['CodigoErrorRegistro']:
                 send_error = u"{} | {}".format(
                     unicode(res_line['CodigoErrorRegistro']),
                     unicode(res_line['DescripcionErrorRegistro'])[:60])
             asset_vals['sii_send_error'] = send_error
             asset.write(asset_vals)
         except Exception as fault:
             new_cr = RegistryManager.get(self.env.cr.dbname).cursor()
             env = api.Environment(new_cr, self.env.uid, self.env.context)
             asset = env['account.investment.assets'].browse(self.id)
             asset_vals.update({
                 'sii_send_failed': True,
                 'sii_send_error': fault,
                 'sii_return': fault,
             })
             asset.write(asset_vals)
             new_cr.commit()
             new_cr.close()
             raise
Esempio n. 11
0
 def import_data(self, f):
     with_error = False
     with api.Environment.manage():
         with RegistryManager.get(self.env.cr.dbname).cursor() as new_cr:
             new_env = api.Environment(new_cr, self.env.uid,
                                       self.env.context)
             #Se hace browse con un env diferente para guardar cambios
             doc_ = self.with_env(new_env).browse(self.id)
             try:
                 invoice_vals = {}
                 invoice_line_vals = {}
                 partner = False
                 for line in f.readlines():
                     line_type = line[14]
                     company_code = line[:6]
                     company = self.sudo().env["res.company"].\
                         search([('a3_company_code', '=', company_code)])
                     if line_type == "1":  # factura de venta
                         invoice_vals = doc_.import_invoice(line, company)
                     elif line_type == "2":  # factura rectificativa venta
                         invoice_vals = doc_.\
                             import_invoice(line, company, True)
                     elif line_type == "9":  # detalle de factura
                         invoice_line_vals = doc_.\
                             import_invoice_line(line, company)
                     elif line_type == "C":
                         partner = doc_.import_partner(line, company)
                     else:
                         raise exceptions.\
                             UserError(_("Line type %s has not a parser") %
                                       line_type)
                     if partner:
                         invoice_vals['partner_id'] = partner.id
                         invoice_vals['account_id'] = \
                             partner.property_account_receivable_id.id
                         invoice_vals['fiscal_position_id'] = \
                             partner.property_account_position_id.id
                         invoice_vals['payment_mode_id'] = \
                             partner.customer_payment_mode_id.id
                         invoice_vals['user_id'] = partner.user_id.id
                         invoice = self.with_env(new_env).\
                             env["account.invoice"].create(invoice_vals)
                         invoice_line_vals['invoice_id'] = invoice.id
                         self.with_env(new_env).\
                             env["account.invoice.line"].\
                             create(invoice_line_vals)
                         invoice.compute_taxes()
                         invoice.action_invoice_open()
                         invoice_vals = {}
                         invoice_line_vals = {}
                         partner = False
             except Exception as e:
                 self.errors = '\n%s' % str(e)
                 self.state = 'error'
                 new_env.cr.rollback()
                 with_error = True
             if not with_error:
                 self.state = 'imported'
                 new_env.cr.commit()
Esempio n. 12
0
 def _get_cursor(self, dbname):
     cr = self._dbname_to_cr.get(dbname)
     if not cr or (cr and cr.closed):
         db = RegistryManager.get(dbname)._db
         cr = db.cursor()
         cr.autocommit(True)
         self._dbname_to_cr[dbname] = cr
     return cr
Esempio n. 13
0
class ResFont(models.Model):
    _name = "res.font"
    _description = 'Fonts available'
    _order = 'family,name,id'
    _rec_name = 'family'

    family = fields.Char(string="Font family", required=True)
    name = fields.Char(string="Font Name", required=True)
    path = fields.Char(required=True)
    mode = fields.Char(required=True)

    _sql_constraints = [
        ('name_font_uniq', 'unique(family, name)', 'You can not register two fonts with the same name'),
    ]

    @api.model
    def font_scan(self, lazy=False):
        """Action of loading fonts
        In lazy mode will scan the filesystem only if there is no founts in the database and sync if no font in CustomTTFonts
        In not lazy mode will force scan filesystem and sync
        """
        if lazy:
            # lazy loading, scan only if no fonts in db
            fonts = self.search([('path', '!=', '/dev/null')])
            if not fonts:
                # no scan yet or no font found on the system, scan the filesystem
                self._scan_disk()
            elif len(customfonts.CustomTTFonts) == 0:
                # CustomTTFonts list is empty
                self._sync()
        else:
            self._scan_disk()
        return True

    def _scan_disk(self):
        """Scan the file system and register the result in database"""
        found_fonts = []
        for font_path in customfonts.list_all_sysfonts():
            try:
                font = ttfonts.TTFontFile(font_path)
                _logger.debug("Found font %s at %s", font.name, font_path)
                found_fonts.append((font.familyName, font.name, font_path, font.styleName))
            except Exception, ex:
                _logger.warning("Could not register Font %s: %s", font_path, ex)

        for family, name, path, mode in found_fonts:
            if not self.search([('family', '=', family), ('name', '=', name)]):
                self.create({'family': family, 'name': name, 'path': path, 'mode': mode})

        # remove fonts not present on the disk anymore
        existing_font_names = [name for (family, name, path, mode) in found_fonts]
        # Remove inexistent fonts
        self.search([('name', 'not in', existing_font_names), ('path', '!=', '/dev/null')]).unlink()

        RegistryManager.signal_caches_change(self._cr.dbname)
        return self._sync()
Esempio n. 14
0
def connect(dbname='trunk', uid=1, context=None):
    from odoo.modules.registry import RegistryManager
    from odoo.api import Environment
    r = RegistryManager.get(dbname)
    cr = r.cursor()
    Environment.reset()
    env = Environment(cr, uid, context or {})
    print('Connected to %s with user %s %s'
          % (dbname, env.uid, env.user.name))
    return env
Esempio n. 15
0
 def _update_models(self, models=None):
     update = False
     if not models:
         checklists = self.with_context(active_test=True).search([])
         models = {
             checklist.model_id: checklist
             for checklist in checklists
         }
     for model, checklist in models.iteritems():
         if model.model not in self.env.registry.models:
             continue
         if checklist:
             update |= self._patch_model_decoration(model.model)
         else:
             update |= self._revert_model_decoration(model.model)
     if update:
         if self.pool.ready:
             RegistryManager.signal_registry_change(self._cr.dbname)
         self.clear_caches()
Esempio n. 16
0
    def create(self, vals):
        if self._context and self._context.get('bve'):
            vals['state'] = 'base'
        res = super(IrModel, self).create(vals)

        # this sql update is necessary since a write method here would
        # be not working (an orm constraint is restricting the modification
        # of the state field while updating ir.model)
        q = "UPDATE ir_model SET state = 'manual' WHERE id = %s"
        self.env.cr.execute(q, (res.id, ))

        # # update registry
        if self._context.get('bve'):
            # setup models; this reloads custom models in registry
            self.pool.setup_models(self._cr, partial=(not self.pool.ready))

            # signal that registry has changed
            RegistryManager.signal_registry_change(self.env.cr.dbname)

        return res
Esempio n. 17
0
def newdbuuid(ctx, db_name):
    config = (
        ctx.obj['config']
    )

    from odoo.modules.registry import RegistryManager
    from odooku.api import environment

    registry = RegistryManager.get(db_name)
    with registry.cursor() as cr:
        with environment(cr) as env:
            env['ir.config_parameter'].init(force=True)
Esempio n. 18
0
    def setUp(self):
        super(TestAdvisoryLock, self).setUp()
        self.registry2 = RegistryManager.get(common.get_db_name())
        self.cr2 = self.registry2.cursor()
        self.env2 = api.Environment(self.cr2, self.env.uid, {})

        @self.addCleanup
        def reset_cr2():
            # rollback and close the cursor, and reset the environments
            self.env2.reset()
            self.cr2.rollback()
            self.cr2.close()
Esempio n. 19
0
def authenticate(token):
    try:
        a = 4 - len(token) % 4
        if a != 0:
            token += '==' if a == 2 else '='
        SERVER,db,login,uid,ts = base64.urlsafe_b64decode(str(token)).split(',')
        if int(ts) + 60*60*24*7*10 < time.time():
            return False
        registry = RegistryManager.get(db)
        cr = registry.cursor()
        env = api.Environment(cr, int(uid), {})
    except Exception,e:
        return str(e)
Esempio n. 20
0
def shell(ctx, input_file, db_name):
    from odoo.modules.registry import RegistryManager
    from odooku.api import environment
    registry = RegistryManager.get(db_name)

    with registry.cursor() as cr:
        with environment(cr) as env:
            context = {'env': env, 'self': env.user}

            args = []
            if input_file is not None:
                args = [input_file]

            bpython.embed(context, args=args, banner='Odooku shell')
Esempio n. 21
0
def authenticate(token):
    try:
        a = 4 - len(token) % 4
        if a != 0:
            token += '==' if a == 2 else '='
        SERVER, db, login, uid, ts = base64.urlsafe_b64decode(
            str(token)).split(',')
        if int(ts) + 60 * 60 * 24 * 7 * 10 < time.time():
            return False
        registry = RegistryManager.get(db)
        cr = registry.cursor()
        env = api.Environment(cr, int(uid), {})
    except Exception, e:
        return str(e)
Esempio n. 22
0
def import_(ctx, db_name, fake, strict, config_file):
    config = (ctx.obj['config'])

    from odoo.modules.registry import RegistryManager
    registry = RegistryManager.get(db_name)
    from odooku_data.importer import Importer
    from odooku_data.config import DataConfig
    importer = Importer(
        registry,
        config=config_file and DataConfig.from_file(config_file)
        or DataConfig.defaults(),
        strict=strict,
    )
    importer.import_(sys.stdin, fake=fake)
Esempio n. 23
0
    def db_list(self):
        db_list = http.db_list() or []
        db_list_by_mobile = []
        for db in db_list:
            db_manager = RegistryManager.get(db)
            with closing(db_manager.cursor()) as cr:
                cr.execute('''
                           SELECT id FROM ir_module_module
                           WHERE state = 'installed' AND name = 'mobile'
                           ''')
                if cr.fetchall():
                    db_list_by_mobile.append(db)

        return db_list_by_mobile
Esempio n. 24
0
def preload(ctx, db_name, module, demo_data):
    config = (
        ctx.obj['config']
    )

    from odoo.modules.registry import RegistryManager

    if module:
        modules = {
            module_name: 1
            for module_name in module
        }
        config['init'] = dict(modules)

    registry = RegistryManager.new(db_name, force_demo=demo_data, update_module=True)
Esempio n. 25
0
def update(ctx, db_name, module):
    config = (
        ctx.obj['config']
    )

    from odoo.modules.registry import RegistryManager

    module = module or ['all']
    modules = {
        module_name: 1
        for module_name in module
    }

    config['update'] = dict(modules)
    for db in db_name:
        registry = RegistryManager.new(db, update_module=True)
Esempio n. 26
0
def export(ctx, db_name, strict, link, config_file=None):
    config = (ctx.obj['config'])

    from odoo.modules.registry import RegistryManager
    registry = RegistryManager.get(db_name)

    from odooku_data.exporter import factory
    from odooku_data.config import DataConfig
    exporter = factory()(
        registry,
        config=config_file and DataConfig.from_file(config_file)
        or DataConfig.defaults(),
        link=link,
        strict=strict,
    )
    exporter.export(sys.stdout)
Esempio n. 27
0
 def signin(self, **kw):
     kw = simplejson.loads(simplejson.dumps(kw).replace('+', ''))
     state = simplejson.loads(kw['state'])
     dbname = state['d']
     provider = state['p']
     context = state.get('c', {})
     registry = RegistryManager.get(dbname)
     with registry.cursor() as cr:
         try:
             env = api.Environment(cr, SUPERUSER_ID, context)
             credentials = env['res.users'].sudo().auth_oauth(provider, kw)
             print credentials
             # u = registry.get('res.users')
             # credentials = u.auth_oauth(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
             return login_and_redirect(*credentials, redirect_url=url)
         except AttributeError:
             # 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 odoo.exceptions.AccessDenied:
             # 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, e:
             # signup error
             _logger.exception("OAuth2: %s" % str(e))
             url = "/web/login?oauth_error=2"
Esempio n. 28
0
    def setUp(self):
        super(TestConcurrentSync, self).setUp()
        self.registry2 = RegistryManager.get(common.get_db_name())
        self.cr2 = self.registry2.cursor()
        self.env2 = api.Environment(self.cr2, self.env.uid, {})

        @self.addCleanup
        def reset_cr2():
            # rollback and close the cursor, and reset the environments
            self.env2.reset()
            self.cr2.rollback()
            self.cr2.close()

        backend2 = mock.MagicMock(name='Backend Record')
        backend2._name = 'magento.backend'
        backend2.id = self.backend.id
        backend2.env = self.env2
        self.backend2 = backend2
Esempio n. 29
0
    def login(self, db_choose=''):
        db_list = http.db_list() or []
        db_list_by_mobile = []
        for db in db_list:
            db_manager = RegistryManager.get(db)
            with closing(db_manager.cursor()) as cr:
                cr.execute('''
                           SELECT id FROM ir_module_module
                           WHERE state = 'installed' AND name = 'mobile'
                           ''')
                if cr.fetchall():
                    db_list_by_mobile.append(db)

        template = env.get_template('login.html')
        return template.render({
            'db_list': db_list_by_mobile,
            'db_choose': db_choose
        })
Esempio n. 30
0
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)
Esempio n. 31
0
def update(ctx, db_name, module, language, overwrite):
    context = {
        'overwrite': overwrite
    }

    from odoo.modules.registry import RegistryManager
    from odooku.api import environment

    domain = [('state', '=', 'installed')]
    if module:
        domain = [('name', 'in', module)]


    for db in db_name:
        registry = RegistryManager.get(db)
        with registry.cursor() as cr:
            with environment(cr) as env:
                mods = env['ir.module.module'].search(domain)
                mods.with_context(overwrite=overwrite).update_translations(language)
Esempio n. 32
0
    def _send_simplified_to_sii(self):
        for order in self.filtered(lambda i: i.state in ['done', 'paid']):
            wsdl = self.env['ir.config_parameter'].get_param(
                'l10n_es_aeat_sii.wsdl_out', False)
            port_name = 'SuministroFactEmitidas'
            if not order.sii_sent:
                tipo_comunicacion = 'A0'
            else:
                tipo_comunicacion = 'A1'
            header = order._get_header(tipo_comunicacion)
            try:
                orders = order._get_simplified()
            except Exception as fault:
                new_cr = RegistryManager.get(self.env.cr.dbname).cursor()
                env = api.Environment(new_cr, self.env.uid, self.env.context)
                self.with_env(env).sii_send_error = fault
                new_cr.commit()
                new_cr.close()
                raise

            try:
                serv = order._connect_wsdl(wsdl, port_name)
                res = serv.SuministroLRFacturasEmitidas(
                    header, orders)
                if res['EstadoEnvio'] in ['Correcto', 'ParcialmenteCorrecto']:
                    self.sii_sent = True
                    self.sii_csv = res['CSV']
                else:
                    self.sii_sent = False
                self.env['aeat.sii.result'].create_result(
                    order, res, 'normal', False, 'pos.order')
                send_error = False
                res_line = res['RespuestaLinea'][0]
                if res_line['CodigoErrorRegistro']:
                    send_error = u"{} | {}".format(
                        unicode(res_line['CodigoErrorRegistro']),
                        unicode(res_line['DescripcionErrorRegistro'])[:60])
                self.sii_send_error = send_error
            except Exception as fault:
                self.env['aeat.sii.result'].create_result(
                    order, False, 'normal', fault, 'pos.order')
                self.sii_send_error = fault
def migrate(cr, version):
    registry = RegistryManager.get(cr.dbname)
    from odoo.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable
    migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_cl')
def migrate(cr, version):
    registry = RegistryManager.get(cr.dbname)
    from odoo.addons.account.models.chart_template import migrate_tags_on_taxes
    migrate_tags_on_taxes(cr, registry)