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.

110 lines
4.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, osv
  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': fields.char(
  35. "Model",
  36. required=True),
  37. 'months': fields.integer(
  38. "Months",
  39. required=True,
  40. help="Number of month after which the records will be set to "
  41. "inactive based on their write date"),
  42. 'company_id': fields.many2one(
  43. 'res.company',
  44. string="Company",
  45. ondelete="cascade",
  46. required=True),
  47. }
  48. _sql_constraints = [
  49. ('model_uniq', 'unique(model, company_id)',
  50. "A model can only have 1 lifespan per company"),
  51. ('months_gt_0', 'check (months > 0)',
  52. "Months must be a value greater than 0"),
  53. ]
  54. def _scheduler_record_archiver(self, cr, uid, context=None):
  55. lifespan_ids = self.search(cr, uid, [], context=context)
  56. _logger.info('Records archiver starts archiving records')
  57. for lifespan_id in lifespan_ids:
  58. try:
  59. self.archive_records(cr, uid, [lifespan_id], context=context)
  60. except osv.except_osv as e:
  61. _logger.error("Archiver error:\n%s", e[1])
  62. _logger.info('Rusty Records now rest in peace')
  63. return True
  64. def archive_records(self, cr, uid, ids, context=None):
  65. """ Search and deactivate old records for each configured lifespan
  66. Only done and cancelled records will be deactivated.
  67. """
  68. lifespans = self.browse(cr, uid, ids, context=context)
  69. today = datetime.today()
  70. for lifespan in lifespans:
  71. model = self.pool[lifespan.model]
  72. if not model:
  73. raise osv.except_osv(
  74. _('Error'),
  75. _('Model %s not found') % lifespan.model)
  76. if 'active' not in model._columns.keys():
  77. raise osv.except_osv(
  78. _('Error'),
  79. _('Model %s has no active field') % lifespan.model)
  80. delta = relativedelta(months=lifespan.months)
  81. expiration_date = (today - delta).strftime(DATE_FORMAT)
  82. domain = [('write_date', '<', expiration_date),
  83. ('company_id', '=', lifespan.company_id.id)]
  84. if 'state' in model._columns.keys():
  85. domain += [('state', 'in', ('done', 'cancel'))]
  86. rec_ids = model.search(cr, uid, domain, context=context)
  87. if not rec_ids:
  88. continue
  89. # use a SQL query to bypass tracking always messages on write for
  90. # object inheriting mail.thread
  91. query = ("UPDATE %s SET active = FALSE WHERE id in %%s"
  92. ) % model._table
  93. cr.execute(query, (tuple(rec_ids),))
  94. _logger.info(
  95. 'Archived %s %s older than %s',
  96. len(rec_ids), lifespan.model, expiration_date)