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.

368 lines
14 KiB

  1. # -*- coding: utf-8 -*-
  2. '''Define model res.partner.relation'''
  3. ##############################################################################
  4. #
  5. # OpenERP, Open Source Management Solution
  6. # This module copyright (C) 2013 Therp BV (<http://therp.nl>).
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. from openerp import osv, models, fields, api, exceptions, _
  23. from . import get_partner_type
  24. class ResPartnerRelation(models.Model):
  25. '''Model res.partner.relation is used to describe all links or relations
  26. between partners in the database.
  27. In many parts of the code we have to know whether the active partner is
  28. the left partner, or the right partner. If the active partner is the
  29. right partner we have to show the inverse name.
  30. Because the active partner is crucial for the working of partner
  31. relationships, we make sure on the res.partner model that the partner id
  32. is set in the context where needed.
  33. '''
  34. _name = 'res.partner.relation'
  35. _description = 'Partner relation'
  36. _order = 'active desc, date_start desc, date_end desc'
  37. def _get_computed_fields(
  38. self, cr, uid, ids, field_names, arg, context=None):
  39. '''Return a dictionary of dictionaries, with for every partner for
  40. ids, the computed values.'''
  41. def get_values(self, dummy_field_names, dummy_arg, context=None):
  42. '''Get computed values for record'''
  43. values = {}
  44. on_right_partner = self._on_right_partner(self.right_partner_id.id)
  45. # type_selection_id
  46. values['type_selection_id'] = (
  47. ((self.type_id.id) * 10) + (on_right_partner and 1 or 0))
  48. # partner_id_display
  49. values['partner_id_display'] = (
  50. self.left_partner_id.id
  51. if on_right_partner
  52. else self.right_partner_id.id
  53. )
  54. return values
  55. return dict([
  56. (i.id, get_values(i, field_names, arg, context=context))
  57. for i in self.browse(cr, uid, ids, context=context)
  58. ])
  59. _columns = {
  60. 'type_selection_id': osv.fields.function(
  61. _get_computed_fields,
  62. multi="computed_fields",
  63. fnct_inv=lambda *args: None,
  64. type='many2one', obj='res.partner.relation.type.selection',
  65. string='Type',
  66. ),
  67. 'partner_id_display': osv.fields.function(
  68. _get_computed_fields,
  69. multi="computed_fields",
  70. fnct_inv=lambda *args: None,
  71. type='many2one', obj='res.partner',
  72. string='Partner'
  73. ),
  74. }
  75. allow_self = fields.Boolean(related='type_id.allow_self')
  76. left_contact_type = fields.Selection(
  77. lambda s: s.env['res.partner.relation.type']._get_partner_types(),
  78. 'Left Partner Type',
  79. compute='_get_partner_type_any',
  80. store=True,
  81. )
  82. right_contact_type = fields.Selection(
  83. lambda s: s.env['res.partner.relation.type']._get_partner_types(),
  84. 'Right Partner Type',
  85. compute='_get_partner_type_any',
  86. store=True,
  87. )
  88. any_partner_id = fields.Many2many(
  89. 'res.partner',
  90. string='Partner',
  91. compute='_get_partner_type_any',
  92. )
  93. left_partner_id = fields.Many2one(
  94. 'res.partner',
  95. string='Source Partner',
  96. required=True,
  97. auto_join=True,
  98. ondelete='cascade',
  99. )
  100. right_partner_id = fields.Many2one(
  101. 'res.partner',
  102. string='Destination Partner',
  103. required=True,
  104. auto_join=True,
  105. ondelete='cascade',
  106. )
  107. type_id = fields.Many2one(
  108. 'res.partner.relation.type',
  109. string='Type',
  110. required=True,
  111. auto_join=True,
  112. )
  113. date_start = fields.Date('Starting date')
  114. date_end = fields.Date('Ending date')
  115. active = fields.Boolean('Active', default=True)
  116. @api.one
  117. @api.depends('left_partner_id', 'right_partner_id')
  118. def _get_partner_type_any(self):
  119. self.left_contact_type = get_partner_type(self.left_partner_id)
  120. self.right_contact_type = get_partner_type(self.right_partner_id)
  121. self.any_partner_id = self.left_partner_id + self.right_partner_id
  122. def _on_right_partner(self, cr, uid, right_partner_id, context=None):
  123. '''Determine wether functions are called in a situation where the
  124. active partner is the right partner. Default False!
  125. '''
  126. if (context and 'active_ids' in context and
  127. right_partner_id in context.get('active_ids', [])):
  128. return True
  129. return False
  130. def _correct_vals(self, vals):
  131. """Fill type and left and right partner id, according to whether
  132. we have a normal relation type or an inverse relation type
  133. """
  134. vals = vals.copy()
  135. # If type_selection_id ends in 1, it is a reverse relation type
  136. if 'type_selection_id' in vals:
  137. prts_model = self.env['res.partner.relation.type.selection']
  138. type_selection_id = vals['type_selection_id']
  139. (type_id, is_reverse) = (
  140. prts_model.browse(type_selection_id).
  141. get_type_from_selection_id()
  142. )
  143. vals['type_id'] = type_id
  144. if self._context.get('active_id'):
  145. if is_reverse:
  146. vals['right_partner_id'] = self._context['active_id']
  147. else:
  148. vals['left_partner_id'] = self._context['active_id']
  149. if vals.get('partner_id_display'):
  150. if is_reverse:
  151. vals['left_partner_id'] = vals['partner_id_display']
  152. else:
  153. vals['right_partner_id'] = vals['partner_id_display']
  154. if vals.get('other_partner_id'):
  155. if is_reverse:
  156. vals['left_partner_id'] = vals['other_partner_id']
  157. else:
  158. vals['right_partner_id'] = vals['other_partner_id']
  159. del vals['other_partner_id']
  160. if vals.get('contact_type'):
  161. del vals['contact_type']
  162. return vals
  163. @api.multi
  164. def write(self, vals):
  165. """Override write to correct values, before being stored."""
  166. vals = self._correct_vals(vals)
  167. return super(ResPartnerRelation, self).write(vals)
  168. @api.model
  169. def create(self, vals):
  170. """Override create to correct values, before being stored."""
  171. vals = self._correct_vals(vals)
  172. return super(ResPartnerRelation, self).create(vals)
  173. def on_change_type_selection_id(
  174. self, cr, uid, dummy_ids, type_selection_id, context=None):
  175. '''Set domain on partner_id_display, when selection a relation type'''
  176. result = {
  177. 'domain': {'partner_id_display': []},
  178. 'value': {'type_id': False}
  179. }
  180. if not type_selection_id:
  181. return result
  182. prts_model = self.pool['res.partner.relation.type.selection']
  183. type_model = self.pool['res.partner.relation.type']
  184. (type_id, is_reverse) = (
  185. prts_model.get_type_from_selection_id(
  186. cr, uid, type_selection_id)
  187. )
  188. result['value']['type_id'] = type_id
  189. type_obj = type_model.browse(cr, uid, type_id, context=context)
  190. partner_domain = []
  191. check_contact_type = type_obj.contact_type_right
  192. check_partner_category = (
  193. type_obj.partner_category_right and
  194. type_obj.partner_category_right.id
  195. )
  196. if is_reverse:
  197. # partner_id_display is left partner
  198. check_contact_type = type_obj.contact_type_left
  199. check_partner_category = (
  200. type_obj.partner_category_left and
  201. type_obj.partner_category_left.id
  202. )
  203. if check_contact_type == 'c':
  204. partner_domain.append(('is_company', '=', True))
  205. if check_contact_type == 'p':
  206. partner_domain.append(('is_company', '=', False))
  207. if check_partner_category:
  208. partner_domain.append(
  209. ('category_id', 'child_of', check_partner_category))
  210. result['domain']['partner_id_display'] = partner_domain
  211. return result
  212. @api.one
  213. @api.constrains('date_start', 'date_end')
  214. def _check_dates(self):
  215. """End date should not be before start date, if not filled
  216. :raises exceptions.Warning: When constraint is violated
  217. """
  218. if (self.date_start and self.date_end and
  219. self.date_start > self.date_end):
  220. raise exceptions.Warning(
  221. _('The starting date cannot be after the ending date.')
  222. )
  223. @api.one
  224. @api.constrains('left_partner_id', 'type_id')
  225. def _check_partner_type_left(self):
  226. """Check left partner for required company or person
  227. :raises exceptions.Warning: When constraint is violated
  228. """
  229. self._check_partner_type("left")
  230. @api.one
  231. @api.constrains('right_partner_id', 'type_id')
  232. def _check_partner_type_right(self):
  233. """Check right partner for required company or person
  234. :raises exceptions.Warning: When constraint is violated
  235. """
  236. self._check_partner_type("right")
  237. @api.one
  238. def _check_partner_type(self, side):
  239. """Check partner to left or right for required company or person
  240. :param str side: left or right
  241. :raises exceptions.Warning: When constraint is violated
  242. """
  243. assert side in ['left', 'right']
  244. ptype = getattr(self.type_id, "contact_type_%s" % side)
  245. company = getattr(self, '%s_partner_id' % side).is_company
  246. if (ptype == 'c' and not company) or (ptype == 'p' and company):
  247. raise exceptions.Warning(
  248. _('The %s partner is not applicable for this relation type.') %
  249. side
  250. )
  251. @api.one
  252. @api.constrains('left_partner_id', 'right_partner_id')
  253. def _check_not_with_self(self):
  254. """Not allowed to link partner to same partner
  255. :raises exceptions.Warning: When constraint is violated
  256. """
  257. if self.left_partner_id == self.right_partner_id:
  258. if not self.allow_self:
  259. raise exceptions.Warning(
  260. _('Partners cannot have a relation with themselves.')
  261. )
  262. @api.one
  263. @api.constrains('left_partner_id', 'right_partner_id', 'active')
  264. def _check_relation_uniqueness(self):
  265. """Forbid multiple active relations of the same type between the same
  266. partners
  267. :raises exceptions.Warning: When constraint is violated
  268. """
  269. if not self.active:
  270. return
  271. domain = [
  272. ('type_id', '=', self.type_id.id),
  273. ('active', '=', True),
  274. ('id', '!=', self.id),
  275. ('left_partner_id', '=', self.left_partner_id.id),
  276. ('right_partner_id', '=', self.right_partner_id.id),
  277. ]
  278. if self.date_start:
  279. domain += ['|', ('date_end', '=', False),
  280. ('date_end', '>=', self.date_start)]
  281. if self.date_end:
  282. domain += ['|', ('date_start', '=', False),
  283. ('date_start', '<=', self.date_end)]
  284. if self.search(domain):
  285. raise exceptions.Warning(
  286. _('There is already a similar relation with overlapping dates')
  287. )
  288. def get_action_related_partners(self, cr, uid, ids, context=None):
  289. '''return a window action showing a list of partners taking part in the
  290. relations names by ids. Context key 'partner_relations_show_side'
  291. determines if we show 'left' side, 'right' side or 'all' (default)
  292. partners.
  293. If active_model is res.partner.relation.all, left=this and
  294. right=other'''
  295. if context is None:
  296. context = {}
  297. field_names = {}
  298. if context.get('active_model', self._name) == self._name:
  299. field_names = {
  300. 'left': ['left'],
  301. 'right': ['right'],
  302. 'all': ['left', 'right']
  303. }
  304. elif context.get('active_model') == 'res.partner.relation.all':
  305. field_names = {
  306. 'left': ['this'],
  307. 'right': ['other'],
  308. 'all': ['this', 'other']
  309. }
  310. else:
  311. assert False, 'Unknown active_model!'
  312. partner_ids = []
  313. field_names = field_names[
  314. context.get('partner_relations_show_side', 'all')]
  315. field_names = ['%s_partner_id' % n for n in field_names]
  316. for relation in self.pool[context.get('active_model')].read(
  317. cr, uid, ids, context=context, load='_classic_write'):
  318. for name in field_names:
  319. partner_ids.append(relation[name])
  320. return {
  321. 'name': _('Related partners'),
  322. 'type': 'ir.actions.act_window',
  323. 'res_model': 'res.partner',
  324. 'domain': [('id', 'in', partner_ids)],
  325. 'views': [(False, 'tree'), (False, 'form')],
  326. 'view_type': 'form'
  327. }