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.

348 lines
14 KiB

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