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.

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