res_partner.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from odoo import api, fields, models
  4. class Partner(models.Model):
  5. _name = 'res.partner'
  6. _inherit = 'res.partner'
  7. team_id = fields.Many2one(
  8. 'crm.team', string='Sales Team',
  9. compute='_compute_team_id',
  10. precompute=True, # avoid queries post-create
  11. ondelete='set null', readonly=False, store=True)
  12. opportunity_ids = fields.One2many('crm.lead', 'partner_id', string='Opportunities', domain=[('type', '=', 'opportunity')])
  13. opportunity_count = fields.Integer("Opportunity", compute='_compute_opportunity_count')
  14. @api.model
  15. def default_get(self, fields):
  16. rec = super(Partner, self).default_get(fields)
  17. active_model = self.env.context.get('active_model')
  18. if active_model == 'crm.lead' and len(self.env.context.get('active_ids', [])) <= 1:
  19. lead = self.env[active_model].browse(self.env.context.get('active_id')).exists()
  20. if lead:
  21. rec.update(
  22. phone=lead.phone,
  23. mobile=lead.mobile,
  24. function=lead.function,
  25. title=lead.title.id,
  26. website=lead.website,
  27. street=lead.street,
  28. street2=lead.street2,
  29. city=lead.city,
  30. state_id=lead.state_id.id,
  31. country_id=lead.country_id.id,
  32. zip=lead.zip,
  33. )
  34. return rec
  35. @api.depends('parent_id')
  36. def _compute_team_id(self):
  37. for partner in self.filtered(lambda partner: not partner.team_id and partner.company_type == 'person' and partner.parent_id.team_id):
  38. partner.team_id = partner.parent_id.team_id
  39. def _compute_opportunity_count(self):
  40. # retrieve all children partners and prefetch 'parent_id' on them
  41. all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
  42. all_partners.read(['parent_id'])
  43. opportunity_data = self.env['crm.lead'].with_context(active_test=False)._read_group(
  44. domain=[('partner_id', 'in', all_partners.ids)],
  45. fields=['partner_id'], groupby=['partner_id']
  46. )
  47. self.opportunity_count = 0
  48. for group in opportunity_data:
  49. partner = self.browse(group['partner_id'][0])
  50. while partner:
  51. if partner in self:
  52. partner.opportunity_count += group['partner_id_count']
  53. partner = partner.parent_id
  54. def action_view_opportunity(self):
  55. '''
  56. This function returns an action that displays the opportunities from partner.
  57. '''
  58. action = self.env['ir.actions.act_window']._for_xml_id('crm.crm_lead_opportunities')
  59. action['context'] = {'active_test': False}
  60. if self.is_company:
  61. action['domain'] = [('partner_id.commercial_partner_id', '=', self.id)]
  62. else:
  63. action['domain'] = [('partner_id', '=', self.id)]
  64. return action