OCA reporting engine fork for dev and update.
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.

205 lines
6.2 KiB

  1. # Copyright 2012 - Now Savoir-faire Linux <https://www.savoirfairelinux.com/>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from datetime import datetime
  4. from dateutil.relativedelta import relativedelta
  5. from odoo import fields, models, api
  6. from odoo.tools.safe_eval import safe_eval
  7. from odoo.tools import (
  8. DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT,
  9. )
  10. import re
  11. import logging
  12. _logger = logging.getLogger(__name__)
  13. def is_one_value(result):
  14. # check if sql query returns only one value
  15. if type(result) is dict and 'value' in result.dictfetchone():
  16. return True
  17. elif type(result) is list and 'value' in result[0]:
  18. return True
  19. else:
  20. return False
  21. RE_SELECT_QUERY = re.compile('.*(' + '|'.join((
  22. 'INSERT',
  23. 'UPDATE',
  24. 'DELETE',
  25. 'CREATE',
  26. 'ALTER',
  27. 'DROP',
  28. 'GRANT',
  29. 'REVOKE',
  30. 'INDEX',
  31. )) + ')')
  32. def is_sql_or_ddl_statement(query):
  33. """Check if sql query is a SELECT statement"""
  34. return not RE_SELECT_QUERY.match(query.upper())
  35. class KPI(models.Model):
  36. """Key Performance Indicators."""
  37. _name = "kpi"
  38. _description = "Key Performance Indicator"
  39. name = fields.Char('Name', required=True)
  40. description = fields.Text('Description')
  41. category_id = fields.Many2one(
  42. 'kpi.category',
  43. 'Category',
  44. required=True,
  45. )
  46. threshold_id = fields.Many2one(
  47. 'kpi.threshold',
  48. 'Threshold',
  49. required=True,
  50. )
  51. periodicity = fields.Integer('Periodicity', default=1)
  52. periodicity_uom = fields.Selection((
  53. ('hour', 'Hour'),
  54. ('day', 'Day'),
  55. ('week', 'Week'),
  56. ('month', 'Month')
  57. ), 'Periodicity UoM', required=True, default='day')
  58. next_execution_date = fields.Datetime(
  59. 'Next execution date',
  60. readonly=True,
  61. )
  62. value = fields.Float(string='Value',
  63. compute="_compute_display_last_kpi_value",
  64. )
  65. color = fields.Text('Color', compute="_compute_display_last_kpi_value",)
  66. last_execution = fields.Datetime(
  67. 'Last execution', compute="_compute_display_last_kpi_value",)
  68. kpi_type = fields.Selection((
  69. ('python', 'Python'),
  70. ('local', 'SQL - Local DB'),
  71. ('external', 'SQL - External DB')
  72. ), 'KPI Computation Type')
  73. dbsource_id = fields.Many2one(
  74. 'base.external.dbsource',
  75. 'External DB Source',
  76. )
  77. kpi_code = fields.Text(
  78. 'KPI Code',
  79. help=("SQL code must return the result as 'value' "
  80. "(i.e. 'SELECT 5 AS value')."),
  81. )
  82. history_ids = fields.One2many(
  83. 'kpi.history',
  84. 'kpi_id',
  85. 'History',
  86. )
  87. active = fields.Boolean(
  88. 'Active',
  89. help=("Only active KPIs will be updated by the scheduler based on"
  90. " the periodicity configuration."), default=True
  91. )
  92. company_id = fields.Many2one(
  93. 'res.company', 'Company',
  94. default=lambda self: self.env.user.company_id.id)
  95. @api.multi
  96. def _compute_display_last_kpi_value(self):
  97. history_obj = self.env['kpi.history']
  98. for obj in self:
  99. history_ids = history_obj.search([("kpi_id", "=", obj.id)])
  100. if history_ids:
  101. his = obj.history_ids[0]
  102. obj.value = his.value
  103. obj.color = his.color
  104. obj.last_execution = his.date
  105. else:
  106. obj.value = 0
  107. obj.color = '#FFFFFF'
  108. obj.last_execution = False
  109. @api.multi
  110. def _get_kpi_value(self):
  111. self.ensure_one()
  112. kpi_value = 0
  113. if self.kpi_code:
  114. if self.kpi_type == 'local' and is_sql_or_ddl_statement(
  115. self.kpi_code):
  116. self.env.cr.execute(self.kpi_code)
  117. dic = self.env.cr.dictfetchall()
  118. if is_one_value(dic):
  119. kpi_value = dic[0]['value']
  120. elif (self.kpi_type == 'external' and self.dbsource_id.id and
  121. is_sql_or_ddl_statement(self.kpi_code)):
  122. dbsrc_obj = self.dbsource_id
  123. res = dbsrc_obj.execute(self.kpi_code)
  124. if is_one_value(res):
  125. kpi_value = res[0]['value']
  126. elif self.kpi_type == 'python':
  127. kpi_value = safe_eval(self.kpi_code, {'self': self})
  128. if isinstance(kpi_value, dict):
  129. res = kpi_value
  130. else:
  131. threshold_obj = self.threshold_id
  132. res = {
  133. 'value': kpi_value,
  134. 'color': threshold_obj.get_color(kpi_value),
  135. }
  136. res.update({'kpi_id': self.id})
  137. return res
  138. @api.multi
  139. def compute_kpi_value(self):
  140. for obj in self:
  141. history_vals = obj._get_kpi_value()
  142. history_obj = self.env['kpi.history']
  143. history_obj.create(history_vals)
  144. return True
  145. @api.multi
  146. def update_next_execution_date(self):
  147. for obj in self:
  148. if obj.periodicity_uom == 'hour':
  149. delta = relativedelta(hours=obj.periodicity)
  150. elif obj.periodicity_uom == 'day':
  151. delta = relativedelta(days=obj.periodicity)
  152. elif obj.periodicity_uom == 'week':
  153. delta = relativedelta(weeks=obj.periodicity)
  154. elif obj.periodicity_uom == 'month':
  155. delta = relativedelta(months=obj.periodicity)
  156. else:
  157. delta = relativedelta()
  158. new_date = datetime.now() + delta
  159. obj.next_execution_date = new_date.strftime(DATETIME_FORMAT)
  160. return True
  161. # Method called by the scheduler
  162. @api.model
  163. def update_kpi_value(self):
  164. filters = [
  165. '&',
  166. '|',
  167. ('active', '=', True),
  168. ('next_execution_date', '<=', datetime.now().strftime(
  169. DATETIME_FORMAT)),
  170. ('next_execution_date', '=', False),
  171. ]
  172. if 'filters' in self.env.context:
  173. filters.extend(self.env.context['filters'])
  174. obj_ids = self.search(filters)
  175. res = None
  176. try:
  177. for obj in obj_ids:
  178. obj.compute_kpi_value()
  179. obj.update_next_execution_date()
  180. except Exception:
  181. _logger.exception("Failed updating KPI values")
  182. return res