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.

189 lines
5.7 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2012 - Now Savoir-faire Linux <https://www.savoirfairelinux.com/>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from datetime import datetime, timedelta
  5. from openerp import fields, models, api
  6. from openerp.tools.safe_eval import safe_eval
  7. from openerp.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. kpi_type = fields.Selection((
  66. ('python', 'Python'),
  67. ('local', 'SQL - Local DB'),
  68. ('external', 'SQL - External DB')
  69. ), 'KPI Computation Type')
  70. dbsource_id = fields.Many2one(
  71. 'base.external.dbsource',
  72. 'External DB Source',
  73. )
  74. kpi_code = fields.Text(
  75. 'KPI Code',
  76. help=("SQL code must return the result as 'value' "
  77. "(i.e. 'SELECT 5 AS value')."),
  78. )
  79. history_ids = fields.One2many(
  80. 'kpi.history',
  81. 'kpi_id',
  82. 'History',
  83. )
  84. active = fields.Boolean(
  85. 'Active',
  86. help=("Only active KPIs will be updated by the scheduler based on"
  87. " the periodicity configuration."), default=True
  88. )
  89. company_id = fields.Many2one(
  90. 'res.company', 'Company',
  91. default=lambda self: self.env.user.company_id.id)
  92. @api.multi
  93. def _compute_display_last_kpi_value(self):
  94. history_obj = self.env['kpi.history']
  95. for obj in self:
  96. history_ids = history_obj.search([("kpi_id", "=", obj.id)])
  97. if history_ids:
  98. obj.value = obj.history_ids[0].value
  99. else:
  100. obj.value = 0
  101. @api.multi
  102. def compute_kpi_value(self):
  103. for obj in self:
  104. kpi_value = 0
  105. if obj.kpi_code:
  106. if obj.kpi_type == 'local' and is_sql_or_ddl_statement(
  107. obj.kpi_code):
  108. self.env.cr.execute(obj.kpi_code)
  109. dic = self.env.cr.dictfetchall()
  110. if is_one_value(dic):
  111. kpi_value = dic[0]['value']
  112. elif (obj.kpi_type == 'external' and obj.dbsource_id.id and
  113. is_sql_or_ddl_statement(obj.kpi_code)):
  114. dbsrc_obj = obj.dbsource_id
  115. res = dbsrc_obj.execute(obj.kpi_code)
  116. if is_one_value(res):
  117. kpi_value = res[0]['value']
  118. elif obj.kpi_type == 'python':
  119. kpi_value = safe_eval(obj.kpi_code)
  120. threshold_obj = obj.threshold_id
  121. values = {
  122. 'kpi_id': obj.id,
  123. 'value': kpi_value,
  124. 'color': threshold_obj.get_color(kpi_value),
  125. }
  126. history_obj = self.env['kpi.history']
  127. history_obj.create(values)
  128. return True
  129. @api.multi
  130. def update_next_execution_date(self):
  131. for obj in self:
  132. if obj.periodicity_uom == 'hour':
  133. delta = timedelta(hours=obj.periodicity)
  134. elif obj.periodicity_uom == 'day':
  135. delta = timedelta(days=obj.periodicity)
  136. elif obj.periodicity_uom == 'week':
  137. delta = timedelta(weeks=obj.periodicity)
  138. elif obj.periodicity_uom == 'month':
  139. delta = timedelta(months=obj.periodicity)
  140. else:
  141. delta = timedelta()
  142. new_date = datetime.now() + delta
  143. obj.next_execution_date = new_date.strftime(DATETIME_FORMAT)
  144. return True
  145. # Method called by the scheduler
  146. @api.model
  147. def update_kpi_value(self):
  148. filters = [
  149. '&',
  150. '|',
  151. ('active', '=', True),
  152. ('next_execution_date', '<=', datetime.now().strftime(
  153. DATETIME_FORMAT)),
  154. ('next_execution_date', '=', False),
  155. ]
  156. if 'filters' in self.env.context:
  157. filters.extend(self.env.context['filters'])
  158. obj_ids = self.search(filters)
  159. res = None
  160. try:
  161. for obj in obj_ids:
  162. obj.compute_kpi_value()
  163. obj.update_next_execution_date()
  164. except Exception:
  165. _logger.exception("Failed updating KPI values")
  166. return res