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.

895 lines
32 KiB

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