def migrate(env, version): if not version: return # Install dependency openupgrade.logged_query(env.cr, """ UPDATE ir_module_module SET state='to install' WHERE name = 'child_switzerland' AND state='uninstalled'; """)
def migrate(env, version): if not version: return cr = env.cr # Install dependency openupgrade.logged_query(cr, """ UPDATE ir_module_module SET state='to install' WHERE name = 'account_payment_mode' AND state='uninstalled'; """)
def migrate(env, version): if not version: return cr = env.cr # Install dependency openupgrade.logged_query(cr, """ UPDATE ir_module_module SET state='to install' WHERE name = 'account_statement_completion' AND state='uninstalled'; """) # Inactive old payment modes openupgrade.logged_query(cr, """ UPDATE account_payment_mode SET active = false; """) # Configure journals openupgrade.logged_query(cr, """ INSERT INTO account_journal_inbound_payment_method_rel (journal_id, inbound_payment_method) VALUES (219, (SELECT id FROM account_payment_method WHERE code = 'lsv')), (212, (SELECT id FROM account_payment_method WHERE code = 'sepa.ch.dd')) """)
def migrate(env, version): cr = env.cr cr.execute(""" SELECT column_name FROM information_schema.columns WHERE table_name='account_analytic_account' AND column_name='user_id' """) if not cr.fetchone(): openupgrade.logged_query( env.cr, """ ALTER TABLE account_analytic_account ADD COLUMN user_id integer; """) openupgrade.logged_query( env.cr, """ UPDATE account_analytic_account aa SET user_id = (SELECT user_id FROM res_partner p WHERE p.id = aa.partner_id AND user_id IS NOT NULL) WHERE user_id IS NULL; """)
def migrate(cr, version): cr.execute("alter table crm_claim_category add column lead_tag_id int") cr.execute("insert into crm_claim_category (name, team_id, lead_tag_id) " "select t.name, t.team_id, t.id " "from crm_lead_tag t " "join ir_model m on t.object_id=m.id and m.model='crm.claim'") cr.execute( "update crm_claim c set categ_id=cc.id " "from crm_claim_category cc where c.%(categ_id)s=cc.lead_tag_id", { 'categ_id': AsIs(openupgrade.get_legacy_name('categ_id')), }) openupgrade.logged_query( cr, "UPDATE ir_model_data imd " "SET res_id = ccc.id, model = 'crm.claim.category' " "FROM crm_claim_category ccc " "WHERE res_id = ccc.lead_tag_id " "AND module = 'crm_claim' " "AND imd.name LIKE 'categ_claim%%'") openupgrade.load_data( cr, 'crm_claim', 'migrations/9.0.1.0/noupdate_changes.xml', )
def subscribe_new_subtypes(env): """Subscribe to the new subtypes to those that were subscribed to the old ones. """ subtype_mapping = [ ('mt_department_holidays_approved', [ 'mt_department_leave_allocation_approved', 'mt_department_leave_approved' ]), ('mt_department_holidays_refused', [ 'mt_department_leave_allocation_refused', 'mt_department_leave_refused' ]), ('mt_holidays_approved', ['mt_leave_allocation_approved', 'mt_leave_approved']), ('mt_holidays_refused', ['mt_leave_allocation_refused', 'mt_leave_refused']), ] for old, new in subtype_mapping: old_id = env.ref('hr_holidays.' + old).id for i, model in enumerate(['hr.leave.allocation', 'hr.leave']): new_id = env.ref('hr_holidays.' + new[i]).id openupgrade.logged_query( env.cr, """ UPDATE mail_followers_mail_message_subtype_rel rel SET mail_message_subtype_id = %s FROM mail_followers mf, mail_message_subtype mms WHERE mf.id = rel.mail_followers_id AND mms.id = rel.mail_message_subtype_id AND mms.res_model = 'hr.holidays' AND mf.res_model = %s AND rel.mail_message_subtype_id = %s """, ( new_id, model, old_id, ))
def fill_pos_order_amounts(env): """Avoid null values in required fields.""" openupgrade.logged_query( env.cr, """ UPDATE pos_order po SET amount_paid = tmp.amount_paid, amount_return = tmp.amount_return FROM ( SELECT po.id, sum(absl.amount) AS amount_paid, sum(LEAST(absl.amount, 0)) AS amount_return FROM pos_order po INNER JOIN account_bank_statement_line absl ON absl.pos_statement_id = po.id GROUP BY po.id ) AS tmp WHERE po.id = tmp.id; """) openupgrade.logged_query( env.cr, """ UPDATE pos_order po SET amount_total = tmp.amount_total, amount_tax = tmp.amount_total - tmp.amount_untaxed FROM ( SELECT po.id, sum(pol.price_subtotal_incl) AS amount_total, sum(pol.price_subtotal) AS amount_untaxed FROM pos_order po INNER JOIN pos_order_line pol ON pol.order_id = po.id GROUP BY po.id ) AS tmp WHERE po.id = tmp.id; """)
def fill_sale_order_template_line_sections(cr): """It's done here instead of post-migration to avoid possible new rows added in the migration""" cr.execute( "ALTER TABLE sale_order_template_line ADD COLUMN display_type varchar", ) openupgrade.logged_query( cr, """ UPDATE sale_order_template_line sotl SET sequence = sub.rank * 5 FROM ( SELECT id, rank() OVER ( PARTITION BY sale_order_template_id ORDER BY sequence, id ) FROM sale_order_template_line ) sub WHERE sotl.id = sub.id """, ) openupgrade.logged_query( cr, """ ALTER TABLE sale_order_template_line ALTER COLUMN product_id DROP not null """, ) openupgrade.logged_query( cr, """ ALTER TABLE sale_order_template_line ALTER COLUMN product_uom_id DROP not null """, ) openupgrade.logged_query( cr, """ INSERT INTO sale_order_template_line (sale_order_template_id, layout_category_id, sequence, name, price_unit, product_uom_qty, display_type, create_uid, create_date, write_uid, write_date) SELECT sotl.sale_order_template_id, sotl.layout_category_id, min(sotl.sequence) - 1 as sequence, max(slc.name), 0, 0, 'line_section', min(sotl.create_uid), min(sotl.create_date), min(sotl.write_uid), min(sotl.write_date) FROM sale_order_template_line sotl INNER JOIN sale_layout_category slc ON slc.id = sotl.layout_category_id GROUP BY sale_order_template_id, layout_category_id ORDER BY sale_order_template_id, layout_category_id, sequence """ )
def merge_stock_putaway_product(cr): if openupgrade.table_exists(cr, 'stock_product_putaway_strategy'): column_name = openupgrade.get_legacy_name('old_strat_id') # first, we add the ones with product variant openupgrade.logged_query( cr, sql.SQL( """INSERT INTO stock_fixed_putaway_strat (product_id, putaway_id, fixed_location_id, sequence, create_uid, create_date, write_uid, write_date, {}) SELECT product_product_id, putaway_id, fixed_location_id, sequence, create_uid, create_date, write_uid, write_date, id FROM stock_product_putaway_strategy WHERE product_product_id IS NOT NULL""").format( sql.Identifier(column_name))) # second, we add the ones with product template # We put sequence + 1000 for giving more priority by default to product # specific rules openupgrade.logged_query( cr, sql.SQL( """INSERT INTO stock_fixed_putaway_strat (product_id, putaway_id, fixed_location_id, sequence, create_uid, create_date, write_uid, write_date, {}) SELECT pp.id, spps.putaway_id, spps.fixed_location_id, spps.sequence + 1000, spps.create_uid, spps.create_date, spps.write_uid, spps.write_date, spps.id FROM stock_product_putaway_strategy spps JOIN product_template pt ON (pt.id = spps.product_tmpl_id AND spps.product_product_id IS NULL) JOIN product_product pp ON pp.product_tmpl_id = pt.id LEFT JOIN stock_fixed_putaway_strat sfps ON ( sfps.product_id = pp.id AND sfps.putaway_id = spps.putaway_id AND sfps.fixed_location_id = spps.fixed_location_id) WHERE sfps.putaway_id IS NULL""").format( sql.Identifier(column_name)))
def assign_employee_leave_manager(env): """Asign as default leave manager the employee responsible, which is the one assigned by Odoo itself, and add them to the proper group, also following Odoo's logic. This is because although the field is not strictly required, all the approval logic needs it implicitly, and Odoo has put code in create/write methods for being sure a value is set. """ openupgrade.logged_query( env.cr, """UPDATE hr_employee he SET leave_manager_id = he_parent.user_id FROM hr_employee he_parent WHERE he_parent.id = he.parent_id AND he.leave_manager_id IS NULL""", ) leave_managers = env["hr.employee"].search([]).mapped("leave_manager_id") approver_group = env.ref( "hr_holidays.group_hr_holidays_responsible", raise_if_not_found=False, ) if approver_group: approver_group.sudo().write({ 'users': [(4, x) for x in leave_managers.ids] })
def _generate_stock_valuation_layer(env): openupgrade.logged_query( env.cr, """ INSERT INTO stock_valuation_layer (value, unit_cost, quantity, remaining_qty, stock_valuation_layer_id, description, stock_move_id, product_id, stock_landed_cost_id, company_id, account_move_id, create_date, create_uid, write_date, write_uid) SELECT sval.additional_landed_cost, 0.0, 0.0, 0.0, svl.id, slc.name, sm.id, sm.product_id, slc.id, am.company_id, am.id, am.create_date, am.create_uid, am.write_date, am.write_uid FROM stock_landed_cost slc JOIN account_move am ON am.id = slc.account_move_id JOIN stock_valuation_adjustment_lines sval ON sval.cost_id = slc.id JOIN stock_move sm ON sm.id = sval.move_id LEFT JOIN ( SELECT MIN(id) as id, stock_move_id FROM stock_valuation_layer GROUP BY stock_move_id ) svl ON svl.stock_move_id = sval.move_id WHERE slc.state = 'done' """, )
def _move_model_in_data(env, ids_map, old_model, new_model): renames = [ ('mail_message', 'model', 'res_id'), ('mail_followers', 'res_model', 'res_id'), ('ir_attachment', 'res_model', 'res_id'), ('mail_activity', 'res_model', 'res_id'), ('ir_model_data', 'model', 'res_id'), ] for old_id, new_id in ids_map: for rename in renames: openupgrade.logged_query( env.cr, """ UPDATE {table} SET {field1} = '{new_value1}', {field2} = {new_value2} WHERE {field1} = '{old_value1}' AND {field2} = {old_value2} """.format( table=rename[0], field1=rename[1], field2=rename[2], old_value1=old_model, new_value1=new_model, old_value2=old_id, new_value2=new_id, ))
def fill_hr_leave(env): # In pre-migration the hr_leave table still doesn't exist openupgrade.logged_query( env.cr, """ INSERT INTO hr_leave ( id, category_id, date_from, date_to, department_id, employee_id, first_approver_id, holiday_status_id, holiday_type, manager_id, meeting_id, name, notes, number_of_days, payslip_status, report_note, second_approver_id, state, user_id, create_uid, create_date, write_uid, write_date ) SELECT id, category_id, date_from, date_to, department_id, employee_id, first_approver_id, holiday_status_id, holiday_type, manager_id, meeting_id, name, notes, number_of_days, payslip_status, report_note, second_approver_id, state, user_id, create_uid, create_date, write_uid, write_date FROM hr_holidays WHERE %s = 'remove' RETURNING id""", (AsIs(openupgrade.get_legacy_name('type')), ), ) ids = [x[0] for x in env.cr.fetchall()] _move_model_in_data(env, ids, 'hr.holidays', 'hr.leave')
def migrate(cr, version): if not version: return cr.execute( """SELECT id FROM account_analytic_journal WHERE type='purchase' """) res = cr.fetchone() if res: openupgrade.add_xmlid(cr, 'account', 'exp', 'account.analytic.journal', res[0], True) openupgrade.rename_columns(cr, column_renames) openupgrade.rename_tables(cr, tables_renames) # drop views that inhibit changing field types. They will be recreated # anyways for view in [ 'analytic_entries_report', 'account_entries_report', 'report_invoice_created', 'report_aged_receivable' ]: cr.execute('drop view if exists %s cascade' % view) # Avoid inconsistencies between partner_id in account_invoice_line and # account invoice openupgrade.logged_query( cr, """ UPDATE account_invoice_line ail SET partner_id=ai.partner_id FROM account_invoice ai WHERE ail.invoice_id = ai.id AND ail.partner_id != ai.partner_id; """) # delete a view from obsolete module account_report_company that causes # migration of the account module not to happen cleanly cr.execute("delete from ir_ui_view v " "using ir_model_data d where " "v.id=d.res_id and d.model='ir.ui.view' and " "d.name='account_report_company_invoice_report_tree_view'")
def fill_event_track_partner_id(cr): openupgrade.logged_query( cr, """ UPDATE event_track et SET partner_id = rel.partner_id FROM (SELECT event_track_id, min(res_partner_id) as partner_id FROM event_track_res_partner_rel ep_rel JOIN res_partner rp ON ep_rel.res_partner_id = rp.id WHERE rp.active GROUP BY event_track_id) rel WHERE et.partner_id IS NULL AND rel.event_track_id = et.id """ ) # We need to fill related email if partner_id.email is filled for avoiding # error on message composer in the track openupgrade.logged_query( cr, """ UPDATE event_track et SET partner_email = rp.email FROM res_partner rp WHERE et.partner_id = rp.id AND rp.email IS NOT NULL AND et.partner_email IS NULL""", )
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. """ # we don not force dependency on openupgradelib, only if available we try # o un de hook _logger.info('running post_init_hook') if not openupgrade.column_exists: return False # write en vez de sql para que genere los campos por defecto necesarios if openupgrade.column_exists(cr, 'res_partner', 'main_id_number'): # we make this so it ise much faster _logger.info('creating id numbers records') openupgrade.logged_query(cr, """ INSERT into res_partner_id_number (partner_id, category_id, name, sequence, create_uid, write_uid, create_date, write_date, active) SELECT id, main_id_category_id, main_id_number, 10, 1, 1, create_date, write_date, true FROM res_partner WHERE main_id_category_id is not null and main_id_number is not null """,) # tambien con este column exists nos damos cuenta si es migracion # si este es el caso y tenia partner_vat_unique tenemos que activar # unique _logger.info('setting id unique if needed') if registry['ir.module.module'].search(cr, 1, [ ('name', '=', 'partner_vat_unique'), ('state', '=', 'to upgrade')]): registry['ir.config_parameter'].set_param( cr, 1, "l10n_cl_partner.unique_id_numbers", True)
def empty_template_pricelist_company(env): """On v13, there's no default company associated with the template nor the pricelist, on contrary than on v12. We need to empty the company_id field in case of having only one company for not having problems later when creating new pricelists and not being able to select old products due to the difference on the company_id field (on a pricelist without company, you can only select templates without company, and vice versa, but not a mix of both). We need to empty the company of pricelists as well. If there are more than one company in the DB, then everything is preserved as it is. """ env.cr.execute("SELECT COUNT(*) FROM res_company") if env.cr.fetchone()[0] == 1: openupgrade.logged_query( env.cr, "UPDATE product_template SET company_id = NULL WHERE company_id is NOT NULL", ) openupgrade.logged_query( env.cr, "UPDATE product_pricelist SET company_id = NULL WHERE company_id is NOT NULL", )
def migrate(cr, installed_version): openupgrade.load_data(cr, "l10n_it_fatturapa_in", "migrations/13.0.1.0.0/noupdate_changes.xml") openupgrade.logged_query( cr, """ update account_move set fatturapa_attachment_in_id = inv.fatturapa_attachment_in_id, inconsistencies = inv.inconsistencies, e_invoice_amount_untaxed = inv.e_invoice_amount_untaxed, e_invoice_amount_tax = inv.e_invoice_amount_tax, e_invoice_amount_total = inv.e_invoice_amount_total, e_invoice_reference = inv.e_invoice_reference, e_invoice_date_invoice = inv.e_invoice_date_invoice, e_invoice_force_validation = inv.e_invoice_force_validation, e_invoice_received_date = inv.e_invoice_received_date from account_invoice inv where account_move.id = inv.move_id; """, ) openupgrade.logged_query( cr, """ update einvoice_line set invoice_id = am.id from account_invoice inv join account_move am on am.id = inv.move_id where invoice_id = inv.id; """, )
def create_asset_groups(cr): # Add a supporting column for indicating the source asset view origin_column = sql.Identifier( openupgrade.get_legacy_name('view_asset_id')) openupgrade.logged_query( cr, sql.SQL("ALTER TABLE account_asset_group ADD {} int4").format( origin_column, ), ) # Now fill new table recursively attending parents parent_column = sql.Identifier(openupgrade.get_legacy_name('parent_id')) parent_group_ids = ('NULL', ) query_sql = sql.SQL(""" INSERT INTO account_asset_group ( name, code, company_id, parent_id, create_uid, create_date, write_date, write_uid, {origin_column} ) SELECT va.name, va.code, va.company_id, aag2.id, va.create_uid, va.create_date, va.write_date, va.write_uid, va.id FROM {table} va LEFT JOIN account_asset_group aag2 ON aag2.{origin_column} = va.{parent_column} WHERE {parent_column} {rest_sql} RETURNING {origin_column} """) isnull = sql.SQL("IS NULL") inids = sql.SQL("IN %(ids)s") while parent_group_ids: query = query_sql.format( origin_column=origin_column, table=sql.Identifier( openupgrade.get_legacy_name('account_asset_view')), parent_column=parent_column, rest_sql=isnull if parent_group_ids == ('NULL', ) else inids) openupgrade.logged_query(cr, query, {'ids': parent_group_ids}) parent_group_ids = tuple(x[0] for x in cr.fetchall())
def update_product_template(cr): # make ir.property records associated to 'standard_price' applicable to # product.product instead of product.template. cr.execute(""" SELECT imf.id FROM ir_model_fields as imf INNER JOIN ir_model as im ON imf.model_id = im.id WHERE im.model = 'product.product' AND imf.name = 'standard_price' LIMIT 1 """) standard_price_field = cr.fetchone()[0] or False openupgrade.logged_query( cr, """ INSERT INTO ir_property (name, res_id, company_id, fields_id, value_float, value_integer, value_text, value_binary, value_reference, value_datetime, type) SELECT ip.name, CONCAT('product.product,', pp.id), ip.company_id, %s, ip.value_float, ip.value_integer, ip.value_text, ip.value_binary, ip.value_reference, ip.value_datetime, ip.type FROM product_product AS pp INNER JOIN product_template AS pt ON pp.product_tmpl_id = pt.id INNER JOIN ir_property AS ip ON ip.res_id = CONCAT('product.template,', pt.id) WHERE ip.name = 'standard_price' """ % standard_price_field) # Remove ir.property records associated to 'standard_price' for model # 'product.template'. openupgrade.logged_query( cr, """ DELETE FROM ir_property WHERE name = 'standard_price' AND res_id like 'product.template%%' """) # On the template, set weight and volume to 0.0 on templates with more # than one (active?) variant as per _compute_product_template_field. openupgrade.logged_query( cr, """ UPDATE product_template SET volume = 0.0, weight = 0.0 FROM ( SELECT product_tmpl_id, count(id) as count FROM product_product WHERE active GROUP BY product_tmpl_id ) as q WHERE q.product_tmpl_id = product_template.id AND q.count > 1 """)
def migrate(env, version): openupgrade.load_data(env.cr, 'project', 'migrations/12.0.1.1/noupdate_changes.xml', mode='init_no_create') openupgrade.load_data(env.cr, 'project', 'migrations/12.0.1.1/noupdate_changes2.xml') openupgrade.delete_records_safely_by_xml_id( env, [ 'project.msg_task_data_14_attach', 'project.msg_task_data_8_attach', 'project.msg_task_data_14', 'project.msg_task_data_8', 'project.project_task_data_8', ], ) openupgrade.logged_query( env.cr, """ UPDATE ir_model_data SET noupdate = TRUE WHERE module = 'project' AND (name = 'ir_cron_rating_project' OR name = 'rating_project_request_email_template') """)
def migrate(env, version): cr = env.cr openupgrade.copy_columns(cr, _column_copies) openupgrade.rename_columns(cr, _column_renames) openupgrade.rename_fields(env, _field_renames) if openupgrade.table_exists(cr, 'sale_order'): openupgrade.rename_fields(env, _field_sale_renames) # https://github.com/odoo/odoo/commit/ca25a692bd19fdca2b2600f2054eb419aae28999 openupgrade.logged_query( env.cr, """ UPDATE ir_config_parameter SET key = 'account.use_invoice_terms' WHERE key = 'sale.use_sale_note'""") openupgrade.rename_models(cr, _model_renames) openupgrade.rename_tables(cr, _table_renames) type_change_account_fiscal_position_zips(env) create_account_invoice_amount_tax_company_signed(env) create_account_move_new_columns(env) fill_account_move_line_parent_state(env) fill_account_move_line_account_internal_type(env) create_res_partner_ranks(env) add_helper_invoice_move_rel(env) if openupgrade.table_exists(cr, 'account_voucher'): add_helper_voucher_move_rel(env)
def insert_missing_product_template_attribute_line(env): """Given this situation in v12: - Template T with attribute A and values A1, and A2, and attribute B with value B1. - Generated variants V1 and V2 for attribute values A1/B1 and A2/B2 respectively. - Generated product.template.attribute.line records for T/A and T/B. - V2 is used in a quotation. - Remove B attribute from the template. Result: * V2 is archived * product.template.attribute.line T/B is removed. On v13, the record is not removed, but marked with active = False. From the current data status we find on v12 for these cases, we need to reintroduce missing product.template.attribute.line records with active = False needed later on next steps for DB integrity. """ openupgrade.add_fields(env, [( "active", "product.template.attribute.line", "product_template_attribute_line", "boolean", False, "product", True, )]) openupgrade.logged_query( env.cr, """ INSERT INTO product_template_attribute_line (active, product_tmpl_id, attribute_id) SELECT False, pp.product_tmpl_id, pav.attribute_id FROM product_attribute_value_product_product_rel pavppr JOIN product_product pp ON pp.id = pavppr.product_product_id JOIN product_attribute_value pav ON pav.id = pavppr.product_attribute_value_id LEFT JOIN product_template_attribute_line ptal ON ptal.product_tmpl_id = pp.product_tmpl_id AND ptal.attribute_id = pav.attribute_id WHERE ptal.id IS NULL GROUP BY pav.attribute_id, pp.product_tmpl_id""", )
def cleanup_translations(cr): """ Cleanup translations of adopted templates """ updated_templates = ( 'calendar_template_meeting_reminder', 'calendar_template_meeting_changedate', 'calendar_template_meeting_invitation', ) cr.execute( """ SELECT res_id FROM ir_model_data WHERE module = 'calendar' AND model = 'mail.template' AND name in %s """, (updated_templates, )) record_ids = tuple([r[0] for r in cr.fetchall()]) query = (""" DELETE FROM ir_translation WHERE module = 'calendar' AND res_id IN %s """) openupgrade.logged_query(cr, query, (record_ids, ))
def merge_refund_journals_to_normal(cr, registry): if openupgrade.column_exists(cr, 'account_journal', 'old_type'): openupgrade.logged_query( cr, """ SELECT id, point_of_sale_number, old_type, company_id FROM account_journal WHERE old_type in ('sale_refund', 'purchase_refund') """, ) journals_read = cr.fetchall() for journal_read in journals_read: (from_journal_id, point_of_sale_number, old_type, company_id) = journal_read new_type = 'sale' if old_type == 'purchase_refund': new_type = 'purchase' domain = [ ('type', '=', new_type), ('id', '!=', from_journal_id), ('company_id', '=', company_id), ] if point_of_sale_number: domain += [('point_of_sale_number', '=', point_of_sale_number)] journals = registry['account.journal'].search(cr, 1, domain) # we only merge journals if we have one coincidence if len(journals) == 1: from_journal = registry['account.journal'].browse( cr, 1, from_journal_id) to_journal = registry['account.journal'].browse( cr, 1, journals[0]) registry['account.journal'].merge_journals( cr, 1, from_journal, to_journal)
def migrate_responsability_type(env): _logger.info('Migrating responsability type to moves') cr = env.cr openupgrade.logged_query( cr, """ SELECT afip_responsability_type_id, move_id FROM account_invoice WHERE move_id is not Null and afip_responsability_type_id is not Null """, ) recs = cr.fetchall() for rec in recs: afip_responsability_type_id, move_id = rec env['account.move'].browse(move_id).afip_responsability_type_id = ( afip_responsability_type_id) invoice_moves = env['account.invoice'].search([ ('move_id', '!=', False), ('afip_responsability_type_id', '!=', False), ]) moves = env['account.move'].search([('id', 'not in', invoice_moves.ids), ('partner_id', '!=', False)]) moves.set_afip_responsability_type_id()
def copy_invoice_m2m_values( env, field_name, old_relation_table=None, old_comodel_column=None ): """ Copy values for m2m field `field_name` from account.invoice to account.move. :param env: Odoo Environment :param field_name: name of the new field :param old_relation_table: name of the relation for the old field :param old_comodel_column: name of the comodel for the old field """ old_model_name = "account.invoice" new_model_name = "account.move" field = env[new_model_name]._fields[field_name] new_model_column = field.column1 new_comodel_column = field.column2 old_comodel_column = old_comodel_column or new_comodel_column new_relation_table = field.relation if not old_relation_table: old_relation_table = new_relation_table.replace( new_model_name.replace(".", "_"), old_model_name.replace(".", "_"), ) query = """ INSERT INTO %(new_relation_table)s (%(new_model_column)s, %(new_comodel_column)s) VALUES ( SELECT am.id, rel.%(old_comodel_column)s FROM %(old_relation_table)s rel JOIN account_invoice ai ON ai.id = rel.account_invoice_id JOIN account_move am on am.id = ai.move_id ) """ return openupgrade.logged_query( env.cr, query, dict( new_model_column=new_model_column, new_comodel_column=new_comodel_column, new_relation_table=new_relation_table, old_comodel_column=old_comodel_column, old_relation_table=old_relation_table, ), )
def migrate(env, version): openupgrade.logged_query( env.cr, """ UPDATE sale_preinvoice_group spg SET move_id = am.id FROM account_move am WHERE am.old_invoice_id = spg.invoice_id """, ) openupgrade.logged_query( env.cr, """ UPDATE account_move am SET agreement_id = ai.agreement_id, coverage_template_id = ai.coverage_template_id, invoice_group_method_id = ai.invoice_group_method_id FROM account_invoice ai WHERE ai.id = am.old_invoice_id""", ) openupgrade.logged_query( env.cr, """ UPDATE sale_order so SET invoice_group_method_id = igm.id FROM sale_order_line sol INNER JOIN invoice_group_method igm ON igm.id = sol.invoice_group_method_id WHERE so.invoice_group_method_id IS NULL AND (igm.no_invoice is NULL OR NOT igm.no_invoice) AND sol.order_id = so.id """, ) openupgrade.logged_query( env.cr, """ UPDATE sale_order so SET invoice_group_method_id = igm.id FROM sale_order_line sol INNER JOIN invoice_group_method igm ON igm.id = sol.invoice_group_method_id WHERE so.invoice_group_method_id IS NULL AND igm.no_invoice AND sol.order_id = so.id """, )
def fill_res_partner_ranks(env): # customer_rank openupgrade.logged_query( env.cr, """ UPDATE res_partner rp SET customer_rank = rel.customer_rank FROM (SELECT am.partner_id, count(am.id) as customer_rank FROM account_move am WHERE am.state != 'draft' AND left(am.type,4) = 'out_' AND am.partner_id IS NOT NULL GROUP BY am.partner_id) rel WHERE rel.partner_id = rp.id""", ) openupgrade.logged_query( env.cr, """ UPDATE res_partner rp SET customer_rank = 1 WHERE rp.customer_rank = 0 AND rp.{}""".format( openupgrade.get_legacy_name("customer")), ) # supplier_rank openupgrade.logged_query( env.cr, """ UPDATE res_partner rp SET supplier_rank = rel.supplier_rank FROM (SELECT am.partner_id, count(am.id) as supplier_rank FROM account_move am JOIN res_partner rp ON am.partner_id = rp.id WHERE am.state != 'draft' AND left(am.type,3) = 'in_' AND am.partner_id IS NOT NULL GROUP BY am.partner_id) rel WHERE rel.partner_id = rp.id""", ) openupgrade.logged_query( env.cr, """ UPDATE res_partner rp SET supplier_rank = 1 WHERE rp.supplier_rank = 0 AND rp.{}""".format( openupgrade.get_legacy_name("supplier")), )
def migrate(env, version): # Link the new field that points to the invoice global discount instead # of the global discount definition openupgrade.logged_query( env.cr, sql.SQL(""" UPDATE account_move_line aml SET invoice_global_discount_id = aigd.id FROM account_invoice_global_discount aigd WHERE aigd.invoice_id = aml.invoice_id AND aigd.global_discount_id = aml.{} """).format( sql.Identifier(openupgrade.get_legacy_name("global_discount_id")))) # Link to existing global discount records, all the invoice taxes as best # effort openupgrade.logged_query( env.cr, """ INSERT INTO account_invoice_global_discount_account_tax_rel (account_invoice_global_discount_id, account_tax_id) SELECT aigd.id, ailt.tax_id FROM account_invoice_global_discount aigd JOIN account_invoice_line ail ON aigd.invoice_id = ail.invoice_id JOIN account_invoice_line_tax ailt ON ailt.invoice_line_id = ail.id GROUP BY aigd.id, ailt.tax_id""") # Delete in prevention of manual manipulations existing tax lines linked # to global discount journal items openupgrade.logged_query( env.cr, """ DELETE FROM account_move_line_account_tax_rel rel USING account_move_line aml WHERE rel.account_move_line_id = aml.id AND aml.invoice_global_discount_id IS NOT NULL""") # Link all invoice taxes in global discount existing journal items as best # effort openupgrade.logged_query( env.cr, """ INSERT INTO account_move_line_account_tax_rel (account_move_line_id, account_tax_id) SELECT aml.id, rel.account_tax_id FROM account_move_line aml JOIN account_invoice_global_discount_account_tax_rel rel ON rel.account_invoice_global_discount_id = aml.invoice_global_discount_id""")
def migrate(env, version): # map old / non existing value 'proforma' and 'proforma2' to value 'draft' openupgrade.map_values(env.cr, openupgrade.get_legacy_name('state'), 'state', [('proforma', 'draft'), ('proforma2', 'draft')], table='account_invoice', write='sql') # copy statement_line_id values from account.move to account.move.line env.cr.execute(""" UPDATE account_move_line aml SET statement_line_id = am.statement_line_id FROM account_move am WHERE aml.move_id = am.id AND am.statement_line_id IS NOT NULL; """) # Migrate draft payments to cancelled if they don't have any move lines # but they have been posted before (i.e. when move_name is set) openupgrade.logged_query( env.cr, """UPDATE account_payment SET state = 'cancelled' WHERE state = 'draft' AND move_name IS NOT NULL AND id NOT IN ( SELECT payment_id FROM account_move_line WHERE payment_id IS NOT NULL)""") # Populate new 'sequence' field according to previous order field 'name' openupgrade.logged_query( env.cr, """UPDATE account_payment_term apt SET sequence = sub.sequence FROM (SELECT id, row_number() over (ORDER BY name asc) AS sequence FROM account_payment_term) sub WHERE sub.id = apt.id """) # Set accounting configuration steps to done if there are moves openupgrade.logged_query( env.cr, """UPDATE res_company rc SET account_setup_bank_data_done = TRUE, account_setup_bar_closed = TRUE, account_setup_coa_done = TRUE, account_setup_company_data_done = TRUE, account_setup_fy_data_done = TRUE WHERE EXISTS ( SELECT id FROM account_move WHERE company_id = rc.id)""") migrate_account_tax_cash_basis(env) fill_account_invoice_line_total(env) fill_account_move_line_tax_base_amount(env) _migrate_security(env) openupgrade.load_data( env.cr, 'account', 'migrations/11.0.1.1/noupdate_changes.xml', )
def fill_slide_likes_dislikes_views(env): """The new structure needs an extra slide.slide.partner record for registering views and possible likes/dislikes. We add fake records here for getting the same numbers that were cumulated in previous versions. """ partner_root = env.ref("base.partner_root") openupgrade.logged_query( env.cr, sql.SQL(""" INSERT INTO slide_slide_partner (create_uid, create_date, write_uid, write_date, slide_id, channel_id, partner_id, vote, completed, quiz_attempts_count) SELECT ss.create_uid, ss.create_date, ss.write_uid, ss.write_date, ss.id, ss.channel_id, %s, 1, False, 0 FROM slide_slide ss CROSS JOIN generate_series(1, ss.{likes}) AS sub WHERE ss.{likes} > 0 """).format( likes=sql.Identifier(openupgrade.get_legacy_name("likes"))), (partner_root.id, )) openupgrade.logged_query( env.cr, sql.SQL(""" INSERT INTO slide_slide_partner (create_uid, create_date, write_uid, write_date, slide_id, channel_id, partner_id, vote, completed, quiz_attempts_count) SELECT ss.create_uid, ss.create_date, ss.write_uid, ss.write_date, ss.id, ss.channel_id, %s, -1, False, 0 FROM slide_slide ss CROSS JOIN generate_series(1, ss.{dislikes}) AS sub WHERE ss.{dislikes} > 0 """).format( dislikes=sql.Identifier(openupgrade.get_legacy_name("dislikes"))), (partner_root.id, )) openupgrade.logged_query( env.cr, sql.SQL(""" INSERT INTO slide_slide_partner (create_uid, create_date, write_uid, write_date, slide_id, channel_id, partner_id, vote, completed, quiz_attempts_count) SELECT ss.create_uid, ss.create_date, ss.write_uid, ss.write_date, ss.id, ss.channel_id, %s, 0, False, 0 FROM slide_slide ss CROSS JOIN generate_series(1, ss.{slide_views} - COALESCE(ss.{likes}, 0) - COALESCE(ss.{dislikes}, 0)) AS sub WHERE ss.{slide_views} > 0 """).format( likes=sql.Identifier(openupgrade.get_legacy_name("likes")), dislikes=sql.Identifier(openupgrade.get_legacy_name("dislikes")), slide_views=sql.Identifier( openupgrade.get_legacy_name("slide_views")), ), (partner_root.id, ))
def copy_crm_claim_stage(cr): """ Copy the whole table crm_claim_stage to mgmtsystem_action_stage In 7.0, mgmtsystem_action.stage_id was pointing to crm_claim_stage In 8.0, it points to mgmtsystem_action_stage which is a table inherited from crm_claim_stage. """ openupgrade.logged_query( cr, """ CREATE TABLE mgmtsystem_action_stage ( LIKE crm_claim_stage INCLUDING ALL ); """) cr.execute( """ select nextval('crm_claim_stage_id_seq') """ ) sequence_num = cr.fetchall()[0][0] openupgrade.logged_query( cr, """ CREATE SEQUENCE mgmtsystem_action_stage_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START %s CACHE 1; """, (sequence_num,) ) openupgrade.logged_query( cr, """ INSERT INTO mgmtsystem_action_stage SELECT * FROM crm_claim_stage """ ) cr.execute( "ALTER TABLE mgmtsystem_action " "DROP CONSTRAINT IF EXISTS mgmtsystem_action_stage_id_fkey") cr.execute( "ALTER TABLE mgmtsystem_action " "DROP CONSTRAINT IF EXISTS mgmtsystem_action_stage_id_fkey1")