# -*- coding: utf-8 -*- """Post-migration for 19.0.2.2.0 - Bundle 11. Back-fills the new x_fc_symptom_class_id M2O on repair.order from the legacy x_fc_issue_category Char so that existing repairs can immediately be used with troubleshooting flowcharts. For each distinct (category, issue_category) text we encounter, we either match an existing symptom.class by lowercase name OR create a placeholder symptom row tagged 'auto-imported' so a manager can clean it up later. """ import logging import re _logger = logging.getLogger(__name__) def _slug(text): return re.sub(r'[^a-z0-9_]+', '_', (text or '').strip().lower()).strip('_') or 'unknown' def migrate(cr, version): if not version: return # fresh install, nothing to back-fill # Find every (category_id, issue_category) pair on existing repairs that # is not yet linked to a symptom class. cr.execute(""" SELECT DISTINCT x_fc_repair_category_id, x_fc_issue_category FROM repair_order WHERE x_fc_issue_category IS NOT NULL AND x_fc_issue_category <> '' AND x_fc_symptom_class_id IS NULL """) pairs = cr.fetchall() if not pairs: return _logger.info( 'Bundle 11 migration: back-filling symptom_class for %d distinct ' '(category, issue_category) pairs', len(pairs), ) for cat_id, issue_text in pairs: if not cat_id: continue code = _slug(issue_text) # Try to reuse an existing symptom class by code-or-name on this category. cr.execute(""" SELECT id FROM fusion_repair_symptom_class WHERE category_id = %s AND (code = %s OR LOWER(name->>'en_US') = LOWER(%s)) LIMIT 1 """, (cat_id, code, issue_text)) row = cr.fetchone() if row: sym_id = row[0] else: # Create a placeholder so the M2O isn't lost. Manager renames later. display = (issue_text or 'Imported').strip()[:80] cr.execute(""" INSERT INTO fusion_repair_symptom_class (name, code, category_id, sequence, active, description, icon, create_date, write_date, create_uid, write_uid) VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW(), 1, 1) RETURNING id """, ( {'en_US': display}, code, cat_id, 90, True, 'Auto-imported by Bundle 11 migration from legacy ' 'x_fc_issue_category. Review and rename if needed.', 'fa-exclamation-circle', )) sym_id = cr.fetchone()[0] # Back-fill the M2O on every repair with this pair. cr.execute(""" UPDATE repair_order SET x_fc_symptom_class_id = %s WHERE x_fc_repair_category_id = %s AND x_fc_issue_category = %s AND x_fc_symptom_class_id IS NULL """, (sym_id, cat_id, issue_text)) _logger.info('Bundle 11 migration: back-fill complete.')