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.

58 lines
2.5 KiB

  1. # Copyright (C) 2017 Creu Blanca
  2. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  3. from odoo import fields, models
  4. from datetime import datetime, timedelta, date as datetime_date
  5. from dateutil.relativedelta import relativedelta
  6. class IrSequence(models.Model):
  7. _inherit = "ir.sequence"
  8. range_reset = fields.Selection([
  9. ('daily', 'Daily'),
  10. ('weekly', 'Weekly'),
  11. ('monthly', 'Monthly'),
  12. ('yearly', 'Yearly')
  13. ])
  14. def _compute_date_from_to(self, date):
  15. self.ensure_one()
  16. date_from = date_to = fields.Date.from_string(date)
  17. if self.range_reset == 'weekly':
  18. date_from = date_from - timedelta(days=date_from.weekday())
  19. date_to = date_from + timedelta(days=6)
  20. elif self.range_reset == 'monthly':
  21. date_from = datetime_date(date_from.year, date_from.month, 1)
  22. date_to = date_from + relativedelta(months=1)
  23. date_to += relativedelta(days=-1)
  24. elif self.range_reset == 'yearly':
  25. date_from = datetime_date(date_from.year, 1, 1)
  26. date_to = datetime_date(date_from.year, 12, 31)
  27. return date_from.strftime('%Y-%m-%d'), date_to.strftime('%Y-%m-%d')
  28. def _create_date_range_seq(self, date):
  29. self.ensure_one()
  30. if not self.range_reset:
  31. return super()._create_date_range_seq(date)
  32. date_from, date_to = self._compute_date_from_to(date)
  33. date_range = self.env['ir.sequence.date_range'].search(
  34. [('sequence_id', '=', self.id), ('date_from', '>=', date),
  35. ('date_from', '<=', date_to)], order='date_from desc', limit=1)
  36. if date_range:
  37. date_to = datetime.strptime(date_range.date_from,
  38. '%Y-%m-%d') + timedelta(days=-1)
  39. date_to = date_to.strftime('%Y-%m-%d')
  40. date_range = self.env['ir.sequence.date_range'].search(
  41. [('sequence_id', '=', self.id), ('date_to', '>=', date_from),
  42. ('date_to', '<=', date)], order='date_to desc', limit=1)
  43. if date_range:
  44. date_from = datetime.strptime(date_range.date_to,
  45. '%Y-%m-%d') + timedelta(days=1)
  46. date_from = date_from.strftime('%Y-%m-%d')
  47. seq_date_range = self.env['ir.sequence.date_range'].sudo().create({
  48. 'date_from': date_from,
  49. 'date_to': date_to,
  50. 'sequence_id': self.id,
  51. })
  52. return seq_date_range