[MERGE] Foward-port saas-5 up to ee4df1e
[odoo/odoo.git] / addons / crm / base_partner_merge.py
1 #!/usr/bin/env python
2 from __future__ import absolute_import
3 from email.utils import parseaddr
4 import functools
5 import htmlentitydefs
6 import itertools
7 import logging
8 import operator
9 import re
10 from ast import literal_eval
11 from openerp.tools import mute_logger
12
13 # Validation Library https://pypi.python.org/pypi/validate_email/1.1
14 from .validate_email import validate_email
15
16 import openerp
17 from openerp.osv import osv, orm
18 from openerp.osv import fields
19 from openerp.osv.orm import browse_record
20 from openerp.tools.translate import _
21
22 pattern = re.compile("&(\w+?);")
23
24 _logger = logging.getLogger('base.partner.merge')
25
26
27 # http://www.php2python.com/wiki/function.html-entity-decode/
28 def html_entity_decode_char(m, defs=htmlentitydefs.entitydefs):
29     try:
30         return defs[m.group(1)]
31     except KeyError:
32         return m.group(0)
33
34
35 def html_entity_decode(string):
36     return pattern.sub(html_entity_decode_char, string)
37
38
39 def sanitize_email(email):
40     assert isinstance(email, basestring) and email
41
42     result = re.subn(r';|/|:', ',',
43                      html_entity_decode(email or ''))[0].split(',')
44
45     emails = [parseaddr(email)[1]
46               for item in result
47               for email in item.split()]
48
49     return [email.lower()
50             for email in emails
51             if validate_email(email)]
52
53
54 def is_integer_list(ids):
55     return all(isinstance(i, (int, long)) for i in ids)
56
57
58 class ResPartner(osv.Model):
59     _inherit = 'res.partner'
60
61     _columns = {
62         'id': fields.integer('Id', readonly=True),
63         'create_date': fields.datetime('Create Date', readonly=True),
64     }
65
66 class MergePartnerLine(osv.TransientModel):
67     _name = 'base.partner.merge.line'
68
69     _columns = {
70         'wizard_id': fields.many2one('base.partner.merge.automatic.wizard',
71                                      'Wizard'),
72         'min_id': fields.integer('MinID'),
73         'aggr_ids': fields.char('Ids', required=True),
74     }
75
76     _order = 'min_id asc'
77
78
79 class MergePartnerAutomatic(osv.TransientModel):
80     """
81         The idea behind this wizard is to create a list of potential partners to
82         merge. We use two objects, the first one is the wizard for the end-user.
83         And the second will contain the partner list to merge.
84     """
85     _name = 'base.partner.merge.automatic.wizard'
86
87     _columns = {
88         # Group by
89         'group_by_email': fields.boolean('Email'),
90         'group_by_name': fields.boolean('Name'),
91         'group_by_is_company': fields.boolean('Is Company'),
92         'group_by_vat': fields.boolean('VAT'),
93         'group_by_parent_id': fields.boolean('Parent Company'),
94
95         'state': fields.selection([('option', 'Option'),
96                                    ('selection', 'Selection'),
97                                    ('finished', 'Finished')],
98                                   'State',
99                                   readonly=True,
100                                   required=True),
101         'number_group': fields.integer("Group of Contacts", readonly=True),
102         'current_line_id': fields.many2one('base.partner.merge.line', 'Current Line'),
103         'line_ids': fields.one2many('base.partner.merge.line', 'wizard_id', 'Lines'),
104         'partner_ids': fields.many2many('res.partner', string='Contacts'),
105         'dst_partner_id': fields.many2one('res.partner', string='Destination Contact'),
106
107         'exclude_contact': fields.boolean('A user associated to the contact'),
108         'exclude_journal_item': fields.boolean('Journal Items associated to the contact'),
109         'maximum_group': fields.integer("Maximum of Group of Contacts"),
110     }
111
112     def default_get(self, cr, uid, fields, context=None):
113         if context is None:
114             context = {}
115         res = super(MergePartnerAutomatic, self).default_get(cr, uid, fields, context)
116         if context.get('active_model') == 'res.partner' and context.get('active_ids'):
117             partner_ids = context['active_ids']
118             res['state'] = 'selection'
119             res['partner_ids'] = partner_ids
120             res['dst_partner_id'] = self._get_ordered_partner(cr, uid, partner_ids, context=context)[-1].id
121         return res
122
123     _defaults = {
124         'state': 'option'
125     }
126
127     def get_fk_on(self, cr, table):
128         q = """  SELECT cl1.relname as table,
129                         att1.attname as column
130                    FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
131                         pg_attribute as att1, pg_attribute as att2
132                   WHERE con.conrelid = cl1.oid
133                     AND con.confrelid = cl2.oid
134                     AND array_lower(con.conkey, 1) = 1
135                     AND con.conkey[1] = att1.attnum
136                     AND att1.attrelid = cl1.oid
137                     AND cl2.relname = %s
138                     AND att2.attname = 'id'
139                     AND array_lower(con.confkey, 1) = 1
140                     AND con.confkey[1] = att2.attnum
141                     AND att2.attrelid = cl2.oid
142                     AND con.contype = 'f'
143         """
144         return cr.execute(q, (table,))
145
146     def _update_foreign_keys(self, cr, uid, src_partners, dst_partner, context=None):
147         _logger.debug('_update_foreign_keys for dst_partner: %s for src_partners: %r', dst_partner.id, list(map(operator.attrgetter('id'), src_partners)))
148
149         # find the many2one relation to a partner
150         proxy = self.pool.get('res.partner')
151         self.get_fk_on(cr, 'res_partner')
152
153         # ignore two tables
154
155         for table, column in cr.fetchall():
156             if 'base_partner_merge_' in table:
157                 continue
158             partner_ids = tuple(map(int, src_partners))
159
160             query = "SELECT column_name FROM information_schema.columns WHERE table_name LIKE '%s'" % (table)
161             cr.execute(query, ())
162             columns = []
163             for data in cr.fetchall():
164                 if data[0] != column:
165                     columns.append(data[0])
166
167             query_dic = {
168                 'table': table,
169                 'column': column,
170                 'value': columns[0],
171             }
172             if len(columns) <= 1:
173                 # unique key treated
174                 query = """
175                     UPDATE "%(table)s" as ___tu
176                     SET %(column)s = %%s
177                     WHERE
178                         %(column)s = %%s AND
179                         NOT EXISTS (
180                             SELECT 1
181                             FROM "%(table)s" as ___tw
182                             WHERE
183                                 %(column)s = %%s AND
184                                 ___tu.%(value)s = ___tw.%(value)s
185                         )""" % query_dic
186                 for partner_id in partner_ids:
187                     cr.execute(query, (dst_partner.id, partner_id, dst_partner.id))
188             else:
189                 cr.execute("SAVEPOINT recursive_partner_savepoint")
190                 try:
191                     query = 'UPDATE "%(table)s" SET %(column)s = %%s WHERE %(column)s IN %%s' % query_dic
192                     cr.execute(query, (dst_partner.id, partner_ids,))
193
194                     if column == proxy._parent_name and table == 'res_partner':
195                         query = """
196                             WITH RECURSIVE cycle(id, parent_id) AS (
197                                     SELECT id, parent_id FROM res_partner
198                                 UNION
199                                     SELECT  cycle.id, res_partner.parent_id
200                                     FROM    res_partner, cycle
201                                     WHERE   res_partner.id = cycle.parent_id AND
202                                             cycle.id != cycle.parent_id
203                             )
204                             SELECT id FROM cycle WHERE id = parent_id AND id = %s
205                         """
206                         cr.execute(query, (dst_partner.id,))
207                         if cr.fetchall():
208                             cr.execute("ROLLBACK TO SAVEPOINT recursive_partner_savepoint")
209                 finally:
210                     cr.execute("RELEASE SAVEPOINT recursive_partner_savepoint")
211
212     def _update_reference_fields(self, cr, uid, src_partners, dst_partner, context=None):
213         _logger.debug('_update_reference_fields for dst_partner: %s for src_partners: %r', dst_partner.id, list(map(operator.attrgetter('id'), src_partners)))
214
215         def update_records(model, src, field_model='model', field_id='res_id', context=None):
216             proxy = self.pool.get(model)
217             if proxy is None:
218                 return
219             domain = [(field_model, '=', 'res.partner'), (field_id, '=', src.id)]
220             ids = proxy.search(cr, openerp.SUPERUSER_ID, domain, context=context)
221             return proxy.write(cr, openerp.SUPERUSER_ID, ids, {field_id: dst_partner.id}, context=context)
222
223         update_records = functools.partial(update_records, context=context)
224
225         for partner in src_partners:
226             update_records('calendar', src=partner, field_model='model_id.model')
227             update_records('ir.attachment', src=partner, field_model='res_model')
228             update_records('mail.followers', src=partner, field_model='res_model')
229             update_records('mail.message', src=partner)
230             update_records('marketing.campaign.workitem', src=partner, field_model='object_id.model')
231             update_records('ir.model.data', src=partner)
232
233         proxy = self.pool['ir.model.fields']
234         domain = [('ttype', '=', 'reference')]
235         record_ids = proxy.search(cr, openerp.SUPERUSER_ID, domain, context=context)
236
237         for record in proxy.browse(cr, openerp.SUPERUSER_ID, record_ids, context=context):
238             try:
239                 proxy_model = self.pool[record.model]
240                 field_type = proxy_model._columns[record.name].__class__._type
241             except KeyError:
242                 # unknown model or field => skip
243                 continue
244
245             if field_type == 'function':
246                 continue
247
248             for partner in src_partners:
249                 domain = [
250                     (record.name, '=', 'res.partner,%d' % partner.id)
251                 ]
252                 model_ids = proxy_model.search(cr, openerp.SUPERUSER_ID, domain, context=context)
253                 values = {
254                     record.name: 'res.partner,%d' % dst_partner.id,
255                 }
256                 proxy_model.write(cr, openerp.SUPERUSER_ID, model_ids, values, context=context)
257
258     def _update_values(self, cr, uid, src_partners, dst_partner, context=None):
259         _logger.debug('_update_values for dst_partner: %s for src_partners: %r', dst_partner.id, list(map(operator.attrgetter('id'), src_partners)))
260
261         columns = dst_partner._columns
262         def write_serializer(column, item):
263             if isinstance(item, browse_record):
264                 return item.id
265             else:
266                 return item
267
268         values = dict()
269         for column, field in columns.iteritems():
270             if field._type not in ('many2many', 'one2many') and not isinstance(field, fields.function):
271                 for item in itertools.chain(src_partners, [dst_partner]):
272                     if item[column]:
273                         values[column] = write_serializer(column, item[column])
274
275         values.pop('id', None)
276         parent_id = values.pop('parent_id', None)
277         dst_partner.write(values)
278         if parent_id and parent_id != dst_partner.id:
279             try:
280                 dst_partner.write({'parent_id': parent_id})
281             except (osv.except_osv, orm.except_orm):
282                 _logger.info('Skip recursive partner hierarchies for parent_id %s of partner: %s', parent_id, dst_partner.id)
283
284     @mute_logger('openerp.osv.expression', 'openerp.models')
285     def _merge(self, cr, uid, partner_ids, dst_partner=None, context=None):
286         proxy = self.pool.get('res.partner')
287
288         partner_ids = proxy.exists(cr, uid, list(partner_ids), context=context)
289         if len(partner_ids) < 2:
290             return
291
292         if len(partner_ids) > 3:
293             raise osv.except_osv(_('Error'), _("For safety reasons, you cannot merge more than 3 contacts together. You can re-open the wizard several times if needed."))
294
295         if openerp.SUPERUSER_ID != uid and len(set(partner.email for partner in proxy.browse(cr, uid, partner_ids, context=context))) > 1:
296             raise osv.except_osv(_('Error'), _("All contacts must have the same email. Only the Administrator can merge contacts with different emails."))
297
298         if dst_partner and dst_partner.id in partner_ids:
299             src_partners = proxy.browse(cr, uid, [id for id in partner_ids if id != dst_partner.id], context=context)
300         else:
301             ordered_partners = self._get_ordered_partner(cr, uid, partner_ids, context)
302             dst_partner = ordered_partners[-1]
303             src_partners = ordered_partners[:-1]
304         _logger.info("dst_partner: %s", dst_partner.id)
305
306         if openerp.SUPERUSER_ID != uid and self._model_is_installed(cr, uid, 'account.move.line', context=context) and \
307                 self.pool.get('account.move.line').search(cr, openerp.SUPERUSER_ID, [('partner_id', 'in', [partner.id for partner in src_partners])], context=context):
308             raise osv.except_osv(_('Error'), _("Only the destination contact may be linked to existing Journal Items. Please ask the Administrator if you need to merge several contacts linked to existing Journal Items."))
309
310         call_it = lambda function: function(cr, uid, src_partners, dst_partner,
311                                             context=context)
312
313         call_it(self._update_foreign_keys)
314         call_it(self._update_reference_fields)
315         call_it(self._update_values)
316
317         _logger.info('(uid = %s) merged the partners %r with %s', uid, list(map(operator.attrgetter('id'), src_partners)), dst_partner.id)
318         dst_partner.message_post(body='%s %s'%(_("Merged with the following partners:"), ", ".join('%s<%s>(ID %s)' % (p.name, p.email or 'n/a', p.id) for p in src_partners)))
319         
320         for partner in src_partners:
321             partner.unlink()
322
323     def clean_emails(self, cr, uid, context=None):
324         """
325         Clean the email address of the partner, if there is an email field with
326         a mimum of two addresses, the system will create a new partner, with the
327         information of the previous one and will copy the new cleaned email into
328         the email field.
329         """
330         context = dict(context or {})
331
332         proxy_model = self.pool['ir.model.fields']
333         field_ids = proxy_model.search(cr, uid, [('model', '=', 'res.partner'),
334                                                  ('ttype', 'like', '%2many')],
335                                        context=context)
336         fields = proxy_model.read(cr, uid, field_ids, context=context)
337         reset_fields = dict((field['name'], []) for field in fields)
338
339         proxy_partner = self.pool['res.partner']
340         context['active_test'] = False
341         ids = proxy_partner.search(cr, uid, [], context=context)
342
343         fields = ['name', 'var' 'partner_id' 'is_company', 'email']
344         partners = proxy_partner.read(cr, uid, ids, fields, context=context)
345
346         partners.sort(key=operator.itemgetter('id'))
347         partners_len = len(partners)
348
349         _logger.info('partner_len: %r', partners_len)
350
351         for idx, partner in enumerate(partners):
352             if not partner['email']:
353                 continue
354
355             percent = (idx / float(partners_len)) * 100.0
356             _logger.info('idx: %r', idx)
357             _logger.info('percent: %r', percent)
358             try:
359                 emails = sanitize_email(partner['email'])
360                 head, tail = emails[:1], emails[1:]
361                 email = head[0] if head else False
362
363                 proxy_partner.write(cr, uid, [partner['id']],
364                                     {'email': email}, context=context)
365
366                 for email in tail:
367                     values = dict(reset_fields, email=email)
368                     proxy_partner.copy(cr, uid, partner['id'], values,
369                                        context=context)
370
371             except Exception:
372                 _logger.exception("There is a problem with this partner: %r", partner)
373                 raise
374         return True
375
376     def close_cb(self, cr, uid, ids, context=None):
377         return {'type': 'ir.actions.act_window_close'}
378
379     def _generate_query(self, fields, maximum_group=100):
380         sql_fields = []
381         for field in fields:
382             if field in ['email', 'name']:
383                 sql_fields.append('lower(%s)' % field)
384             elif field in ['vat']:
385                 sql_fields.append("replace(%s, ' ', '')" % field)
386             else:
387                 sql_fields.append(field)
388
389         group_fields = ', '.join(sql_fields)
390
391         filters = []
392         for field in fields:
393             if field in ['email', 'name', 'vat']:
394                 filters.append((field, 'IS NOT', 'NULL'))
395
396         criteria = ' AND '.join('%s %s %s' % (field, operator, value)
397                                 for field, operator, value in filters)
398
399         text = [
400             "SELECT min(id), array_agg(id)",
401             "FROM res_partner",
402         ]
403
404         if criteria:
405             text.append('WHERE %s' % criteria)
406
407         text.extend([
408             "GROUP BY %s" % group_fields,
409             "HAVING COUNT(*) >= 2",
410             "ORDER BY min(id)",
411         ])
412
413         if maximum_group:
414             text.extend([
415                 "LIMIT %s" % maximum_group,
416             ])
417
418         return ' '.join(text)
419
420     def _compute_selected_groupby(self, this):
421         group_by_str = 'group_by_'
422         group_by_len = len(group_by_str)
423
424         fields = [
425             key[group_by_len:]
426             for key in self._columns.keys()
427             if key.startswith(group_by_str)
428         ]
429
430         groups = [
431             field
432             for field in fields
433             if getattr(this, '%s%s' % (group_by_str, field), False)
434         ]
435
436         if not groups:
437             raise osv.except_osv(_('Error'),
438                                  _("You have to specify a filter for your selection"))
439
440         return groups
441
442     def next_cb(self, cr, uid, ids, context=None):
443         """
444         Don't compute any thing
445         """
446         context = dict(context or {}, active_test=False)
447         this = self.browse(cr, uid, ids[0], context=context)
448         if this.current_line_id:
449             this.current_line_id.unlink()
450         return self._next_screen(cr, uid, this, context)
451
452     def _get_ordered_partner(self, cr, uid, partner_ids, context=None):
453         partners = self.pool.get('res.partner').browse(cr, uid, list(partner_ids), context=context)
454         ordered_partners = sorted(sorted(partners,
455                             key=operator.attrgetter('create_date'), reverse=True),
456                                 key=operator.attrgetter('active'), reverse=True)
457         return ordered_partners
458
459     def _next_screen(self, cr, uid, this, context=None):
460         this.refresh()
461         values = {}
462         if this.line_ids:
463             # in this case, we try to find the next record.
464             current_line = this.line_ids[0]
465             current_partner_ids = literal_eval(current_line.aggr_ids)
466             values.update({
467                 'current_line_id': current_line.id,
468                 'partner_ids': [(6, 0, current_partner_ids)],
469                 'dst_partner_id': self._get_ordered_partner(cr, uid, current_partner_ids, context)[-1].id,
470                 'state': 'selection',
471             })
472         else:
473             values.update({
474                 'current_line_id': False,
475                 'partner_ids': [],
476                 'state': 'finished',
477             })
478
479         this.write(values)
480
481         return {
482             'type': 'ir.actions.act_window',
483             'res_model': this._name,
484             'res_id': this.id,
485             'view_mode': 'form',
486             'target': 'new',
487         }
488
489     def _model_is_installed(self, cr, uid, model, context=None):
490         proxy = self.pool.get('ir.model')
491         domain = [('model', '=', model)]
492         return proxy.search_count(cr, uid, domain, context=context) > 0
493
494     def _partner_use_in(self, cr, uid, aggr_ids, models, context=None):
495         """
496         Check if there is no occurence of this group of partner in the selected
497         model
498         """
499         for model, field in models.iteritems():
500             proxy = self.pool.get(model)
501             domain = [(field, 'in', aggr_ids)]
502             if proxy.search_count(cr, uid, domain, context=context):
503                 return True
504         return False
505
506     def compute_models(self, cr, uid, ids, context=None):
507         """
508         Compute the different models needed by the system if you want to exclude
509         some partners.
510         """
511         assert is_integer_list(ids)
512
513         this = self.browse(cr, uid, ids[0], context=context)
514
515         models = {}
516         if this.exclude_contact:
517             models['res.users'] = 'partner_id'
518
519         if self._model_is_installed(cr, uid, 'account.move.line', context=context) and this.exclude_journal_item:
520             models['account.move.line'] = 'partner_id'
521
522         return models
523
524     def _process_query(self, cr, uid, ids, query, context=None):
525         """
526         Execute the select request and write the result in this wizard
527         """
528         proxy = self.pool.get('base.partner.merge.line')
529         this = self.browse(cr, uid, ids[0], context=context)
530         models = self.compute_models(cr, uid, ids, context=context)
531         cr.execute(query)
532
533         counter = 0
534         for min_id, aggr_ids in cr.fetchall():
535             if models and self._partner_use_in(cr, uid, aggr_ids, models, context=context):
536                 continue
537             values = {
538                 'wizard_id': this.id,
539                 'min_id': min_id,
540                 'aggr_ids': aggr_ids,
541             }
542
543             proxy.create(cr, uid, values, context=context)
544             counter += 1
545
546         values = {
547             'state': 'selection',
548             'number_group': counter,
549         }
550
551         this.write(values)
552
553         _logger.info("counter: %s", counter)
554
555     def start_process_cb(self, cr, uid, ids, context=None):
556         """
557         Start the process.
558         * Compute the selected groups (with duplication)
559         * If the user has selected the 'exclude_XXX' fields, avoid the partners.
560         """
561         assert is_integer_list(ids)
562
563         context = dict(context or {}, active_test=False)
564         this = self.browse(cr, uid, ids[0], context=context)
565         groups = self._compute_selected_groupby(this)
566         query = self._generate_query(groups, this.maximum_group)
567         self._process_query(cr, uid, ids, query, context=context)
568
569         return self._next_screen(cr, uid, this, context)
570
571     def automatic_process_cb(self, cr, uid, ids, context=None):
572         assert is_integer_list(ids)
573         this = self.browse(cr, uid, ids[0], context=context)
574         this.start_process_cb()
575         this.refresh()
576
577         for line in this.line_ids:
578             partner_ids = literal_eval(line.aggr_ids)
579             self._merge(cr, uid, partner_ids, context=context)
580             line.unlink()
581             cr.commit()
582
583         this.write({'state': 'finished'})
584         return {
585             'type': 'ir.actions.act_window',
586             'res_model': this._name,
587             'res_id': this.id,
588             'view_mode': 'form',
589             'target': 'new',
590         }
591
592     def parent_migration_process_cb(self, cr, uid, ids, context=None):
593         assert is_integer_list(ids)
594
595         context = dict(context or {}, active_test=False)
596         this = self.browse(cr, uid, ids[0], context=context)
597
598         query = """
599             SELECT
600                 min(p1.id),
601                 array_agg(DISTINCT p1.id)
602             FROM
603                 res_partner as p1
604             INNER join
605                 res_partner as p2
606             ON
607                 p1.email = p2.email AND
608                 p1.name = p2.name AND
609                 (p1.parent_id = p2.id OR p1.id = p2.parent_id)
610             WHERE
611                 p2.id IS NOT NULL
612             GROUP BY
613                 p1.email,
614                 p1.name,
615                 CASE WHEN p1.parent_id = p2.id THEN p2.id
616                     ELSE p1.id
617                 END
618             HAVING COUNT(*) >= 2
619             ORDER BY
620                 min(p1.id)
621         """
622
623         self._process_query(cr, uid, ids, query, context=context)
624
625         for line in this.line_ids:
626             partner_ids = literal_eval(line.aggr_ids)
627             self._merge(cr, uid, partner_ids, context=context)
628             line.unlink()
629             cr.commit()
630
631         this.write({'state': 'finished'})
632
633         cr.execute("""
634             UPDATE
635                 res_partner
636             SET
637                 is_company = NULL,
638                 parent_id = NULL
639             WHERE
640                 parent_id = id
641         """)
642
643         return {
644             'type': 'ir.actions.act_window',
645             'res_model': this._name,
646             'res_id': this.id,
647             'view_mode': 'form',
648             'target': 'new',
649         }
650
651     def update_all_process_cb(self, cr, uid, ids, context=None):
652         assert is_integer_list(ids)
653
654         # WITH RECURSIVE cycle(id, parent_id) AS (
655         #     SELECT id, parent_id FROM res_partner
656         #   UNION
657         #     SELECT  cycle.id, res_partner.parent_id
658         #     FROM    res_partner, cycle
659         #     WHERE   res_partner.id = cycle.parent_id AND
660         #             cycle.id != cycle.parent_id
661         # )
662         # UPDATE  res_partner
663         # SET     parent_id = NULL
664         # WHERE   id in (SELECT id FROM cycle WHERE id = parent_id);
665
666         this = self.browse(cr, uid, ids[0], context=context)
667
668         self.parent_migration_process_cb(cr, uid, ids, context=None)
669
670         list_merge = [
671             {'group_by_vat': True, 'group_by_email': True, 'group_by_name': True},
672             # {'group_by_name': True, 'group_by_is_company': True, 'group_by_parent_id': True},
673             # {'group_by_email': True, 'group_by_is_company': True, 'group_by_parent_id': True},
674             # {'group_by_name': True, 'group_by_vat': True, 'group_by_is_company': True, 'exclude_journal_item': True},
675             # {'group_by_email': True, 'group_by_vat': True, 'group_by_is_company': True, 'exclude_journal_item': True},
676             # {'group_by_email': True, 'group_by_is_company': True, 'exclude_contact': True, 'exclude_journal_item': True},
677             # {'group_by_name': True, 'group_by_is_company': True, 'exclude_contact': True, 'exclude_journal_item': True}
678         ]
679
680         for merge_value in list_merge:
681             id = self.create(cr, uid, merge_value, context=context)
682             self.automatic_process_cb(cr, uid, [id], context=context)
683
684         cr.execute("""
685             UPDATE
686                 res_partner
687             SET
688                 is_company = NULL
689             WHERE
690                 parent_id IS NOT NULL AND
691                 is_company IS NOT NULL
692         """)
693
694         # cr.execute("""
695         #     UPDATE
696         #         res_partner as p1
697         #     SET
698         #         is_company = NULL,
699         #         parent_id = (
700         #             SELECT  p2.id
701         #             FROM    res_partner as p2
702         #             WHERE   p2.email = p1.email AND
703         #                     p2.parent_id != p2.id
704         #             LIMIT 1
705         #         )
706         #     WHERE
707         #         p1.parent_id = p1.id
708         # """)
709
710         return self._next_screen(cr, uid, this, context)
711
712     def merge_cb(self, cr, uid, ids, context=None):
713         assert is_integer_list(ids)
714
715         context = dict(context or {}, active_test=False)
716         this = self.browse(cr, uid, ids[0], context=context)
717
718         partner_ids = set(map(int, this.partner_ids))
719         if not partner_ids:
720             this.write({'state': 'finished'})
721             return {
722                 'type': 'ir.actions.act_window',
723                 'res_model': this._name,
724                 'res_id': this.id,
725                 'view_mode': 'form',
726                 'target': 'new',
727             }
728
729         self._merge(cr, uid, partner_ids, this.dst_partner_id, context=context)
730
731         if this.current_line_id:
732             this.current_line_id.unlink()
733
734         return self._next_screen(cr, uid, this, context)
735
736     def auto_set_parent_id(self, cr, uid, ids, context=None):
737         assert is_integer_list(ids)
738
739         # select partner who have one least invoice
740         partner_treated = ['@gmail.com']
741         cr.execute("""  SELECT p.id, p.email
742                         FROM res_partner as p 
743                         LEFT JOIN account_invoice as a 
744                         ON p.id = a.partner_id AND a.state in ('open','paid')
745                         WHERE p.grade_id is NOT NULL
746                         GROUP BY p.id
747                         ORDER BY COUNT(a.id) DESC
748                 """)
749         re_email = re.compile(r".*@")
750         for id, email in cr.fetchall():
751             # check email domain
752             email = re_email.sub("@", email or "")
753             if not email or email in partner_treated:
754                 continue
755             partner_treated.append(email)
756
757             # don't update the partners if they are more of one who have invoice
758             cr.execute("""  SELECT *
759                             FROM res_partner as p
760                             WHERE p.id != %s AND p.email LIKE '%%%s' AND
761                                 EXISTS (SELECT * FROM account_invoice as a WHERE p.id = a.partner_id AND a.state in ('open','paid'))
762                     """ % (id, email))
763
764             if len(cr.fetchall()) > 1:
765                 _logger.info("%s MORE OF ONE COMPANY", email)
766                 continue
767
768             # to display changed values
769             cr.execute("""  SELECT id,email
770                             FROM res_partner
771                             WHERE parent_id != %s AND id != %s AND email LIKE '%%%s'
772                     """ % (id, id, email))
773             _logger.info("%r", cr.fetchall())
774
775             # upgrade
776             cr.execute("""  UPDATE res_partner
777                             SET parent_id = %s
778                             WHERE id != %s AND email LIKE '%%%s'
779                     """ % (id, id, email))
780         return False