You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

852 lines
31 KiB

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