Thibault Delavallée (OpenERP) has proposed merging 
lp:~openerp-dev/openobject-addons/trunk-mail-cleaning-alias-tde into 
lp:openobject-addons.

Requested reviews:
  OpenERP Core Team (openerp)

For more details, see:
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-mail-cleaning-alias-tde/+merge/121044

mail_alias: moved database manipulation to force alias_id to required into 
mail_alias; res_users and hr_recruitement now calls a kewl migrate_to_alias.
-- 
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-mail-cleaning-alias-tde/+merge/121044
Your team OpenERP R&D Team is subscribed to branch 
lp:~openerp-dev/openobject-addons/trunk-mail-cleaning-alias-tde.
=== modified file 'hr_recruitment/hr_recruitment.py'
--- hr_recruitment/hr_recruitment.py	2012-08-16 14:44:03 +0000
+++ hr_recruitment/hr_recruitment.py	2012-08-23 16:12:47 +0000
@@ -19,19 +19,14 @@
 #
 ##############################################################################
 
-import logging
 import time
+import tools
+
+from base_status.base_stage import base_stage
 from datetime import datetime
-
-import tools
 from osv import fields, osv
-from openerp.modules.registry import RegistryManager
-from openerp import SUPERUSER_ID
-from base_status.base_stage import base_stage
 from tools.translate import _
 
-_logger = logging.getLogger(__name__)
-
 AVAILABLE_STATES = [
     ('draft', 'New'),
     ('cancel', 'Refused'),
@@ -522,35 +517,8 @@
 
     def _auto_init(self, cr, context=None):
         """Installation hook to create aliases for all jobs and avoid constraint errors."""
-
-        # disable the unique alias_id not null constraint, to avoid spurious warning during
-        # super.auto_init. We'll reinstall it afterwards.
-        self._columns['alias_id'].required = False
-
-        super(hr_job,self)._auto_init(cr, context=context)
-
-        registry = RegistryManager.get(cr.dbname)
-        mail_alias = registry.get('mail.alias')
-        hr_jobs = registry.get('hr.job')
-        jobs_no_alias = hr_jobs.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
-        # Use read() not browse(), to avoid prefetching uninitialized inherited fields
-        for job_data in hr_jobs.read(cr, SUPERUSER_ID, jobs_no_alias, ['name']):
-            alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, {'alias_name': 'job+'+job_data['name'],
-                                                                         'alias_defaults': {'job_id': job_data['id']}},
-                                                      model_name='hr.applicant')
-            hr_jobs.write(cr, SUPERUSER_ID, job_data['id'], {'alias_id': alias_id})
-            _logger.info('Mail alias created for hr.job %s (uid %s)', job_data['name'], job_data['id'])
-
-        # Finally attempt to reinstate the missing constraint
-        try:
-            cr.execute('ALTER TABLE hr_job ALTER COLUMN alias_id SET NOT NULL')
-        except Exception:
-            _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
-                            "If you want to have it, you should update the records and execute manually:\n"\
-                            "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
-                            self._table, 'alias_id', self._table, 'alias_id')
-
-        self._columns['alias_id'].required = True
+        self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(hr_job,self)._auto_init,
+            self._columns['alias_id'], 'name', alias_prefix='job+', alias_defaults={'job_id': 'id'}, context=context)
 
     def create(self, cr, uid, vals, context=None):
         mail_alias = self.pool.get('mail.alias')

=== modified file 'mail/mail_alias.py'
--- mail/mail_alias.py	2012-08-14 10:03:54 +0000
+++ mail/mail_alias.py	2012-08-23 16:12:47 +0000
@@ -19,11 +19,16 @@
 #
 ##############################################################################
 
+import logging
 import re
 import unicodedata
 
 from openerp.osv import fields, osv
 from openerp.tools import ustr
+from openerp.modules.registry import RegistryManager
+from openerp import SUPERUSER_ID
+
+_logger = logging.getLogger(__name__)
 
 # Inspired by http://stackoverflow.com/questions/517923
 def remove_accents(input_str):
@@ -129,6 +134,56 @@
             sequence = (sequence + 1) if sequence else 2
         return new_name
 
+    def migrate_to_alias(self, cr, child_model_name, child_table_name, child_model_auto_init_fct,
+        alias_id_column, alias_column, alias_prefix = '', alias_force_thread_id = '', alias_defaults = {}, context=None):
+        """ Installation hook to create aliases for all users and avoid constraint errors.
+
+            :param child_model_name: model name of the child class (i.e. res.users)
+            :param child_table_name: table name of the child class (i.e. res_users)
+            :param child_model_auto_init_fct: pointer to the _auto_init function
+                (i.e. super(res_users,self)._auto_init(cr, context=context))
+            :param alias_id_column: alias_id column (i.e. self._columns['alias_id'])
+            :param alias_column: column used for the unique name (i.e. 'login')
+            :param alias_prefix: prefix for the unique name (i.e. 'jobs' + ...)
+            :param alias_force_thread_id': name of the column for force_thread_id;
+                if empty string, not taken into account
+            :param alias_defaults: dict, keys = mail.alias columns, values = child
+                model column name used for default values (i.e. {'job_id': 'id'})
+        """
+
+        # disable the unique alias_id not null constraint, to avoid spurious warning during 
+        # super.auto_init. We'll reinstall it afterwards.
+        alias_id_column.required = False
+
+        # call _auto_init
+        child_model_auto_init_fct(cr, context=context)
+
+        registry = RegistryManager.get(cr.dbname)
+        mail_alias = registry.get('mail.alias')
+        child_class_model = registry.get(child_model_name)
+        no_alias_ids = child_class_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
+        # Use read() not browse(), to avoid prefetching uninitialized inherited fields
+        for obj_data in child_class_model.read(cr, SUPERUSER_ID, no_alias_ids, [alias_column]):
+            alias_vals = {'alias_name': '%s%s' % (alias_prefix, obj_data[alias_column]) }
+            if alias_force_thread_id:
+                alias_vals['alias_force_thread_id'] = obj_data[alias_force_thread_id]
+            alias_vals['alias_defaults'] = dict( (k, obj_data[v]) for k, v in alias_defaults.iteritems())
+            alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, alias_vals, model_name=child_model_name)
+            child_class_model.write(cr, SUPERUSER_ID, obj_data['id'], {'alias_id': alias_id})
+            _logger.info('Mail alias created for %s %s (uid %s)', child_model_name, obj_data[alias_column], obj_data['id'])
+
+        # Finally attempt to reinstate the missing constraint
+        try:
+            cr.execute('ALTER TABLE %s ALTER COLUMN alias_id SET NOT NULL' % (child_table_name))
+        except Exception:
+            _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
+                            "If you want to have it, you should update the records and execute manually:\n"\
+                            "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
+                            child_table_name, 'alias_id', child_table_name, 'alias_id')
+
+        # set back the unique alias_id constraint
+        alias_id_column.required = True
+
     def create_unique_alias(self, cr, uid, vals, model_name=None, context=None):
         """Creates an email.alias record according to the values provided in ``vals``,
         with 2 alterations: the ``alias_name`` value may be suffixed in order to

=== modified file 'mail/res_users.py'
--- mail/res_users.py	2012-08-15 21:20:59 +0000
+++ mail/res_users.py	2012-08-23 16:12:47 +0000
@@ -19,15 +19,10 @@
 #
 ##############################################################################
 
-import logging
-
 from osv import osv, fields
-from openerp.modules.registry import RegistryManager
 from openerp import SUPERUSER_ID
 from tools.translate import _
 
-_logger = logging.getLogger(__name__)
-
 class res_users(osv.Model):
     """ Update of res.users class
         - add a preference about sending emails about notifications
@@ -69,35 +64,8 @@
 
     def _auto_init(self, cr, context=None):
         """Installation hook to create aliases for all users and avoid constraint errors."""
-
-        # disable the unique alias_id not null constraint, to avoid spurious warning during 
-        # super.auto_init. We'll reinstall it afterwards.
-        self._columns['alias_id'].required = False
-
-        super(res_users,self)._auto_init(cr, context=context)
-
-        registry = RegistryManager.get(cr.dbname)
-        mail_alias = registry.get('mail.alias')
-        res_users_model = registry.get('res.users')
-        users_no_alias = res_users_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)])
-        # Use read() not browse(), to avoid prefetching uninitialized inherited fields
-        for user_data in res_users_model.read(cr, SUPERUSER_ID, users_no_alias, ['login']):
-            alias_id = mail_alias.create_unique_alias(cr, SUPERUSER_ID, {'alias_name': user_data['login'],
-                                                                         'alias_force_id': user_data['id']},
-                                                      model_name=self._name)
-            res_users_model.write(cr, SUPERUSER_ID, user_data['id'], {'alias_id': alias_id})
-            _logger.info('Mail alias created for user %s (uid %s)', user_data['login'], user_data['id'])
-
-        # Finally attempt to reinstate the missing constraint
-        try:
-            cr.execute('ALTER TABLE res_users ALTER COLUMN alias_id SET NOT NULL')
-        except Exception:
-            _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
-                            "If you want to have it, you should update the records and execute manually:\n"\
-                            "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
-                            self._table, 'alias_id', self._table, 'alias_id')
-
-        self._columns['alias_id'].required = True
+        self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(res_users,self)._auto_init,
+            self._columns['alias_id'], 'login', alias_force_thread_id='id', context=context)
 
     def create(self, cr, uid, data, context=None):
         # create default alias same as the login

_______________________________________________
Mailing list: https://launchpad.net/~openerp-dev-gtk
Post to     : [email protected]
Unsubscribe : https://launchpad.net/~openerp-dev-gtk
More help   : https://help.launchpad.net/ListHelp

Reply via email to