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.

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