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.

142 lines
4.8 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:
  47. continue
  48. allowed_states \
  49. = [x[0] for x in state_field.get('selection', [('')])]
  50. if not all(archive_state in allowed_states
  51. for archive_state in lifespan._get_archive_states()):
  52. raise exceptions.ValidationError(_(
  53. 'Invalid set of states for "%s" model:\n'
  54. '%s\n'
  55. 'Valid states:\n%s'
  56. ) % (
  57. lifespan.model_id.name,
  58. lifespan.archive_states,
  59. '\n'.join('- {}'.format(s) for s in allowed_states),
  60. ))
  61. @api.model
  62. def _scheduler_archive_records(self):
  63. lifespans = self.search([])
  64. _logger.info('Records archiver starts archiving records')
  65. for lifespan in lifespans:
  66. try:
  67. lifespan.archive_records()
  68. except exceptions.UserError as e:
  69. _logger.error("Archiver error:\n%s", e[1])
  70. _logger.info('Rusty Records now rest in peace')
  71. return True
  72. @api.multi
  73. def _get_archive_states(self):
  74. self.ensure_one()
  75. if not self.archive_states:
  76. return ['done', 'cancel']
  77. return [s.strip() for s in self.archive_states.split(',')]
  78. @api.multi
  79. def _archive_domain(self, expiration_date):
  80. """Returns the domain used to find the records to archive.
  81. Can be inherited to change the archived records for a model.
  82. """
  83. self.ensure_one()
  84. model = self.env[self.model_id.model]
  85. domain = [('write_date', '<', expiration_date)]
  86. if 'state' in model.fields_get_keys():
  87. domain += [('state', 'in', self._get_archive_states())]
  88. return domain
  89. @api.multi
  90. def _archive_lifespan_records(self):
  91. """Archive the records for a lifespan, so for a model.
  92. Can be inherited to customize the archive strategy.
  93. The default strategy is to change the field ``active`` to False
  94. on the records having a ``write_date`` older than the lifespan.
  95. Only done and canceled records will be deactivated.
  96. """
  97. self.ensure_one()
  98. today = datetime.today()
  99. model_name = self.model_id.model
  100. model = self.env[model_name]
  101. if not isinstance(model, models.Model):
  102. raise exceptions.UserError(
  103. _('Model %s not found') % model_name)
  104. if 'active' not in model.fields_get_keys():
  105. raise exceptions.UserError(
  106. _('Model %s has no active field') % model_name)
  107. delta = relativedelta(months=self.months)
  108. expiration_date = fields.Datetime.to_string(today - delta)
  109. domain = self._archive_domain(expiration_date)
  110. recs = model.search(domain)
  111. if not recs:
  112. return
  113. recs.with_context(tracking_disable=True).toggle_active()
  114. _logger.info(
  115. 'Archived %s %s older than %s',
  116. len(recs.ids), model_name, expiration_date)
  117. @api.multi
  118. def archive_records(self):
  119. """Call the archiver for several record lifespans."""
  120. for lifespan in self:
  121. lifespan._archive_lifespan_records()
  122. return True