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.

320 lines
13 KiB

10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. '''Extend res.partner model'''
  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. import time
  23. from openerp import osv, models, fields, exceptions, api
  24. from openerp.osv.expression import is_leaf, AND, OR, FALSE_LEAF
  25. from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
  26. from openerp.tools.translate import _
  27. class ResPartner(models.Model):
  28. _inherit = 'res.partner'
  29. relation_count = fields.Integer(
  30. 'Relation Count',
  31. compute="_count_relations"
  32. )
  33. @api.one
  34. @api.depends("relation_ids")
  35. def _count_relations(self):
  36. """Count the number of relations this partner has for Smart Button
  37. Don't count inactive relations.
  38. """
  39. self.relation_count = len([r for r in self.relation_ids if r.active])
  40. def _get_relation_ids_select(self, cr, uid, ids, field_name, arg,
  41. context=None):
  42. '''return the partners' relations as tuple
  43. (id, left_partner_id, right_partner_id)'''
  44. cr.execute(
  45. '''select id, left_partner_id, right_partner_id
  46. from res_partner_relation
  47. where (left_partner_id in %s or right_partner_id in %s)''' +
  48. ' order by ' + self.pool['res.partner.relation']._order,
  49. (tuple(ids), tuple(ids))
  50. )
  51. return cr.fetchall()
  52. def _get_relation_ids(
  53. self, cr, uid, ids, field_name, arg, context=None):
  54. '''getter for relation_ids'''
  55. if context is None:
  56. context = {}
  57. result = dict([(i, []) for i in ids])
  58. # TODO: do a permission test on returned ids
  59. for row in self._get_relation_ids_select(
  60. cr, uid, ids, field_name, arg, context=context):
  61. if row[1] in result:
  62. result[row[1]].append(row[0])
  63. if row[2] in result:
  64. result[row[2]].append(row[0])
  65. return result
  66. def _set_relation_ids(
  67. self, cr, uid, ids, dummy_name, field_value, dummy_arg,
  68. context=None):
  69. '''setter for relation_ids'''
  70. if context is None:
  71. context = {}
  72. relation_obj = self.pool.get('res.partner.relation')
  73. context2 = self._update_context(context, ids)
  74. for value in field_value:
  75. if value[0] == 0:
  76. relation_obj.create(cr, uid, value[2], context=context2)
  77. if value[0] == 1:
  78. # if we write partner_id_display, we also need to pass
  79. # type_selection_id in order to have this write end up on
  80. # the correct field
  81. if 'partner_id_display' in value[2] and 'type_selection_id'\
  82. not in value[2]:
  83. relation_data = relation_obj.read(
  84. cr, uid, [value[1]], ['type_selection_id'],
  85. context=context)[0]
  86. value[2]['type_selection_id'] =\
  87. relation_data['type_selection_id']
  88. relation_obj.write(
  89. cr, uid, value[1], value[2], context=context2)
  90. if value[0] == 2:
  91. relation_obj.unlink(cr, uid, value[1], context=context2)
  92. def _search_relation_id(
  93. self, cr, uid, dummy_obj, name, args, context=None):
  94. result = []
  95. for arg in args:
  96. if isinstance(arg, tuple) and arg[0] == name:
  97. if arg[1] not in ['=', '!=', 'like', 'not like', 'ilike',
  98. 'not ilike', 'in', 'not in']:
  99. raise exceptions.ValidationError(
  100. _('Unsupported search operand "%s"') % arg[1])
  101. relation_type_selection_ids = []
  102. relation_type_selection = self\
  103. .pool['res.partner.relation.type.selection']
  104. if arg[1] == '=' and isinstance(arg[2], (long, int)):
  105. relation_type_selection_ids.append(arg[2])
  106. elif arg[1] == '!=' and isinstance(arg[2], (long, int)):
  107. type_id, is_inverse = (
  108. relation_type_selection.browse(cr, uid, arg[2],
  109. context=context)
  110. .get_type_from_selection_id()
  111. )
  112. result = OR([
  113. result,
  114. [
  115. ('relation_all_ids.type_id', '!=', type_id),
  116. ]
  117. ])
  118. continue
  119. else:
  120. relation_type_selection_ids = relation_type_selection\
  121. .search(
  122. cr, uid,
  123. [
  124. ('type_id.name', arg[1], arg[2]),
  125. ('record_type', '=', 'a'),
  126. ],
  127. context=context)
  128. relation_type_selection_ids.extend(
  129. relation_type_selection.search(
  130. cr, uid,
  131. [
  132. ('type_id.name_inverse', arg[1], arg[2]),
  133. ('record_type', '=', 'b'),
  134. ],
  135. context=context))
  136. if not relation_type_selection_ids:
  137. result = AND([result, [FALSE_LEAF]])
  138. for relation_type_selection_id in relation_type_selection_ids:
  139. type_id, is_inverse = (
  140. relation_type_selection.browse(
  141. cr, uid, relation_type_selection_id,
  142. context=context
  143. ).get_type_from_selection_id()
  144. )
  145. result = OR([
  146. result,
  147. [
  148. '&',
  149. ('relation_all_ids.type_id', '=', type_id),
  150. ('relation_all_ids.record_type', '=',
  151. 'b' if is_inverse else 'a')
  152. ],
  153. ])
  154. return result
  155. def _search_relation_date(self, cr, uid, obj, name, args, context=None):
  156. result = []
  157. for arg in args:
  158. if isinstance(arg, tuple) and arg[0] == name:
  159. # TODO: handle {<,>}{,=}
  160. if arg[1] != '=':
  161. continue
  162. result.extend([
  163. '&',
  164. '|',
  165. ('relation_all_ids.date_start', '=', False),
  166. ('relation_all_ids.date_start', '<=', arg[2]),
  167. '|',
  168. ('relation_all_ids.date_end', '=', False),
  169. ('relation_all_ids.date_end', '>=', arg[2]),
  170. ])
  171. return result
  172. def _search_related_partner_id(
  173. self, cr, uid, dummy_obj, name, args, context=None):
  174. result = []
  175. for arg in args:
  176. if isinstance(arg, tuple) and arg[0] == name:
  177. result.append(
  178. (
  179. 'relation_all_ids.other_partner_id',
  180. arg[1],
  181. arg[2],
  182. ))
  183. return result
  184. def _search_related_partner_category_id(
  185. self, cr, uid, dummy_obj, name, args, context=None):
  186. result = []
  187. for arg in args:
  188. if isinstance(arg, tuple) and arg[0] == name:
  189. result.append(
  190. (
  191. 'relation_all_ids.other_partner_id.category_id',
  192. arg[1],
  193. arg[2],
  194. ))
  195. return result
  196. _columns = {
  197. 'relation_ids': osv.fields.function(
  198. lambda self, *args, **kwargs: self._get_relation_ids(
  199. *args, **kwargs),
  200. fnct_inv=_set_relation_ids,
  201. type='one2many', obj='res.partner.relation',
  202. string='Relations',
  203. selectable=False,
  204. ),
  205. 'relation_all_ids': osv.fields.one2many(
  206. 'res.partner.relation.all', 'this_partner_id',
  207. string='All relations with current partner',
  208. auto_join=True,
  209. selectable=False,
  210. ),
  211. 'search_relation_id': osv.fields.function(
  212. lambda self, cr, uid, ids, *args: dict([
  213. (i, False) for i in ids]),
  214. fnct_search=_search_relation_id,
  215. string='Has relation of type',
  216. type='many2one', obj='res.partner.relation.type.selection'
  217. ),
  218. 'search_relation_partner_id': osv.fields.function(
  219. lambda self, cr, uid, ids, *args: dict([
  220. (i, False) for i in ids]),
  221. fnct_search=_search_related_partner_id,
  222. string='Has relation with',
  223. type='many2one', obj='res.partner'
  224. ),
  225. 'search_relation_date': osv.fields.function(
  226. lambda self, cr, uid, ids, *args: dict([
  227. (i, False) for i in ids]),
  228. fnct_search=_search_relation_date,
  229. string='Relation valid', type='date'
  230. ),
  231. 'search_relation_partner_category_id': osv.fields.function(
  232. lambda self, cr, uid, ids, *args: dict([
  233. (i, False) for i in ids]),
  234. fnct_search=_search_related_partner_category_id,
  235. string='Has relation with a partner in category',
  236. type='many2one', obj='res.partner.category'
  237. ),
  238. }
  239. def copy_data(self, cr, uid, id, default=None, context=None):
  240. if default is None:
  241. default = {}
  242. default.setdefault('relation_ids', [])
  243. default.setdefault('relation_all_ids', [])
  244. return super(ResPartner, self).copy_data(cr, uid, id, default=default,
  245. context=context)
  246. def search(self, cr, uid, args, offset=0, limit=None, order=None,
  247. context=None, count=False):
  248. if context is None:
  249. context = {}
  250. # inject searching for current relation date if we search for relation
  251. # properties and no explicit date was given
  252. date_args = []
  253. for arg in args:
  254. if is_leaf(arg) and arg[0].startswith('search_relation'):
  255. if arg[0] == 'search_relation_date':
  256. date_args = []
  257. break
  258. if not date_args:
  259. date_args = [
  260. ('search_relation_date', '=', time.strftime(
  261. DEFAULT_SERVER_DATE_FORMAT))]
  262. # because of auto_join, we have to do the active test by hand
  263. active_args = []
  264. if context.get('active_test', True):
  265. for arg in args:
  266. if is_leaf(arg) and\
  267. arg[0].startswith('search_relation'):
  268. active_args = [('relation_all_ids.active', '=', True)]
  269. break
  270. return super(ResPartner, self).search(
  271. cr, uid, args + date_args + active_args, offset=offset,
  272. limit=limit, order=order, context=context, count=count)
  273. def read(
  274. self, cr, uid, ids, fields=None, context=None,
  275. load='_classic_read'):
  276. return super(ResPartner, self).read(
  277. cr, uid, ids, fields=fields,
  278. context=self._update_context(context, ids))
  279. def write(self, cr, uid, ids, vals, context=None):
  280. return super(ResPartner, self).write(
  281. cr, uid, ids, vals, context=self._update_context(context, ids))
  282. def _update_context(self, context, ids):
  283. if context is None:
  284. context = {}
  285. ids = ids if isinstance(ids, list) else [ids] if ids else []
  286. result = context.copy()
  287. result.setdefault('active_id', ids[0] if ids else None)
  288. result.setdefault('active_ids', ids)
  289. result.setdefault('active_model', self._name)
  290. return result