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.

366 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. left_contact_type = fields.Selection(
  76. lambda s: s.env['res.partner.relation.type']._get_partner_types(),
  77. 'Left Partner Type',
  78. compute='_get_partner_type_any',
  79. store=True,
  80. )
  81. right_contact_type = fields.Selection(
  82. lambda s: s.env['res.partner.relation.type']._get_partner_types(),
  83. 'Right Partner Type',
  84. compute='_get_partner_type_any',
  85. store=True,
  86. )
  87. any_partner_id = fields.Many2many(
  88. 'res.partner',
  89. string='Partner',
  90. compute='_get_partner_type_any',
  91. )
  92. left_partner_id = fields.Many2one(
  93. 'res.partner',
  94. string='Source Partner',
  95. required=True,
  96. auto_join=True,
  97. ondelete='cascade',
  98. )
  99. right_partner_id = fields.Many2one(
  100. 'res.partner',
  101. string='Destination Partner',
  102. required=True,
  103. auto_join=True,
  104. ondelete='cascade',
  105. )
  106. type_id = fields.Many2one(
  107. 'res.partner.relation.type',
  108. string='Type',
  109. required=True,
  110. auto_join=True,
  111. )
  112. date_start = fields.Date('Starting date')
  113. date_end = fields.Date('Ending date')
  114. active = fields.Boolean('Active', default=True)
  115. @api.one
  116. @api.depends('left_partner_id', 'right_partner_id')
  117. def _get_partner_type_any(self):
  118. self.left_contact_type = get_partner_type(self.left_partner_id)
  119. self.right_contact_type = get_partner_type(self.right_partner_id)
  120. self.any_partner_id = self.left_partner_id + self.right_partner_id
  121. def _on_right_partner(self, cr, uid, right_partner_id, context=None):
  122. '''Determine wether functions are called in a situation where the
  123. active partner is the right partner. Default False!
  124. '''
  125. if (context and 'active_ids' in context and
  126. right_partner_id in context.get('active_ids', [])):
  127. return True
  128. return False
  129. def _correct_vals(self, vals):
  130. """Fill type and left and right partner id, according to whether
  131. we have a normal relation type or an inverse relation type
  132. """
  133. vals = vals.copy()
  134. # If type_selection_id ends in 1, it is a reverse relation type
  135. if 'type_selection_id' in vals:
  136. prts_model = self.env['res.partner.relation.type.selection']
  137. type_selection_id = vals['type_selection_id']
  138. (type_id, is_reverse) = (
  139. prts_model.browse(type_selection_id).
  140. get_type_from_selection_id()
  141. )
  142. vals['type_id'] = type_id
  143. if self._context.get('active_id'):
  144. if is_reverse:
  145. vals['right_partner_id'] = self._context['active_id']
  146. else:
  147. vals['left_partner_id'] = self._context['active_id']
  148. if vals.get('partner_id_display'):
  149. if is_reverse:
  150. vals['left_partner_id'] = vals['partner_id_display']
  151. else:
  152. vals['right_partner_id'] = vals['partner_id_display']
  153. if vals.get('other_partner_id'):
  154. if is_reverse:
  155. vals['left_partner_id'] = vals['other_partner_id']
  156. else:
  157. vals['right_partner_id'] = vals['other_partner_id']
  158. del vals['other_partner_id']
  159. if vals.get('contact_type'):
  160. del vals['contact_type']
  161. return vals
  162. @api.multi
  163. def write(self, vals):
  164. """Override write to correct values, before being stored."""
  165. vals = self._correct_vals(vals)
  166. return super(ResPartnerRelation, self).write(vals)
  167. @api.model
  168. def create(self, vals):
  169. """Override create to correct values, before being stored."""
  170. vals = self._correct_vals(vals)
  171. return super(ResPartnerRelation, self).create(vals)
  172. def on_change_type_selection_id(
  173. self, cr, uid, dummy_ids, type_selection_id, context=None):
  174. '''Set domain on partner_id_display, when selection a relation type'''
  175. result = {
  176. 'domain': {'partner_id_display': []},
  177. 'value': {'type_id': False}
  178. }
  179. if not type_selection_id:
  180. return result
  181. prts_model = self.pool['res.partner.relation.type.selection']
  182. type_model = self.pool['res.partner.relation.type']
  183. (type_id, is_reverse) = (
  184. prts_model.get_type_from_selection_id(
  185. cr, uid, type_selection_id)
  186. )
  187. result['value']['type_id'] = type_id
  188. type_obj = type_model.browse(cr, uid, type_id, context=context)
  189. partner_domain = []
  190. check_contact_type = type_obj.contact_type_right
  191. check_partner_category = (
  192. type_obj.partner_category_right and
  193. type_obj.partner_category_right.id
  194. )
  195. if is_reverse:
  196. # partner_id_display is left partner
  197. check_contact_type = type_obj.contact_type_left
  198. check_partner_category = (
  199. type_obj.partner_category_left and
  200. type_obj.partner_category_left.id
  201. )
  202. if check_contact_type == 'c':
  203. partner_domain.append(('is_company', '=', True))
  204. if check_contact_type == 'p':
  205. partner_domain.append(('is_company', '=', False))
  206. if check_partner_category:
  207. partner_domain.append(
  208. ('category_id', 'child_of', check_partner_category))
  209. result['domain']['partner_id_display'] = partner_domain
  210. return result
  211. @api.one
  212. @api.constrains('date_start', 'date_end')
  213. def _check_dates(self):
  214. """End date should not be before start date, if not filled
  215. :raises exceptions.Warning: When constraint is violated
  216. """
  217. if (self.date_start and self.date_end and
  218. self.date_start > self.date_end):
  219. raise exceptions.Warning(
  220. _('The starting date cannot be after the ending date.')
  221. )
  222. @api.one
  223. @api.constrains('left_partner_id', 'type_id')
  224. def _check_partner_type_left(self):
  225. """Check left partner for required company or person
  226. :raises exceptions.Warning: When constraint is violated
  227. """
  228. self._check_partner_type("left")
  229. @api.one
  230. @api.constrains('right_partner_id', 'type_id')
  231. def _check_partner_type_right(self):
  232. """Check right partner for required company or person
  233. :raises exceptions.Warning: When constraint is violated
  234. """
  235. self._check_partner_type("right")
  236. @api.one
  237. def _check_partner_type(self, side):
  238. """Check partner to left or right for required company or person
  239. :param str side: left or right
  240. :raises exceptions.Warning: When constraint is violated
  241. """
  242. assert side in ['left', 'right']
  243. ptype = getattr(self.type_id, "contact_type_%s" % side)
  244. company = getattr(self, '%s_partner_id' % side).is_company
  245. if (ptype == 'c' and not company) or (ptype == 'p' and company):
  246. raise exceptions.Warning(
  247. _('The %s partner is not applicable for this relation type.') %
  248. side
  249. )
  250. @api.one
  251. @api.constrains('left_partner_id', 'right_partner_id')
  252. def _check_not_with_self(self):
  253. """Not allowed to link partner to same partner
  254. :raises exceptions.Warning: When constraint is violated
  255. """
  256. if self.left_partner_id == self.right_partner_id:
  257. raise exceptions.Warning(
  258. _('Partners cannot have a relation with themselves.')
  259. )
  260. @api.one
  261. @api.constrains('left_partner_id', 'right_partner_id', 'active')
  262. def _check_relation_uniqueness(self):
  263. """Forbid multiple active relations of the same type between the same
  264. partners
  265. :raises exceptions.Warning: When constraint is violated
  266. """
  267. if not self.active:
  268. return
  269. domain = [
  270. ('type_id', '=', self.type_id.id),
  271. ('active', '=', True),
  272. ('id', '!=', self.id),
  273. ('left_partner_id', '=', self.left_partner_id.id),
  274. ('right_partner_id', '=', self.right_partner_id.id),
  275. ]
  276. if self.date_start:
  277. domain += ['|', ('date_end', '=', False),
  278. ('date_end', '>=', self.date_start)]
  279. if self.date_end:
  280. domain += ['|', ('date_start', '=', False),
  281. ('date_start', '<=', self.date_end)]
  282. if self.search(domain):
  283. raise exceptions.Warning(
  284. _('There is already a similar relation with overlapping dates')
  285. )
  286. def get_action_related_partners(self, cr, uid, ids, context=None):
  287. '''return a window action showing a list of partners taking part in the
  288. relations names by ids. Context key 'partner_relations_show_side'
  289. determines if we show 'left' side, 'right' side or 'all' (default)
  290. partners.
  291. If active_model is res.partner.relation.all, left=this and
  292. right=other'''
  293. if context is None:
  294. context = {}
  295. field_names = {}
  296. if context.get('active_model', self._name) == self._name:
  297. field_names = {
  298. 'left': ['left'],
  299. 'right': ['right'],
  300. 'all': ['left', 'right']
  301. }
  302. elif context.get('active_model') == 'res.partner.relation.all':
  303. field_names = {
  304. 'left': ['this'],
  305. 'right': ['other'],
  306. 'all': ['this', 'other']
  307. }
  308. else:
  309. assert False, 'Unknown active_model!'
  310. partner_ids = []
  311. field_names = field_names[
  312. context.get('partner_relations_show_side', 'all')]
  313. field_names = ['%s_partner_id' % n for n in field_names]
  314. for relation in self.pool[context.get('active_model')].read(
  315. cr, uid, ids, context=context, load='_classic_write'):
  316. for name in field_names:
  317. partner_ids.append(relation[name])
  318. return {
  319. 'name': _('Related partners'),
  320. 'type': 'ir.actions.act_window',
  321. 'res_model': 'res.partner',
  322. 'domain': [('id', 'in', partner_ids)],
  323. 'views': [(False, 'tree'), (False, 'form')],
  324. 'view_type': 'form'
  325. }