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.

140 lines
5.1 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. 'company_id': fields.many2one(
  53. 'res.company',
  54. string="Company",
  55. ondelete="cascade",
  56. required=True),
  57. }
  58. _sql_constraints = [
  59. ('model_uniq', 'unique(model_id, company_id)',
  60. "A model can only have 1 lifespan per company"),
  61. ('months_gt_0', 'check (months > 0)',
  62. "Months must be a value greater than 0"),
  63. ]
  64. def _scheduler_archive_records(self, cr, uid, context=None):
  65. lifespan_ids = self.search(cr, uid, [], context=context)
  66. _logger.info('Records archiver starts archiving records')
  67. for lifespan_id in lifespan_ids:
  68. try:
  69. self.archive_records(cr, uid, [lifespan_id], context=context)
  70. except orm.except_orm as e:
  71. _logger.error("Archiver error:\n%s", e[1])
  72. _logger.info('Rusty Records now rest in peace')
  73. return True
  74. def _archive_domain(self, cr, uid, lifespan, expiration_date,
  75. context=None):
  76. """ Returns the domain used to find the records to archive.
  77. Can be inherited to change the archived records for a model.
  78. """
  79. model = self.pool[lifespan.model]
  80. domain = [('write_date', '<', expiration_date),
  81. ('company_id', '=', lifespan.company_id.id)]
  82. if 'state' in model._columns:
  83. domain += [('state', 'in', ('done', 'cancel'))]
  84. return domain
  85. def _archive_lifespan_records(self, cr, uid, lifespan, context=None):
  86. """ Archive the records for a lifespan, so for a model.
  87. Can be inherited to customize the archive strategy.
  88. The default strategy is to change the field ``active`` to False
  89. on the records having a ``write_date`` older than the lifespan.
  90. Only done and canceled records will be deactivated.
  91. """
  92. today = datetime.today()
  93. model = self.pool.get(lifespan.model)
  94. if not model:
  95. raise orm.except_orm(
  96. _('Error'),
  97. _('Model %s not found') % lifespan.model)
  98. if 'active' not in model._columns:
  99. raise orm.except_orm(
  100. _('Error'),
  101. _('Model %s has no active field') % lifespan.model)
  102. delta = relativedelta(months=lifespan.months)
  103. expiration_date = (today - delta).strftime(DATE_FORMAT)
  104. domain = self._archive_domain(cr, uid, lifespan, expiration_date,
  105. context=context)
  106. rec_ids = model.search(cr, uid, domain, context=context)
  107. if not rec_ids:
  108. return
  109. # use a SQL query to bypass tracking always messages on write for
  110. # object inheriting mail.thread
  111. query = ("UPDATE %s SET active = FALSE WHERE id in %%s"
  112. ) % model._table
  113. cr.execute(query, (tuple(rec_ids),))
  114. _logger.info(
  115. 'Archived %s %s older than %s',
  116. len(rec_ids), lifespan.model, expiration_date)
  117. def archive_records(self, cr, uid, ids, context=None):
  118. """ Call the archiver for several record lifespans """
  119. for lifespan in self.browse(cr, uid, ids, context=context):
  120. self._archive_lifespan_records(cr, uid, lifespan, context=context)
  121. return True