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.

133 lines
4.8 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Author: Yannick Vaucher
  4. # Copyright 2015 Camptocamp SA
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as
  8. # published by the Free Software Foundation, either version 3 of the
  9. # License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import logging
  20. from datetime import datetime
  21. from dateutil.relativedelta import relativedelta
  22. from openerp.osv import orm, fields
  23. from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT
  24. from openerp.tools.translate import _
  25. _logger = logging.getLogger(__name__)
  26. class RecordLifespan(orm.Model):
  27. """ Configure records lifespans per model
  28. After the lifespan is expired (compared to the `write_date` of the
  29. records), the records are deactivated.
  30. """
  31. _name = 'record.lifespan'
  32. _order = 'model'
  33. _columns = {
  34. 'model_id': fields.many2one(
  35. 'ir.model',
  36. string='Model',
  37. required=True,
  38. domain=[('has_an_active_field', '=', True)],
  39. ),
  40. 'model': fields.related(
  41. 'model_id', 'model',
  42. string='Model Name',
  43. type='char',
  44. readonly=True,
  45. store=True,
  46. ),
  47. 'months': fields.integer(
  48. "Months",
  49. required=True,
  50. help="Number of month after which the records will be set to "
  51. "inactive based on their write date"),
  52. }
  53. _sql_constraints = [
  54. ('months_gt_0', 'check (months > 0)',
  55. "Months must be a value greater than 0"),
  56. ]
  57. def _scheduler_archive_records(self, cr, uid, context=None):
  58. lifespan_ids = self.search(cr, uid, [], context=context)
  59. _logger.info('Records archiver starts archiving records')
  60. for lifespan_id in lifespan_ids:
  61. try:
  62. self.archive_records(cr, uid, [lifespan_id], context=context)
  63. except orm.except_orm as e:
  64. _logger.error("Archiver error:\n%s", e[1])
  65. _logger.info('Rusty Records now rest in peace')
  66. return True
  67. def _archive_domain(self, cr, uid, lifespan, expiration_date,
  68. context=None):
  69. """ Returns the domain used to find the records to archive.
  70. Can be inherited to change the archived records for a model.
  71. """
  72. model = self.pool[lifespan.model]
  73. domain = [('write_date', '<', expiration_date),
  74. ]
  75. if 'state' in model._columns:
  76. domain += [('state', 'in', ('done', 'cancel'))]
  77. return domain
  78. def _archive_lifespan_records(self, cr, uid, lifespan, context=None):
  79. """ Archive the records for a lifespan, so for a model.
  80. Can be inherited to customize the archive strategy.
  81. The default strategy is to change the field ``active`` to False
  82. on the records having a ``write_date`` older than the lifespan.
  83. Only done and canceled records will be deactivated.
  84. """
  85. today = datetime.today()
  86. model = self.pool.get(lifespan.model)
  87. if not model:
  88. raise orm.except_orm(
  89. _('Error'),
  90. _('Model %s not found') % lifespan.model)
  91. if 'active' not in model._columns:
  92. raise orm.except_orm(
  93. _('Error'),
  94. _('Model %s has no active field') % lifespan.model)
  95. delta = relativedelta(months=lifespan.months)
  96. expiration_date = (today - delta).strftime(DATE_FORMAT)
  97. domain = self._archive_domain(cr, uid, lifespan, expiration_date,
  98. context=context)
  99. rec_ids = model.search(cr, uid, domain, context=context)
  100. if not rec_ids:
  101. return
  102. # use a SQL query to bypass tracking always messages on write for
  103. # object inheriting mail.thread
  104. query = ("UPDATE %s SET active = FALSE WHERE id in %%s"
  105. ) % model._table
  106. cr.execute(query, (tuple(rec_ids),))
  107. _logger.info(
  108. 'Archived %s %s older than %s',
  109. len(rec_ids), lifespan.model, expiration_date)
  110. def archive_records(self, cr, uid, ids, context=None):
  111. """ Call the archiver for several record lifespans """
  112. for lifespan in self.browse(cr, uid, ids, context=context):
  113. self._archive_lifespan_records(cr, uid, lifespan, context=context)
  114. return True