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.

144 lines
4.9 KiB

  1. # Copyright 2015-2016 Yannick Vaucher (Camptocamp SA)
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. import logging
  4. from datetime import datetime
  5. from dateutil.relativedelta import relativedelta
  6. from odoo import _, api, exceptions, fields, models
  7. _logger = logging.getLogger(__name__)
  8. class RecordLifespan(models.Model):
  9. """Configure records lifespans per model.
  10. After the lifespan is expired (compared to the `write_date` of the
  11. records), the records are deactivated.
  12. """
  13. _name = 'record.lifespan'
  14. _order = 'model_name'
  15. model_id = fields.Many2one(
  16. 'ir.model',
  17. string='Model',
  18. required=True,
  19. domain=[('has_an_active_field', '=', True)],
  20. )
  21. model_name = fields.Char(
  22. related='model_id.model',
  23. readonly=True,
  24. string='Model Name',
  25. )
  26. months = fields.Integer(
  27. required=True,
  28. help="Number of month after which the records will be set to inactive"
  29. " based on their write date",
  30. )
  31. archive_states = fields.Char(
  32. help="Comma-separated list of states in which records should be"
  33. " archived. Implicit value is `'done, cancel')`.",
  34. )
  35. _sql_constraints = [
  36. ('months_gt_0', 'check (months > 0)',
  37. "Months must be a value greater than 0"),
  38. ]
  39. @api.constrains('archive_states')
  40. def _check_archive_states(self):
  41. for lifespan in self:
  42. if not lifespan.archive_states:
  43. continue
  44. model = self.env[lifespan.model_id.model]
  45. state_field = model.fields_get().get('state', {})
  46. if not state_field or state_field['type'] != 'selection':
  47. continue
  48. allowed_states = [
  49. state[0]
  50. for state in state_field.get('selection', [('')])
  51. ]
  52. if not all(archive_state in allowed_states
  53. for archive_state in lifespan._get_archive_states()):
  54. raise exceptions.ValidationError(_(
  55. 'Invalid set of states for "%s" model:\n'
  56. '%s\n'
  57. 'Valid states:\n%s'
  58. ) % (
  59. lifespan.model_id.name,
  60. lifespan.archive_states,
  61. '\n'.join('- {}'.format(s) for s in allowed_states),
  62. ))
  63. @api.model
  64. def _scheduler_archive_records(self):
  65. lifespans = self.search([])
  66. _logger.info('Records archiver starts archiving records')
  67. for lifespan in lifespans:
  68. try:
  69. lifespan.archive_records()
  70. except exceptions.UserError as e:
  71. _logger.error("Archiver error:\n%s", e[1])
  72. _logger.info('Rusty Records now rest in peace')
  73. return True
  74. @api.multi
  75. def _get_archive_states(self):
  76. self.ensure_one()
  77. if not self.archive_states:
  78. return ['done', 'cancel']
  79. return [s.strip() for s in self.archive_states.split(',') if s.strip()]
  80. @api.multi
  81. def _archive_domain(self, expiration_date):
  82. """Returns the domain used to find the records to archive.
  83. Can be inherited to change the archived records for a model.
  84. """
  85. self.ensure_one()
  86. model = self.env[self.model_id.model]
  87. domain = [('write_date', '<', expiration_date)]
  88. if 'state' in model.fields_get_keys():
  89. domain += [('state', 'in', self._get_archive_states())]
  90. return domain
  91. @api.multi
  92. def _archive_lifespan_records(self):
  93. """Archive the records for a lifespan, so for a model.
  94. Can be inherited to customize the archive strategy.
  95. The default strategy is to change the field ``active`` to False
  96. on the records having a ``write_date`` older than the lifespan.
  97. Only done and canceled records will be deactivated.
  98. """
  99. self.ensure_one()
  100. today = datetime.today()
  101. model_name = self.model_id.model
  102. model = self.env[model_name]
  103. if not isinstance(model, models.Model):
  104. raise exceptions.UserError(
  105. _('Model %s not found') % model_name)
  106. if 'active' not in model.fields_get_keys():
  107. raise exceptions.UserError(
  108. _('Model %s has no active field') % model_name)
  109. delta = relativedelta(months=self.months)
  110. expiration_date = fields.Datetime.to_string(today - delta)
  111. domain = self._archive_domain(expiration_date)
  112. recs = model.search(domain)
  113. if not recs:
  114. return
  115. recs.with_context(tracking_disable=True).toggle_active()
  116. _logger.info(
  117. 'Archived %s %s older than %s',
  118. len(recs.ids), model_name, expiration_date)
  119. @api.multi
  120. def archive_records(self):
  121. """Call the archiver for several record lifespans."""
  122. for lifespan in self:
  123. lifespan._archive_lifespan_records()
  124. return True