Пример #1
0
    def generate(self):
        """ Main wizard step. Make sure that all modules are up-to-date,
        then reinitialize all installed modules.
        Equivalent of running the server with '-d <database> --init all'

        The goal of this is to fill the records table.

        TODO: update module list and versions, then update all modules? """
        # Truncate the records table
        if (openupgrade_tools.table_exists(
            self.env.cr, 'openupgrade_attribute') and
                openupgrade_tools.table_exists(
                    self.env.cr, 'openupgrade_record')):
            self.env.cr.execute(
                'TRUNCATE openupgrade_attribute, openupgrade_record;'
                )

        # Need to get all modules in state 'installed'
        modules = self.env['ir.module.module'].search(
            [('state', 'in', ['to install', 'to upgrade'])])
        if modules:
            self.env.cr.commit()
            Registry.new(self.env.cr.dbname, update_module=True)
        # Did we succeed above?
        modules = self.env['ir.module.module'].search(
            [('state', 'in', ['to install', 'to upgrade'])])
        if modules:
            raise UserError(
                "Cannot seem to install or upgrade modules %s" % (
                    ', '.join([module.name for module in modules])))
        # Now reinitialize all installed modules
        self.env['ir.module.module'].search(
            [('state', '=', 'installed')]).write(
                {'state': 'to install'})
        self.env.cr.commit()
        Registry.new(self.env.cr.dbname, update_module=True)

        # Set noupdate property from ir_model_data
        self.env.cr.execute(
            """ UPDATE openupgrade_record our
            SET noupdate = imd.noupdate
            FROM ir_model_data imd
            WHERE our.type = 'xmlid'
                AND our.model = imd.model
                AND our.name = imd.module || '.' || imd.name
            """)
        self.env.invalidate([
            (self.env['openupgrade.record']._fields['noupdate'], None),
        ])
        return self.write({'state': 'ready'})
Пример #2
0
def post_init_hook(cr, registry):
    """Loaded after installing the module.
    This module's DB modifications will be available.
    :param odoo.sql_db.Cursor cr:
        Database cursor.
    :param odoo.modules.registry.RegistryManager registry:
        Database registry, using v7 api.
    """
    # we don not force dependency on openupgradelib, only if available we try
    # o un de hook
    if not table_exists:
        return False
    # write en vez de sql para que genere los campos por defecto necesarios
    query = (
        "SELECT aj.id, apos.number, apos.document_sequence_type, apos.type "
        "FROM account_journal aj INNER JOIN afip_point_of_sale apos "
        "ON aj.point_of_sale_id = apos.id")
    if table_exists(cr, 'afip_point_of_sale'):
        cr.execute(query)
        for journal_id, number, document_sequence_type, type in cr.fetchall():
            registry['account.journal'].write(
                cr, 1, [journal_id], {
                    'point_of_sale_type': type,
                    'point_of_sale_number': number,
                    'document_sequence_type': document_sequence_type,
                })
def compare_registries(cr, module, registry, local_registry):
    """
    OpenUpgrade: Compare the local registry with the global registry,
    log any differences and merge the local registry with
    the global one.
    """
    if not table_exists(cr, 'openupgrade_record'):
        return
    for model, flds in local_registry.items():
        registry.setdefault(model, {})
        for field, attributes in flds.items():
            old_field = registry[model].setdefault(field, {})
            mode = old_field and 'modify' or 'create'
            record_id = False
            for key, value in attributes.items():
                if key not in old_field or old_field[key] != value:
                    if not record_id:
                        record_id = get_record_id(cr, module, model, field,
                                                  mode)
                    cr.execute(
                        "SELECT id FROM openupgrade_attribute "
                        "WHERE name = %s AND value = %s AND "
                        "record_id = %s", (key, value, record_id))
                    if not cr.fetchone():
                        cr.execute(
                            "INSERT INTO openupgrade_attribute "
                            "(name, value, record_id) VALUES (%s, %s, %s)",
                            (key, value, record_id))
                    old_field[key] = value
Пример #4
0
def migrate_model_tables(cr):
    if table_exists(cr, 'ir_model') and not column_exists(
            cr, 'ir_model', 'transient'):
        # ir_model needs to be updated
        cr.execute("""ALTER TABLE ir_model
                      ADD COLUMN transient boolean
                      """)

        # we assume ir_model_fields needs fixing too
        cr.execute("""ALTER TABLE ir_model_fields
                      ADD COLUMN help varchar,
                      ADD COLUMN index boolean,
                      ADD COLUMN copy boolean,
                      ADD COLUMN related varchar,
                      ADD COLUMN relation_table varchar,
                      ADD COLUMN column1 varchar,
                      ADD COLUMN column2 varchar,
                      ALTER COLUMN select_level SET DEFAULT '0'
                      """)

        # ir_model needs to be updated
        cr.execute("""ALTER TABLE ir_model_constraint
                      ADD COLUMN definition varchar
                      """)

        cr.commit()
Пример #5
0
def log_xml_id(cr, module, xml_id):
    """
    Log xml_ids at load time in the records table.
    Called from tools/convert.py:xml_import._test_xml_id()

    # Catcha's
    - The module needs to be loaded with 'init', or the calling method
    won't be called. This can be brought about by installing the
    module or updating the 'state' field of the module to 'to install'
    or call the server with '--init <module>' and the database argument.

    - Do you get the right results immediately when installing the module?
    No, sorry. This method retrieves the model from the ir_model_table, but
    when the xml id is encountered for the first time, this method is called
    before the item is present in this table. Therefore, you will not
    get any meaningful results until the *second* time that you 'init'
    the module.

    - The good news is that the upgrade_analysis module that comes
    with this distribution allows you to deal with all of this with
    one click on the menu item Settings -> Customizations ->
    Database Structure -> OpenUpgrade -> Generate Records

    - You cannot reinitialize the modules in your production database
    and expect to keep working on it happily ever after. Do not perform
    this routine on your production database.

    :param module: The module that contains the xml_id
    :param xml_id: the xml_id, with or without 'module.' prefix
    """
    if not table_exists(cr, "upgrade_record"):
        return
    if "." not in xml_id:
        xml_id = "{}.{}".format(module, xml_id)
    cr.execute(
        "SELECT model FROM ir_model_data "
        "WHERE module = %s AND name = %s",
        xml_id.split("."),
    )
    record = cr.fetchone()
    if not record:
        _logger.warning("Cannot find xml_id %s", xml_id)
        return
    else:
        cr.execute(
            "SELECT id FROM upgrade_record "
            "WHERE module=%s AND model=%s AND name=%s AND type=%s",
            (module, record[0], xml_id, "xmlid"),
        )
        if not cr.fetchone():
            cr.execute(
                "INSERT INTO upgrade_record "
                "(create_date, module, model, name, type) "
                "values(NOW() AT TIME ZONE 'UTC', %s, %s, %s, %s)",
                (module, record[0], xml_id, "xmlid"),
            )
Пример #6
0
    def generate(self, cr, uid, ids, context=None):
        """
        Main wizard step. Make sure that all modules are up-to-date,
        then reinitialize all installed modules.
        Equivalent of running the server with '-d <database> --init all'

        The goal of this is to fill the records table.

        TODO: update module list and versions, then update all modules?
        """
        # Truncate the records table
        if (openupgrade_tools.table_exists(cr, 'openupgrade_attribute')
                and openupgrade_tools.table_exists(cr, 'openupgrade_record')):
            cr.execute('TRUNCATE openupgrade_attribute, openupgrade_record;')

        # Need to get all modules in state 'installed'
        module_obj = self.pool.get('ir.module.module')
        module_ids = module_obj.search(
            cr, uid, [('state', 'in', ['to install', 'to upgrade'])])
        if module_ids:
            cr.commit()
            _db, pool = pooler.restart_pool(cr.dbname, update_module=True)
        # Did we succeed above?
        module_ids = module_obj.search(
            cr, uid, [('state', 'in', ['to install', 'to upgrade'])])
        if module_ids:
            modules = module_obj.read(cr,
                                      uid,
                                      module_ids, ['name'],
                                      context=context)
            raise except_orm("Cannot reliably generate records",
                             ("Cannot seem to install or upgrade modules " +
                              ', '.join([x['name'] for x in modules])))
        # Now reinitialize all installed modules
        module_ids = module_obj.search(cr, uid, [('state', '=', 'installed')])
        module_obj.write(cr, uid, module_ids, {'state': 'to install'})
        self.quirk_payment_term_lines(cr, uid, context=context)
        cr.commit()
        _db, pool = pooler.restart_pool(cr.dbname, update_module=True)
        self.write(cr, uid, ids, {'state': 'ready'})
        # and we are done
        return True
Пример #7
0
def post_init_hook(cr, registry):
    """Loaded after installing the module.
    This module's DB modifications will be available.
    :param odoo.sql_db.Cursor cr:
        Database cursor.
    :param odoo.modules.registry.Registry registry:
        Database registry, using v7 api.
    """
    _logger.info('running payment')

    if table_exists and table_exists(cr, 'account_voucher_copy'):
        restore_canceled_payments_state(cr, registry)

    payment_ids = registry['account.payment'].search(
        cr, 1, [('payment_type', '!=', 'transfer')])

    for payment in registry['account.payment'].browse(cr, 1, payment_ids):

        _logger.info('creating payment group for payment %s' % payment.id)
        registry['account.payment.group'].create(
            cr,
            1,
            {
                'company_id':
                payment.company_id.id,
                'partner_type':
                payment.partner_type,
                'partner_id':
                payment.partner_id.id,
                'payment_date':
                payment.payment_date,
                # en realidad aparentemente odoo no migra nada a communication
                # tal vez a este campo deberíamos llevar el viejo name que ahora
                # name es la secuencia
                'communication':
                payment.communication,
                'payment_ids': [(4, payment.id, False)],
                'state': (payment.state in ['sent', 'reconciled'] and 'posted'
                          or payment.state),
            })

    if column_exists and column_exists(cr, 'res_company', 'double_validation'):
        field = 'field_res_company_double_validation'
        xmlid_renames = [
            ('account_voucher_double_validation.%s' % field,
             'account_payment_group.%s' % field),
        ]
        openupgrade.rename_xmlids(cr, xmlid_renames)

    set_user_group_for_double_validation(cr, registry)
    def generate(self):
        """ Main wizard step. Make sure that all modules are up-to-date,
        then reinitialize all installed modules.
        Equivalent of running the server with '-d <database> --init all'

        The goal of this is to fill the records table.

        TODO: update module list and versions, then update all modules? """
        # Truncate the records table
        if (openupgrade_tools.table_exists(self.env.cr,
                                           'openupgrade_attribute')
                and openupgrade_tools.table_exists(self.env.cr,
                                                   'openupgrade_record')):
            self.env.cr.execute(
                'TRUNCATE openupgrade_attribute, openupgrade_record;')

        # Need to get all modules in state 'installed'
        modules = self.env['ir.module.module'].search([
            ('state', 'in', ['to install', 'to upgrade'])
        ])
        if modules:
            self.env.cr.commit()
            Registry.new(self.env.cr.dbname, update_module=True)
        # Did we succeed above?
        modules = self.env['ir.module.module'].search([
            ('state', 'in', ['to install', 'to upgrade'])
        ])
        if modules:
            raise UserError("Cannot seem to install or upgrade modules %s" %
                            (', '.join([module.name for module in modules])))
        # Now reinitialize all installed modules
        self.env['ir.module.module'].search([('state', '=', 'installed')
                                             ]).write({'state': 'to install'})
        self.env.cr.commit()
        Registry.new(self.env.cr.dbname, update_module=True)
        return self.write({'state': 'ready'})
Пример #9
0
def post_init_hook(cr, registry):
    """Loaded after installing the module.
    This module's DB modifications will be available.
    :param openerp.sql_db.Cursor cr:
        Database cursor.
    :param openerp.modules.registry.RegistryManager registry:
        Database registry, using v7 api.
    """
    ar_invoice_ids = registry['account.invoice'].search(
        cr, 1, [('localization', '=', 'argentina')])
    for invoice_id in ar_invoice_ids:
        vals = registry['account.invoice'].get_localization_invoice_vals(
            cr, 1, invoice_id)
        registry['account.invoice'].write(
            cr, 1, invoice_id, {'currency_rate': vals.get('currency_rate')})

    # we don not force dependency on openupgradelib, only if available we try
    # o un de hook
    if not table_exists:
        return False
    # write en vez de sql para que genere los campos por defecto necesarios
    # we where using this but we decide to make it easier and change on v8
    # using related fields
    # query = (
    #     "SELECT aj.id, apos.number, apos.document_sequence_type, apos.type "
    #     "FROM account_journal aj INNER JOIN afip_point_of_sale apos "
    #     "ON aj.point_of_sale_id = apos.id")
    # if table_exists(cr, 'afip_point_of_sale'):
    #     cr.execute(query)
    #     for journal_id, number, doc_sequence_type, type in cr.fetchall():
    #         registry['account.journal'].write(cr, 1, [journal_id], {
    #             'point_of_sale_type': type,
    #             'point_of_sale_number': number,
    #             'document_sequence_type': doc_sequence_type,
    #         })

    # TODO choose:
    # odoo migration delete vouchers that where moved to payments so we make
    # a copy of voucher table and get data from thisone. Beacuse
    # account_payment ids and account_voucher ids does not match, we search
    # by move_id
    if table_exists(cr, 'account_voucher_copy'):
        for payment_id in registry['account.payment'].search(cr, 1, []):
            move_ids = registry['account.move'].search(
                cr, 1, [('line_ids.payment_id', '=', payment_id)], limit=1)
            if not move_ids:
                continue
            cr.execute(
                """
                SELECT receiptbook_id, afip_document_number
                FROM account_voucher_copy
                WHERE move_id = %s
                """, (move_ids[0], ))
            recs = cr.fetchall()
            if recs:
                receiptbook_id, document_number = recs[0]
                registry['account.payment'].write(
                    cr, 1, [payment_id], {
                        'receiptbook_id': receiptbook_id,
                        'document_number': document_number,
                    })

    # este era el script para openupgrade
    # if table_exists(cr, 'account_voucher'):
    #     for payment_id in registry['account.payment'].search(cr, 1, []):
    #         cr.execute("""
    #             SELECT receiptbook_id, afip_document_number
    #             FROM account_voucher
    #             WHERE id = %s
    #             """, (payment_id,))
    #         recs = cr.fetchall()
    #         if recs:
    #             receiptbook_id, document_number = recs[0]
    #             registry['account.payment'].write(cr, 1, [payment_id], {
    #                 'receiptbook_id': receiptbook_id,
    #                 'document_number': document_number,
    #             })
    merge_refund_journals_to_normal(cr, registry)
    map_tax_groups_to_taxes(cr, registry)
Пример #10
0
def post_init_hook(cr, registry):
    """Loaded after installing the module.
    This module's DB modifications will be available.
    :param openerp.sql_db.Cursor cr:
        Database cursor.
    :param openerp.modules.registry.RegistryManager registry:
        Database registry, using v7 api.
    """
    _logger.info('Post init hook initialized')

    document_types_not_updatable(cr, registry)
    sync_padron_afip(cr, registry)

    # we don not force dependency on openupgradelib, only if available we try
    # o un de hook
    if not table_exists:
        return False

    # TODO choose:
    # odoo migration delete vouchers that where moved to payments so we make
    # a copy of voucher table and get data from thisone. Beacuse
    # account_payment ids and account_voucher ids does not match, we search
    # by move_id
    advance_column = column_exists(cr, 'account_voucher_copy',
                                   'advance_amount')
    if advance_column:
        sql = """
                SELECT receiptbook_id, afip_document_number, advance_amount
                FROM account_voucher_copy
                WHERE move_id = %s
                """
    else:
        sql = """
                SELECT receiptbook_id, afip_document_number
                FROM account_voucher_copy
                WHERE move_id = %s
                """
    if table_exists(cr, 'account_voucher_copy'):
        _logger.info('Migrating vouchers data')
        for payment_id in registry['account.payment'].search(cr, 1, []):
            _logger.info('Migrating vouchers data for payment %s' % payment_id)
            move_ids = registry['account.move'].search(
                cr, 1, [('line_ids.payment_id', '=', payment_id)], limit=1)
            if not move_ids:
                continue
            cr.execute(sql, (move_ids[0], ))
            recs = cr.fetchall()
            if recs:
                # steamos el advance_amount aunque sea para los pagos que
                # fueron validados
                if advance_column:
                    receiptbook_id, document_number, advance_amount = recs[0]
                    registry['account.payment'].write(
                        cr,
                        1,
                        [payment_id],
                        {
                            'receiptbook_id': receiptbook_id,
                            'document_number': document_number,
                            # no lo hacemos aca porque este campo es de
                            # payment.group y el payment group probablemente no
                            # existe en este momento, lo hacemos en l10 withholding
                            # 'unreconciled_amount': advance_amount,
                        })
                else:
                    receiptbook_id, document_number = recs[0]
                    registry['account.payment'].write(
                        cr, 1, [payment_id], {
                            'receiptbook_id': receiptbook_id,
                            'document_number': document_number,
                        })

    # forma horrible de saber si se esta instalando en una bd que viene migrada
    # despues de hacer esto aprendimos a usar el no_version en migrates
    # pero que en realidad tampoco nos anduvo
    env = Environment(cr, 1, {})
    if openupgrade.column_exists(cr, 'account_journal', 'old_type'):
        set_company_loc_ar(cr)
        merge_padron_into_account(cr)
        migrate_responsability_type(env)
        fix_invoice_without_date(env)
        merge_refund_journals_to_normal(env)
        map_tax_groups_to_taxes(cr, registry)

        _logger.info('Getting currency rate for invoices')
        ar_invoice_ids = registry['account.invoice'].search(
            cr, 1, [('localization', '=', 'argentina')])
        for invoice_id in ar_invoice_ids:
            vals = registry['account.invoice'].get_localization_invoice_vals(
                cr, 1, invoice_id)
            registry['account.invoice'].write(
                cr, 1, invoice_id,
                {'currency_rate': vals.get('currency_rate')})
Пример #11
0
    def generate(self):
        """ Main wizard step. Make sure that all modules are up-to-date,
        then reinitialize all installed modules.
        Equivalent of running the server with '-d <database> --init all'

        The goal of this is to fill the records table.

        TODO: update module list and versions, then update all modules? """
        # Truncate the records table
        if (openupgrade_tools.table_exists(self.env.cr,
                                           'openupgrade_attribute')
                and openupgrade_tools.table_exists(self.env.cr,
                                                   'openupgrade_record')):
            self.env.cr.execute(
                'TRUNCATE openupgrade_attribute, openupgrade_record;')

        # Run any quirks
        self.quirk_standard_calendar_attendances()

        # Need to get all modules in state 'installed'
        modules = self.env['ir.module.module'].search([
            ('state', 'in', ['to install', 'to upgrade'])
        ])
        if modules:
            self.env.cr.commit()
            Registry.new(self.env.cr.dbname, update_module=True)
        # Did we succeed above?
        modules = self.env['ir.module.module'].search([
            ('state', 'in', ['to install', 'to upgrade'])
        ])
        if modules:
            raise UserError("Cannot seem to install or upgrade modules %s" %
                            (', '.join([module.name for module in modules])))
        # Now reinitialize all installed modules
        self.env['ir.module.module'].search([('state', '=', 'installed')
                                             ]).write({'state': 'to install'})
        self.env.cr.commit()
        Registry.new(self.env.cr.dbname, update_module=True)

        # Set domain property
        self.env.cr.execute(""" UPDATE openupgrade_record our
            SET domain = iaw.domain
            FROM ir_model_data imd
            JOIN ir_act_window iaw ON imd.res_id = iaw.id
            WHERE our.type = 'xmlid'
                AND imd.model = 'ir.actions.act_window'
                AND our.model = imd.model
                AND our.name = imd.module || '.' || imd.name
            """)
        self.env.cache.invalidate([
            (self.env['openupgrade.record']._fields['domain'], None),
        ])

        # Set noupdate property from ir_model_data
        self.env.cr.execute(""" UPDATE openupgrade_record our
            SET noupdate = imd.noupdate
            FROM ir_model_data imd
            WHERE our.type = 'xmlid'
                AND our.model = imd.model
                AND our.name = imd.module || '.' || imd.name
            """)
        self.env.cache.invalidate([
            (self.env['openupgrade.record']._fields['noupdate'], None),
        ])

        # Log model records
        self.env.cr.execute(
            """INSERT INTO openupgrade_record
            (module, name, model, type)
            SELECT imd2.module, imd2.module || '.' || imd.name AS name,
                im.model, 'model' AS type
            FROM (
                SELECT min(id) as id, name, res_id
                FROM ir_model_data
                WHERE name LIKE 'model_%' AND model = 'ir.model'
                GROUP BY name, res_id
                ) imd
            JOIN ir_model_data imd2 ON imd2.id = imd.id
            JOIN ir_model im ON imd.res_id = im.id
            ORDER BY imd.name, imd.id""", )

        return self.write({'state': 'ready'})