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.

914 lines
33 KiB

11 years ago
9 years ago
10 years ago
11 years ago
11 years ago
9 years ago
9 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
9 years ago
11 years ago
11 years ago
9 years ago
11 years ago
10 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 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. import openerp.osv.fields as fields
  16. from openerp.osv.orm import TransientModel, browse_record
  17. from openerp.exceptions import except_orm
  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(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(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. legacy = proxy_model._columns.get(record.name)
  251. field_spec = proxy_model._fields.get(record.name)
  252. if isinstance(legacy, fields.function) or field_spec.compute:
  253. continue
  254. for partner in src_partners:
  255. domain = [
  256. (record.name, '=', 'res.partner,%d' % partner.id)
  257. ]
  258. model_ids = proxy_model.search(cr, openerp.SUPERUSER_ID,
  259. domain, context=context)
  260. values = {
  261. record.name: 'res.partner,%d' % dst_partner.id,
  262. }
  263. proxy_model.write(cr, openerp.SUPERUSER_ID, model_ids, values,
  264. context=context)
  265. def _update_values(self, cr, uid, src_partners, dst_partner, context=None):
  266. _logger.debug('_update_values for dst_partner: %s for src_partners: '
  267. '%r',
  268. dst_partner.id,
  269. list(map(operator.attrgetter('id'), src_partners)))
  270. columns = dst_partner._columns
  271. def write_serializer(column, item):
  272. if isinstance(item, browse_record):
  273. return item.id
  274. else:
  275. return item
  276. values = dict()
  277. for column, field in columns.iteritems():
  278. if (field._type not in ('many2many', 'one2many') and
  279. not isinstance(field, fields.function)):
  280. for item in itertools.chain(src_partners, [dst_partner]):
  281. if item[column]:
  282. values[column] = write_serializer(column,
  283. item[column])
  284. values.pop('id', None)
  285. parent_id = values.pop('parent_id', None)
  286. dst_partner.write(values)
  287. if parent_id and parent_id != dst_partner.id:
  288. try:
  289. dst_partner.write({'parent_id': parent_id})
  290. except except_orm:
  291. _logger.info('Skip recursive partner hierarchies for '
  292. 'parent_id %s of partner: %s',
  293. parent_id, dst_partner.id)
  294. @mute_logger('openerp.osv.expression', 'openerp.osv.orm')
  295. def _merge(self, cr, uid, partner_ids, dst_partner=None, context=None):
  296. proxy = self.pool.get('res.partner')
  297. partner_ids = proxy.exists(cr, uid, list(partner_ids),
  298. context=context)
  299. if len(partner_ids) < 2:
  300. return
  301. if len(partner_ids) > 3:
  302. raise except_orm(
  303. _('Error'),
  304. _("For safety reasons, you cannot merge more than 3 contacts "
  305. "together. You can re-open the wizard several times if "
  306. "needed."))
  307. if (openerp.SUPERUSER_ID != uid and
  308. len(set(partner.email for partner
  309. in proxy.browse(cr, uid, partner_ids,
  310. context=context))) > 1):
  311. raise except_orm(
  312. _('Error'),
  313. _("All contacts must have the same email. Only the "
  314. "Administrator can merge contacts with different emails."))
  315. if dst_partner and dst_partner.id in partner_ids:
  316. src_partners = proxy.browse(cr, uid,
  317. [id for id in partner_ids
  318. if id != dst_partner.id],
  319. context=context)
  320. else:
  321. ordered_partners = self._get_ordered_partner(cr, uid, partner_ids,
  322. context)
  323. dst_partner = ordered_partners[-1]
  324. src_partners = ordered_partners[:-1]
  325. _logger.info("dst_partner: %s", dst_partner.id)
  326. if (openerp.SUPERUSER_ID != uid and
  327. self._model_is_installed(
  328. cr, uid, 'account.move.line', context=context) and
  329. self.pool['account.move.line'].search(
  330. cr, openerp.SUPERUSER_ID,
  331. [('partner_id', 'in', [partner.id for partner
  332. in src_partners])],
  333. context=context)):
  334. raise except_orm(
  335. _('Error'),
  336. _("Only the destination contact may be linked to existing "
  337. "Journal Items. Please ask the Administrator if you need to"
  338. " merge several contacts linked to existing Journal "
  339. "Items."))
  340. self._update_foreign_keys(
  341. cr, uid, src_partners, dst_partner, context=context)
  342. self._update_reference_fields(
  343. cr, uid, src_partners, dst_partner, context=context)
  344. self._update_values(
  345. cr, uid, src_partners, dst_partner, context=context)
  346. _logger.info('(uid = %s) merged the partners %r with %s',
  347. uid,
  348. list(map(operator.attrgetter('id'), src_partners)),
  349. dst_partner.id)
  350. dst_partner.message_post(
  351. body='%s %s' % (
  352. _("Merged with the following partners:"),
  353. ", ".join(
  354. '%s<%s>(ID %s)' % (p.name, p.email or 'n/a', p.id)
  355. for p in src_partners
  356. )
  357. )
  358. )
  359. for partner in src_partners:
  360. partner.unlink()
  361. def clean_emails(self, cr, uid, context=None):
  362. """
  363. Clean the email address of the partner, if there is an email field
  364. with a minimum of two addresses, the system will create a new partner,
  365. with the information of the previous one and will copy the new cleaned
  366. email into the email field.
  367. """
  368. if context is None:
  369. context = {}
  370. proxy_model = self.pool['ir.model.fields']
  371. field_ids = proxy_model.search(cr, uid,
  372. [('model', '=', 'res.partner'),
  373. ('ttype', 'like', '%2many')],
  374. context=context)
  375. fields = proxy_model.read(cr, uid, field_ids, context=context)
  376. reset_fields = dict((field['name'], []) for field in fields)
  377. proxy_partner = self.pool['res.partner']
  378. context['active_test'] = False
  379. ids = proxy_partner.search(cr, uid, [], context=context)
  380. fields = ['name', 'var' 'partner_id' 'is_company', 'email']
  381. partners = proxy_partner.read(cr, uid, ids, fields, context=context)
  382. partners.sort(key=operator.itemgetter('id'))
  383. partners_len = len(partners)
  384. _logger.info('partner_len: %r', partners_len)
  385. for idx, partner in enumerate(partners):
  386. if not partner['email']:
  387. continue
  388. percent = (idx / float(partners_len)) * 100.0
  389. _logger.info('idx: %r', idx)
  390. _logger.info('percent: %r', percent)
  391. try:
  392. emails = sanitize_email(partner['email'])
  393. head, tail = emails[:1], emails[1:]
  394. email = head[0] if head else False
  395. proxy_partner.write(cr, uid, [partner['id']],
  396. {'email': email}, context=context)
  397. for email in tail:
  398. values = dict(reset_fields, email=email)
  399. proxy_partner.copy(cr, uid, partner['id'], values,
  400. context=context)
  401. except Exception:
  402. _logger.exception("There is a problem with this partner: %r",
  403. partner)
  404. raise
  405. return True
  406. def close_cb(self, cr, uid, ids, context=None):
  407. return {'type': 'ir.actions.act_window_close'}
  408. def _generate_query(self, fields, maximum_group=100):
  409. group_fields = ', '.join(fields)
  410. filters = []
  411. for field in fields:
  412. if field in ['email', 'name']:
  413. filters.append((field, 'IS NOT', 'NULL'))
  414. criteria = ' AND '.join('%s %s %s' % (field, operator, value)
  415. for field, operator, value in filters)
  416. text = [
  417. "SELECT min(id), array_agg(id)",
  418. "FROM res_partner",
  419. ]
  420. if criteria:
  421. text.append('WHERE %s' % criteria)
  422. text.extend([
  423. "GROUP BY %s" % group_fields,
  424. "HAVING COUNT(*) >= 2",
  425. "ORDER BY min(id)",
  426. ])
  427. if maximum_group:
  428. text.extend([
  429. "LIMIT %s" % maximum_group,
  430. ])
  431. return ' '.join(text)
  432. def _compute_selected_groupby(self, this):
  433. group_by_str = 'group_by_'
  434. group_by_len = len(group_by_str)
  435. fields = [
  436. key[group_by_len:]
  437. for key in self._columns.keys()
  438. if key.startswith(group_by_str)
  439. ]
  440. groups = [
  441. field
  442. for field in fields
  443. if getattr(this, '%s%s' % (group_by_str, field), False)
  444. ]
  445. if not groups:
  446. raise except_orm(_('Error'),
  447. _("You have to specify a filter for your "
  448. "selection"))
  449. return groups
  450. def next_cb(self, cr, uid, ids, context=None):
  451. """
  452. Don't compute any thing
  453. """
  454. context = dict(context or {}, active_test=False)
  455. this = self.browse(cr, uid, ids[0], context=context)
  456. if this.current_line_id:
  457. this.current_line_id.unlink()
  458. return self._next_screen(cr, uid, this, context)
  459. def _get_ordered_partner(self, cr, uid, partner_ids, context=None):
  460. partners = self.pool.get('res.partner'
  461. ).browse(cr, uid,
  462. list(partner_ids),
  463. context=context)
  464. ordered_partners = sorted(
  465. sorted(
  466. partners,
  467. key=operator.attrgetter('create_date'),
  468. reverse=True
  469. ),
  470. key=operator.attrgetter('active'),
  471. reverse=True
  472. )
  473. return ordered_partners
  474. def _next_screen(self, cr, uid, this, context=None):
  475. this.refresh()
  476. values = {}
  477. if this.line_ids:
  478. # in this case, we try to find the next record.
  479. current_line = this.line_ids[0]
  480. current_partner_ids = literal_eval(current_line.aggr_ids)
  481. values.update({
  482. 'current_line_id': current_line.id,
  483. 'partner_ids': [(6, 0, current_partner_ids)],
  484. 'dst_partner_id': self._get_ordered_partner(
  485. cr, uid,
  486. current_partner_ids,
  487. context
  488. )[-1].id,
  489. 'state': 'selection',
  490. })
  491. else:
  492. values.update({
  493. 'current_line_id': False,
  494. 'partner_ids': [],
  495. 'state': 'finished',
  496. })
  497. this.write(values)
  498. return {
  499. 'type': 'ir.actions.act_window',
  500. 'res_model': this._name,
  501. 'res_id': this.id,
  502. 'view_mode': 'form',
  503. 'target': 'new',
  504. }
  505. def _model_is_installed(self, cr, uid, model, context=None):
  506. proxy = self.pool.get('ir.model')
  507. domain = [('model', '=', model)]
  508. return proxy.search_count(cr, uid, domain, context=context) > 0
  509. def _partner_use_in(self, cr, uid, aggr_ids, models, context=None):
  510. """
  511. Check if there is no occurence of this group of partner in the selected
  512. model
  513. """
  514. for model, field in models.iteritems():
  515. proxy = self.pool.get(model)
  516. domain = [(field, 'in', aggr_ids)]
  517. if proxy.search_count(cr, uid, domain, context=context):
  518. return True
  519. return False
  520. def compute_models(self, cr, uid, ids, context=None):
  521. """
  522. Compute the different models needed by the system if you want to
  523. exclude some partners.
  524. """
  525. assert is_integer_list(ids)
  526. this = self.browse(cr, uid, ids[0], context=context)
  527. models = {}
  528. if this.exclude_contact:
  529. models['res.users'] = 'partner_id'
  530. if (self._model_is_installed(
  531. cr, uid, 'account.move.line', context=context) and
  532. this.exclude_journal_item):
  533. models['account.move.line'] = 'partner_id'
  534. return models
  535. def _process_query(self, cr, uid, ids, query, context=None):
  536. """
  537. Execute the select request and write the result in this wizard
  538. """
  539. proxy = self.pool.get('base.partner.merge.line')
  540. this = self.browse(cr, uid, ids[0], context=context)
  541. models = self.compute_models(cr, uid, ids, context=context)
  542. cr.execute(query)
  543. counter = 0
  544. for min_id, aggr_ids in cr.fetchall():
  545. if models and self._partner_use_in(cr, uid, aggr_ids, models,
  546. context=context):
  547. continue
  548. values = {
  549. 'wizard_id': this.id,
  550. 'min_id': min_id,
  551. 'aggr_ids': aggr_ids,
  552. }
  553. proxy.create(cr, uid, values, context=context)
  554. counter += 1
  555. values = {
  556. 'state': 'selection',
  557. 'number_group': counter,
  558. }
  559. this.write(values)
  560. _logger.info("counter: %s", counter)
  561. def start_process_cb(self, cr, uid, ids, context=None):
  562. """
  563. Start the process.
  564. * Compute the selected groups (with duplication)
  565. * If the user has selected the 'exclude_XXX' fields, avoid the
  566. partners.
  567. """
  568. assert is_integer_list(ids)
  569. context = dict(context or {}, active_test=False)
  570. this = self.browse(cr, uid, ids[0], context=context)
  571. groups = self._compute_selected_groupby(this)
  572. query = self._generate_query(groups, this.maximum_group)
  573. self._process_query(cr, uid, ids, query, context=context)
  574. return self._next_screen(cr, uid, this, context)
  575. def automatic_process_cb(self, cr, uid, ids, context=None):
  576. assert is_integer_list(ids)
  577. this = self.browse(cr, uid, ids[0], context=context)
  578. this.start_process_cb()
  579. this.refresh()
  580. for line in this.line_ids:
  581. partner_ids = literal_eval(line.aggr_ids)
  582. self._merge(cr, uid, partner_ids, context=context)
  583. line.unlink()
  584. cr.commit()
  585. this.write({'state': 'finished'})
  586. return {
  587. 'type': 'ir.actions.act_window',
  588. 'res_model': this._name,
  589. 'res_id': this.id,
  590. 'view_mode': 'form',
  591. 'target': 'new',
  592. }
  593. def parent_migration_process_cb(self, cr, uid, ids, context=None):
  594. assert is_integer_list(ids)
  595. context = dict(context or {}, active_test=False)
  596. this = self.browse(cr, uid, ids[0], context=context)
  597. query = """
  598. SELECT
  599. min(p1.id),
  600. array_agg(DISTINCT p1.id)
  601. FROM
  602. res_partner as p1
  603. INNER join
  604. res_partner as p2
  605. ON
  606. p1.email = p2.email AND
  607. p1.name = p2.name AND
  608. (p1.parent_id = p2.id OR p1.id = p2.parent_id)
  609. WHERE
  610. p2.id IS NOT NULL
  611. GROUP BY
  612. p1.email,
  613. p1.name,
  614. CASE WHEN p1.parent_id = p2.id THEN p2.id
  615. ELSE p1.id
  616. END
  617. HAVING COUNT(*) >= 2
  618. ORDER BY
  619. min(p1.id)
  620. """
  621. self._process_query(cr, uid, ids, query, context=context)
  622. for line in this.line_ids:
  623. partner_ids = literal_eval(line.aggr_ids)
  624. self._merge(cr, uid, partner_ids, context=context)
  625. line.unlink()
  626. cr.commit()
  627. this.write({'state': 'finished'})
  628. cr.execute("""
  629. UPDATE
  630. res_partner
  631. SET
  632. is_company = NULL,
  633. parent_id = NULL
  634. WHERE
  635. parent_id = id
  636. """)
  637. return {
  638. 'type': 'ir.actions.act_window',
  639. 'res_model': this._name,
  640. 'res_id': this.id,
  641. 'view_mode': 'form',
  642. 'target': 'new',
  643. }
  644. def update_all_process_cb(self, cr, uid, ids, context=None):
  645. assert is_integer_list(ids)
  646. # WITH RECURSIVE cycle(id, parent_id) AS (
  647. # SELECT id, parent_id FROM res_partner
  648. # UNION
  649. # SELECT cycle.id, res_partner.parent_id
  650. # FROM res_partner, cycle
  651. # WHERE res_partner.id = cycle.parent_id AND
  652. # cycle.id != cycle.parent_id
  653. # )
  654. # UPDATE res_partner
  655. # SET parent_id = NULL
  656. # WHERE id in (SELECT id FROM cycle WHERE id = parent_id);
  657. this = self.browse(cr, uid, ids[0], context=context)
  658. self.parent_migration_process_cb(cr, uid, ids, context=None)
  659. list_merge = [
  660. {'group_by_vat': True,
  661. 'group_by_email': True,
  662. 'group_by_name': True},
  663. # {'group_by_name': True,
  664. # 'group_by_is_company': True,
  665. # 'group_by_parent_id': True},
  666. # {'group_by_email': True,
  667. # 'group_by_is_company': True,
  668. # 'group_by_parent_id': True},
  669. # {'group_by_name': True,
  670. # 'group_by_vat': True,
  671. # 'group_by_is_company': True,
  672. # 'exclude_journal_item': True},
  673. # {'group_by_email': True,
  674. # 'group_by_vat': True,
  675. # 'group_by_is_company': True,
  676. # 'exclude_journal_item': True},
  677. # {'group_by_email': True,
  678. # 'group_by_is_company': True,
  679. # 'exclude_contact': True,
  680. # 'exclude_journal_item': True},
  681. # {'group_by_name': True,
  682. # 'group_by_is_company': True,
  683. # 'exclude_contact': True,
  684. # 'exclude_journal_item': True}
  685. ]
  686. for merge_value in list_merge:
  687. id = self.create(cr, uid, merge_value, context=context)
  688. self.automatic_process_cb(cr, uid, [id], context=context)
  689. cr.execute("""
  690. UPDATE
  691. res_partner
  692. SET
  693. is_company = NULL
  694. WHERE
  695. parent_id IS NOT NULL AND
  696. is_company IS NOT NULL
  697. """)
  698. # cr.execute("""
  699. # UPDATE
  700. # res_partner as p1
  701. # SET
  702. # is_company = NULL,
  703. # parent_id = (
  704. # SELECT p2.id
  705. # FROM res_partner as p2
  706. # WHERE p2.email = p1.email AND
  707. # p2.parent_id != p2.id
  708. # LIMIT 1
  709. # )
  710. # WHERE
  711. # p1.parent_id = p1.id
  712. # """)
  713. return self._next_screen(cr, uid, this, context)
  714. def merge_cb(self, cr, uid, ids, context=None):
  715. assert is_integer_list(ids)
  716. context = dict(context or {}, active_test=False)
  717. this = self.browse(cr, uid, ids[0], context=context)
  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. self._merge(cr, uid, partner_ids, this.dst_partner_id,
  729. context=context)
  730. if this.current_line_id:
  731. this.current_line_id.unlink()
  732. return self._next_screen(cr, uid, this, context)
  733. def auto_set_parent_id(self, cr, uid, ids, context=None):
  734. assert is_integer_list(ids)
  735. # select partner who have one least invoice
  736. partner_treated = ['@gmail.com']
  737. cr.execute(""" SELECT p.id, p.email
  738. FROM res_partner as p
  739. LEFT JOIN account_invoice as a
  740. ON p.id = a.partner_id AND a.state in ('open','paid')
  741. WHERE p.grade_id is NOT NULL
  742. GROUP BY p.id
  743. ORDER BY COUNT(a.id) DESC
  744. """)
  745. re_email = re.compile(r".*@")
  746. for id, email in cr.fetchall():
  747. # check email domain
  748. email = re_email.sub("@", email or "")
  749. if not email or email in partner_treated:
  750. continue
  751. partner_treated.append(email)
  752. # don't update the partners if they are more of one who have
  753. # invoice
  754. cr.execute("""
  755. SELECT *
  756. FROM res_partner as p
  757. WHERE p.id != %s AND p.email LIKE '%%%s' AND
  758. EXISTS (SELECT * FROM account_invoice as a
  759. WHERE p.id = a.partner_id
  760. AND a.state in ('open','paid'))
  761. """ % (id, email))
  762. if len(cr.fetchall()) > 1:
  763. _logger.info("%s MORE OF ONE COMPANY", email)
  764. continue
  765. # to display changed values
  766. cr.execute(""" SELECT id,email
  767. FROM res_partner
  768. WHERE parent_id != %s
  769. AND id != %s AND email LIKE '%%%s'
  770. """ % (id, id, email))
  771. _logger.info("%r", cr.fetchall())
  772. # upgrade
  773. cr.execute(""" UPDATE res_partner
  774. SET parent_id = %s
  775. WHERE id != %s AND email LIKE '%%%s'
  776. """ % (id, id, email))
  777. return False