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.

514 lines
20 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2015-2016 Camptocamp SA
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. from itertools import groupby
  5. from lxml import etree
  6. from operator import attrgetter
  7. from openerp import models, fields, api, exceptions, _
  8. from openerp.osv.orm import setup_modifiers
  9. # sentinel object to be sure that no empty value was passed to
  10. # ResPartnerChangesetChange._value_for_changeset
  11. _NO_VALUE = object()
  12. class ResPartnerChangeset(models.Model):
  13. _name = 'res.partner.changeset'
  14. _description = 'Partner Changeset'
  15. _order = 'date desc'
  16. _rec_name = 'date'
  17. partner_id = fields.Many2one(comodel_name='res.partner',
  18. string='Partner',
  19. select=True,
  20. required=True,
  21. readonly=True,
  22. ondelete='cascade')
  23. change_ids = fields.One2many(comodel_name='res.partner.changeset.change',
  24. inverse_name='changeset_id',
  25. string='Changes',
  26. readonly=True)
  27. date = fields.Datetime(default=fields.Datetime.now,
  28. select=True,
  29. readonly=True)
  30. state = fields.Selection(
  31. compute='_compute_state',
  32. selection=[('draft', 'Pending'),
  33. ('done', 'Done')],
  34. string='State',
  35. store=True,
  36. )
  37. note = fields.Text()
  38. source = fields.Reference(
  39. string='Source of the change',
  40. selection='_reference_models',
  41. readonly=True,
  42. )
  43. @api.model
  44. def _reference_models(self):
  45. models = self.env['ir.model'].search([])
  46. return [(model.model, model.name) for model in models]
  47. @api.depends('change_ids', 'change_ids.state')
  48. def _compute_state(self):
  49. for res in self:
  50. if all(change.state in ('done', 'cancel') for change
  51. in res.mapped('change_ids')):
  52. res.state = 'done'
  53. else:
  54. res.state = 'draft'
  55. @api.multi
  56. def apply(self):
  57. self.mapped('change_ids').apply()
  58. @api.multi
  59. def cancel(self):
  60. self.mapped('change_ids').cancel()
  61. @api.multi
  62. def add_changeset(self, record, values):
  63. """ Add a changeset on a partner
  64. By default, when a partner is modified by a user or by the
  65. system, the the changeset will follow the rules configured for
  66. the 'Users' / global rules.
  67. A caller should pass the following keys in the context:
  68. * ``__changeset_rules_source_model``: name of the model which
  69. asks for the change
  70. * ``__changeset_rules_source_id``: id of the record which asks
  71. for the change
  72. When the source model and id are not defined, the current user
  73. is considered as the origin of the change.
  74. Should be called before the execution of ``write`` on the record
  75. so we can keep track of the existing value and also because the
  76. returned values should be used for ``write`` as some of the
  77. values may have been removed.
  78. :param values: the values being written on the partner
  79. :type values: dict
  80. :returns: dict of values that should be wrote on the partner
  81. (fields with a 'Validate' or 'Never' rule are excluded)
  82. """
  83. record.ensure_one()
  84. source_model = self.env.context.get('__changeset_rules_source_model')
  85. source_id = self.env.context.get('__changeset_rules_source_id')
  86. if not source_model:
  87. # if the changes source is not defined, log the user who
  88. # made the change
  89. source_model = 'res.users'
  90. if not source_id:
  91. source_id = self.env.uid
  92. if source_model and source_id:
  93. source = '%s,%s' % (source_model, source_id)
  94. else:
  95. source = False
  96. change_model = self.env['res.partner.changeset.change']
  97. write_values = values.copy()
  98. changes = []
  99. rules = self.env['changeset.field.rule'].get_rules(
  100. source_model_name=source_model,
  101. )
  102. for field in values:
  103. rule = rules.get(field)
  104. if not rule:
  105. continue
  106. if field in values:
  107. if not change_model._has_field_changed(record, field,
  108. values[field]):
  109. continue
  110. change, pop_value = change_model._prepare_changeset_change(
  111. record, rule, field, values[field]
  112. )
  113. if pop_value:
  114. write_values.pop(field)
  115. changes.append(change)
  116. if changes:
  117. self.env['res.partner.changeset'].create({
  118. 'partner_id': record.id,
  119. 'change_ids': [(0, 0, vals) for vals in changes],
  120. 'date': fields.Datetime.now(),
  121. 'source': source,
  122. })
  123. return write_values
  124. class ResPartnerChangesetChange(models.Model):
  125. """ Store the change of one field for one changeset on one partner
  126. This model is composed of 3 sets of fields:
  127. * 'origin'
  128. * 'old'
  129. * 'new'
  130. The 'new' fields contain the value that needs to be validated.
  131. The 'old' field copies the actual value of the partner when the
  132. change is either applied either canceled. This field is used as a storage
  133. place but never shown by itself.
  134. The 'origin' fields is a related field towards the actual values of
  135. the partner until the change is either applied either canceled, past
  136. that it shows the 'old' value.
  137. The reason behind this is that the values may change on a partner between
  138. the moment when the changeset is created and when it is applied.
  139. On the views, we show the origin fields which represent the actual
  140. partner values or the old values and we show the new fields.
  141. The 'origin' and 'new_value_display' are displayed on
  142. the tree view where we need a unique of field, the other fields are
  143. displayed on the form view so we benefit from their widgets.
  144. """
  145. _name = 'res.partner.changeset.change'
  146. _description = 'Partner Changeset Change'
  147. _rec_name = 'field_id'
  148. changeset_id = fields.Many2one(comodel_name='res.partner.changeset',
  149. required=True,
  150. string='Changeset',
  151. ondelete='cascade',
  152. readonly=True)
  153. field_id = fields.Many2one(comodel_name='ir.model.fields',
  154. string='Field',
  155. required=True,
  156. readonly=True)
  157. field_type = fields.Selection(related='field_id.ttype',
  158. string='Field Type',
  159. readonly=True)
  160. origin_value_display = fields.Char(
  161. string='Previous',
  162. compute='_compute_value_display',
  163. )
  164. new_value_display = fields.Char(
  165. string='New',
  166. compute='_compute_value_display',
  167. )
  168. # Fields showing the origin partner's value or the 'old' value if
  169. # the change is applied or canceled.
  170. origin_value_char = fields.Char(compute='_compute_origin_values',
  171. string='Previous',
  172. readonly=True)
  173. origin_value_date = fields.Date(compute='_compute_origin_values',
  174. string='Previous',
  175. readonly=True)
  176. origin_value_datetime = fields.Datetime(compute='_compute_origin_values',
  177. string='Previous',
  178. readonly=True)
  179. origin_value_float = fields.Float(compute='_compute_origin_values',
  180. string='Previous',
  181. readonly=True)
  182. origin_value_integer = fields.Integer(compute='_compute_origin_values',
  183. string='Previous',
  184. readonly=True)
  185. origin_value_text = fields.Text(compute='_compute_origin_values',
  186. string='Previous',
  187. readonly=True)
  188. origin_value_boolean = fields.Boolean(compute='_compute_origin_values',
  189. string='Previous',
  190. readonly=True)
  191. origin_value_reference = fields.Reference(
  192. compute='_compute_origin_values',
  193. string='Previous',
  194. selection='_reference_models',
  195. readonly=True,
  196. )
  197. # Fields storing the previous partner's values (saved when the
  198. # changeset is applied)
  199. old_value_char = fields.Char(string='Old',
  200. readonly=True)
  201. old_value_date = fields.Date(string='Old',
  202. readonly=True)
  203. old_value_datetime = fields.Datetime(string='Old',
  204. readonly=True)
  205. old_value_float = fields.Float(string='Old',
  206. readonly=True)
  207. old_value_integer = fields.Integer(string='Old',
  208. readonly=True)
  209. old_value_text = fields.Text(string='Old',
  210. readonly=True)
  211. old_value_boolean = fields.Boolean(string='Old',
  212. readonly=True)
  213. old_value_reference = fields.Reference(string='Old',
  214. selection='_reference_models',
  215. readonly=True)
  216. # Fields storing the value applied on the partner
  217. new_value_char = fields.Char(string='New',
  218. readonly=True)
  219. new_value_date = fields.Date(string='New',
  220. readonly=True)
  221. new_value_datetime = fields.Datetime(string='New',
  222. readonly=True)
  223. new_value_float = fields.Float(string='New',
  224. readonly=True)
  225. new_value_integer = fields.Integer(string='New',
  226. readonly=True)
  227. new_value_text = fields.Text(string='New',
  228. readonly=True)
  229. new_value_boolean = fields.Boolean(string='New',
  230. readonly=True)
  231. new_value_reference = fields.Reference(string='New',
  232. selection='_reference_models',
  233. readonly=True)
  234. state = fields.Selection(
  235. selection=[('draft', 'Pending'),
  236. ('done', 'Accepted'),
  237. ('cancel', 'Rejected'),
  238. ],
  239. required=True,
  240. default='draft',
  241. readonly=True,
  242. )
  243. @api.model
  244. def _reference_models(self):
  245. models = self.env['ir.model'].search([])
  246. return [(model.model, model.name) for model in models]
  247. _suffix_to_types = {
  248. 'char': ('char', 'selection'),
  249. 'date': ('date',),
  250. 'datetime': ('datetime',),
  251. 'float': ('float',),
  252. 'integer': ('integer',),
  253. 'text': ('text',),
  254. 'boolean': ('boolean',),
  255. 'reference': ('many2one',),
  256. }
  257. _type_to_suffix = {ftype: suffix
  258. for suffix, ftypes in _suffix_to_types.iteritems()
  259. for ftype in ftypes}
  260. _origin_value_fields = ['origin_value_%s' % suffix
  261. for suffix in _suffix_to_types]
  262. _old_value_fields = ['old_value_%s' % suffix
  263. for suffix in _suffix_to_types]
  264. _new_value_fields = ['new_value_%s' % suffix
  265. for suffix in _suffix_to_types]
  266. _value_fields = (_origin_value_fields +
  267. _old_value_fields +
  268. _new_value_fields)
  269. @api.depends('changeset_id.partner_id')
  270. def _compute_origin_values(self):
  271. for res in self:
  272. field_name = res.get_field_for_type(res.field_id, 'origin')
  273. if res.state == 'draft':
  274. value = res.changeset_id.partner_id[res.field_id.name]
  275. else:
  276. old_field = res.get_field_for_type(res.field_id, 'old')
  277. value = res[old_field]
  278. setattr(res, field_name, value)
  279. @api.depends(lambda self: self._value_fields)
  280. def _compute_value_display(self):
  281. for res in self:
  282. for prefix in ('origin', 'new'):
  283. value = getattr(res, 'get_%s_value' % prefix)()
  284. if res.field_id.ttype == 'many2one' and value:
  285. value = value.display_name
  286. setattr(res, '%s_value_display' % prefix, value)
  287. @api.model
  288. def get_field_for_type(self, field, prefix):
  289. assert prefix in ('origin', 'old', 'new')
  290. field_type = self._type_to_suffix.get(field.ttype)
  291. if not field_type:
  292. raise NotImplementedError(
  293. 'field type %s is not supported' % field_type
  294. )
  295. return '%s_value_%s' % (prefix, field_type)
  296. @api.multi
  297. def get_origin_value(self):
  298. self.ensure_one()
  299. field_name = self.get_field_for_type(self.field_id, 'origin')
  300. return self[field_name]
  301. @api.multi
  302. def get_new_value(self):
  303. self.ensure_one()
  304. field_name = self.get_field_for_type(self.field_id, 'new')
  305. return self[field_name]
  306. @api.multi
  307. def set_old_value(self):
  308. """ Copy the value of the partner to the 'old' field """
  309. for change in self:
  310. # copy the existing partner's value for the history
  311. old_value_for_write = self._value_for_changeset(
  312. change.changeset_id.partner_id,
  313. change.field_id.name
  314. )
  315. old_field_name = self.get_field_for_type(change.field_id, 'old')
  316. change.write({old_field_name: old_value_for_write})
  317. @api.multi
  318. def apply(self):
  319. """ Apply the change on the changeset's partner
  320. It is optimized thus that it makes only one write on the partner
  321. per changeset if many changes are applied at once.
  322. """
  323. changes_ok = self.browse()
  324. key = attrgetter('changeset_id')
  325. for changeset, changes in groupby(self.sorted(key=key), key=key):
  326. values = {}
  327. partner = changeset.partner_id
  328. for change in changes:
  329. if change.state in ('cancel', 'done'):
  330. continue
  331. field = change.field_id
  332. value_for_write = change._convert_value_for_write(
  333. change.get_new_value()
  334. )
  335. values[field.name] = value_for_write
  336. change.set_old_value()
  337. changes_ok |= change
  338. if not values:
  339. continue
  340. previous_changesets = self.env['res.partner.changeset'].search(
  341. [('date', '<', changeset.date),
  342. ('state', '=', 'draft'),
  343. ('partner_id', '=', changeset.partner_id.id),
  344. ],
  345. limit=1,
  346. )
  347. if previous_changesets:
  348. raise exceptions.Warning(
  349. _('This change cannot be applied because a previous '
  350. 'changeset for the same partner is pending.\n'
  351. 'Apply all the anterior changesets before applying '
  352. 'this one.')
  353. )
  354. partner.with_context(__no_changeset=True).write(values)
  355. changes_ok.write({'state': 'done'})
  356. @api.multi
  357. def cancel(self):
  358. """ Reject the change """
  359. if any(change.state == 'done' for change in self):
  360. raise exceptions.Warning(
  361. _('This change has already be applied.')
  362. )
  363. self.set_old_value()
  364. self.write({'state': 'cancel'})
  365. @api.model
  366. def _has_field_changed(self, record, field, value):
  367. field_def = record._fields[field]
  368. current_value = field_def.convert_to_write(record[field])
  369. if not (current_value or value):
  370. return False
  371. return current_value != value
  372. @api.multi
  373. def _convert_value_for_write(self, value):
  374. if not value:
  375. return value
  376. model = self.env[self.field_id.model_id.model]
  377. model_field_def = model._fields[self.field_id.name]
  378. return model_field_def.convert_to_write(value)
  379. @api.model
  380. def _value_for_changeset(self, record, field_name, value=_NO_VALUE):
  381. """ Return a value from the record ready to write in a changeset field
  382. :param record: modified record
  383. :param field_name: name of the modified field
  384. :param value: if no value is given, it is read from the record
  385. """
  386. field_def = record._fields[field_name]
  387. if value is _NO_VALUE:
  388. # when the value is read from the record, we need to prepare
  389. # it for the write (e.g. extract .id from a many2one record)
  390. value = field_def.convert_to_write(record[field_name])
  391. if field_def.type == 'many2one':
  392. # store as 'reference'
  393. comodel = field_def.comodel_name
  394. return "%s,%s" % (comodel, value) if value else False
  395. else:
  396. return value
  397. @api.multi
  398. def _prepare_changeset_change(self, record, rule, field_name, value):
  399. """ Prepare data for a changeset change
  400. It returns a dict of the values to write on the changeset change
  401. and a boolean that indicates if the value should be popped out
  402. of the values to write on the model.
  403. :returns: dict of values, boolean
  404. """
  405. new_field_name = self.get_field_for_type(rule.field_id, 'new')
  406. new_value = self._value_for_changeset(record, field_name, value=value)
  407. change = {
  408. new_field_name: new_value,
  409. 'field_id': rule.field_id.id,
  410. }
  411. if rule.action == 'auto':
  412. change['state'] = 'done'
  413. pop_value = False
  414. elif rule.action == 'validate':
  415. change['state'] = 'draft'
  416. pop_value = True # change to apply manually
  417. elif rule.action == 'never':
  418. change['state'] = 'cancel'
  419. pop_value = True # change never applied
  420. if change['state'] in ('cancel', 'done'):
  421. # Normally the 'old' value is set when we use the 'apply'
  422. # button, but since we short circuit the 'apply', we
  423. # directly set the 'old' value here
  424. old_field_name = self.get_field_for_type(rule.field_id, 'old')
  425. # get values ready to write as expected by the changeset
  426. # (for instance, a many2one is written in a reference
  427. # field)
  428. origin_value = self._value_for_changeset(record, field_name)
  429. change[old_field_name] = origin_value
  430. return change, pop_value
  431. def fields_view_get(self, *args, **kwargs):
  432. _super = super(ResPartnerChangesetChange, self)
  433. result = _super.fields_view_get(*args, **kwargs)
  434. if result['type'] != 'form':
  435. return
  436. doc = etree.XML(result['arch'])
  437. for suffix, ftypes in self._suffix_to_types.iteritems():
  438. for prefix in ('origin', 'old', 'new'):
  439. field_name = '%s_value_%s' % (prefix, suffix)
  440. field_nodes = doc.xpath("//field[@name='%s']" % field_name)
  441. for node in field_nodes:
  442. node.set(
  443. 'attrs',
  444. "{'invisible': "
  445. "[('field_type', 'not in', %s)]}" % (ftypes,)
  446. )
  447. setup_modifiers(node)
  448. result['arch'] = etree.tostring(doc)
  449. return result