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.

518 lines
20 KiB

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