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.

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