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.

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