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.

913 lines
33 KiB

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