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.

316 lines
12 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(arg[2])
  109. .get_type_from_selection_id()
  110. )
  111. result = OR([
  112. result,
  113. [
  114. ('relation_all_ids.type_id', '!=', type_id),
  115. ]
  116. ])
  117. continue
  118. else:
  119. relation_type_selection_ids = relation_type_selection\
  120. .search(
  121. cr, uid,
  122. [
  123. ('type_id.name', arg[1], arg[2]),
  124. ('record_type', '=', 'a'),
  125. ],
  126. context=context)
  127. relation_type_selection_ids.extend(
  128. relation_type_selection.search(
  129. cr, uid,
  130. [
  131. ('type_id.name_inverse', arg[1], arg[2]),
  132. ('record_type', '=', 'b'),
  133. ],
  134. context=context))
  135. if not relation_type_selection_ids:
  136. result = AND([result, [FALSE_LEAF]])
  137. for relation_type_selection_id in relation_type_selection_ids:
  138. type_id, is_inverse = (
  139. relation_type_selection_id.get_type_from_selection_id()
  140. )
  141. result = OR([
  142. result,
  143. [
  144. '&',
  145. ('relation_all_ids.type_id', '=', type_id),
  146. ('relation_all_ids.record_type', '=',
  147. 'b' if is_inverse else 'a')
  148. ],
  149. ])
  150. return result
  151. def _search_relation_date(self, cr, uid, obj, name, args, context=None):
  152. result = []
  153. for arg in args:
  154. if isinstance(arg, tuple) and arg[0] == name:
  155. # TODO: handle {<,>}{,=}
  156. if arg[1] != '=':
  157. continue
  158. result.extend([
  159. '&',
  160. '|',
  161. ('relation_all_ids.date_start', '=', False),
  162. ('relation_all_ids.date_start', '<=', arg[2]),
  163. '|',
  164. ('relation_all_ids.date_end', '=', False),
  165. ('relation_all_ids.date_end', '>=', arg[2]),
  166. ])
  167. return result
  168. def _search_related_partner_id(
  169. self, cr, uid, dummy_obj, name, args, context=None):
  170. result = []
  171. for arg in args:
  172. if isinstance(arg, tuple) and arg[0] == name:
  173. result.append(
  174. (
  175. 'relation_all_ids.other_partner_id',
  176. arg[1],
  177. arg[2],
  178. ))
  179. return result
  180. def _search_related_partner_category_id(
  181. self, cr, uid, dummy_obj, name, args, context=None):
  182. result = []
  183. for arg in args:
  184. if isinstance(arg, tuple) and arg[0] == name:
  185. result.append(
  186. (
  187. 'relation_all_ids.other_partner_id.category_id',
  188. arg[1],
  189. arg[2],
  190. ))
  191. return result
  192. _columns = {
  193. 'relation_ids': osv.fields.function(
  194. lambda self, *args, **kwargs: self._get_relation_ids(
  195. *args, **kwargs),
  196. fnct_inv=_set_relation_ids,
  197. type='one2many', obj='res.partner.relation',
  198. string='Relations',
  199. selectable=False,
  200. ),
  201. 'relation_all_ids': osv.fields.one2many(
  202. 'res.partner.relation.all', 'this_partner_id',
  203. string='All relations with current partner',
  204. auto_join=True,
  205. selectable=False,
  206. ),
  207. 'search_relation_id': osv.fields.function(
  208. lambda self, cr, uid, ids, *args: dict([
  209. (i, False) for i in ids]),
  210. fnct_search=_search_relation_id,
  211. string='Has relation of type',
  212. type='many2one', obj='res.partner.relation.type.selection'
  213. ),
  214. 'search_relation_partner_id': osv.fields.function(
  215. lambda self, cr, uid, ids, *args: dict([
  216. (i, False) for i in ids]),
  217. fnct_search=_search_related_partner_id,
  218. string='Has relation with',
  219. type='many2one', obj='res.partner'
  220. ),
  221. 'search_relation_date': osv.fields.function(
  222. lambda self, cr, uid, ids, *args: dict([
  223. (i, False) for i in ids]),
  224. fnct_search=_search_relation_date,
  225. string='Relation valid', type='date'
  226. ),
  227. 'search_relation_partner_category_id': osv.fields.function(
  228. lambda self, cr, uid, ids, *args: dict([
  229. (i, False) for i in ids]),
  230. fnct_search=_search_related_partner_category_id,
  231. string='Has relation with a partner in category',
  232. type='many2one', obj='res.partner.category'
  233. ),
  234. }
  235. def copy_data(self, cr, uid, id, default=None, context=None):
  236. if default is None:
  237. default = {}
  238. default.setdefault('relation_ids', [])
  239. default.setdefault('relation_all_ids', [])
  240. return super(ResPartner, self).copy_data(cr, uid, id, default=default,
  241. context=context)
  242. def search(self, cr, uid, args, offset=0, limit=None, order=None,
  243. context=None, count=False):
  244. if context is None:
  245. context = {}
  246. # inject searching for current relation date if we search for relation
  247. # properties and no explicit date was given
  248. date_args = []
  249. for arg in args:
  250. if is_leaf(arg) and arg[0].startswith('search_relation'):
  251. if arg[0] == 'search_relation_date':
  252. date_args = []
  253. break
  254. if not date_args:
  255. date_args = [
  256. ('search_relation_date', '=', time.strftime(
  257. DEFAULT_SERVER_DATE_FORMAT))]
  258. # because of auto_join, we have to do the active test by hand
  259. active_args = []
  260. if context.get('active_test', True):
  261. for arg in args:
  262. if is_leaf(arg) and\
  263. arg[0].startswith('search_relation'):
  264. active_args = [('relation_all_ids.active', '=', True)]
  265. break
  266. return super(ResPartner, self).search(
  267. cr, uid, args + date_args + active_args, offset=offset,
  268. limit=limit, order=order, context=context, count=count)
  269. def read(
  270. self, cr, uid, ids, fields=None, context=None,
  271. load='_classic_read'):
  272. return super(ResPartner, self).read(
  273. cr, uid, ids, fields=fields,
  274. context=self._update_context(context, ids))
  275. def write(self, cr, uid, ids, vals, context=None):
  276. return super(ResPartner, self).write(
  277. cr, uid, ids, vals, context=self._update_context(context, ids))
  278. def _update_context(self, context, ids):
  279. if context is None:
  280. context = {}
  281. ids = ids if isinstance(ids, list) else [ids] if ids else []
  282. result = context.copy()
  283. result.setdefault('active_id', ids[0] if ids else None)
  284. result.setdefault('active_ids', ids)
  285. result.setdefault('active_model', self._name)
  286. return result