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.

279 lines
9.4 KiB

8 years ago
9 years ago
9 years ago
  1. # -*- coding: utf-8 -*-
  2. # © 2010-2013 OpenERP s.a. (<http://openerp.com>).
  3. # © 2014 initOS GmbH & Co. KG (<http://www.initos.com>).
  4. # © 2015-Today GRAP
  5. # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
  6. import datetime
  7. import time
  8. from dateutil.relativedelta import relativedelta
  9. from collections import OrderedDict
  10. from openerp import api, fields, models
  11. from openerp.tools.safe_eval import safe_eval as eval
  12. from openerp.tools.translate import _
  13. from openerp.exceptions import ValidationError, except_orm
  14. def median(vals):
  15. # https://docs.python.org/3/library/statistics.html#statistics.median
  16. # TODO : refactor, using statistics.median when Odoo will be available
  17. # in Python 3.4
  18. even = (0 if len(vals) % 2 else 1) + 1
  19. half = (len(vals) - 1) / 2
  20. return sum(sorted(vals)[half:half + even]) / float(even)
  21. FIELD_FUNCTIONS = OrderedDict([
  22. ('count', {
  23. 'name': 'Count',
  24. 'func': False, # its hardcoded in _compute_data
  25. 'help': _('Number of records')}),
  26. ('min', {
  27. 'name': 'Minimum',
  28. 'func': min,
  29. 'help': _("Minimum value of '%s'")}),
  30. ('max', {
  31. 'name': 'Maximum',
  32. 'func': max,
  33. 'help': _("Maximum value of '%s'")}),
  34. ('sum', {
  35. 'name': 'Sum',
  36. 'func': sum,
  37. 'help': _("Total value of '%s'")}),
  38. ('avg', {
  39. 'name': 'Average',
  40. 'func': lambda vals: sum(vals)/len(vals),
  41. 'help': _("Minimum value of '%s'")}),
  42. ('median', {
  43. 'name': 'Median',
  44. 'func': median,
  45. 'help': _("Median value of '%s'")}),
  46. ])
  47. FIELD_FUNCTION_SELECTION = [
  48. (k, FIELD_FUNCTIONS[k].get('name')) for k in FIELD_FUNCTIONS]
  49. class TileTile(models.Model):
  50. _name = 'tile.tile'
  51. _description = 'Dashboard Tile'
  52. _order = 'sequence, name'
  53. def _get_eval_context(self):
  54. def _context_today():
  55. return fields.Date.from_string(fields.Date.context_today(self))
  56. context = self.env.context.copy()
  57. context.update({
  58. 'time': time,
  59. 'datetime': datetime,
  60. 'relativedelta': relativedelta,
  61. 'context_today': _context_today,
  62. 'current_date': fields.Date.today(),
  63. })
  64. return context
  65. # Column Section
  66. name = fields.Char(required=True)
  67. sequence = fields.Integer(default=0, required=True)
  68. user_id = fields.Many2one('res.users', 'User')
  69. background_color = fields.Char(default='#0E6C7E', oldname='color')
  70. font_color = fields.Char(default='#FFFFFF')
  71. group_ids = fields.Many2many(
  72. 'res.groups',
  73. string='Groups',
  74. help='If this field is set, only users of this group can view this '
  75. 'tile. Please note that it will only work for global tiles '
  76. '(that is, when User field is left empty)')
  77. model_id = fields.Many2one('ir.model', 'Model', required=True)
  78. domain = fields.Text(default='[]')
  79. action_id = fields.Many2one('ir.actions.act_window', 'Action')
  80. active = fields.Boolean(
  81. compute='_compute_active',
  82. search='_search_active',
  83. readonly=True)
  84. # Primary Value
  85. primary_function = fields.Selection(
  86. FIELD_FUNCTION_SELECTION,
  87. string='Function',
  88. default='count')
  89. primary_field_id = fields.Many2one(
  90. 'ir.model.fields',
  91. string='Field',
  92. domain="[('model_id', '=', model_id),"
  93. " ('ttype', 'in', ['float', 'integer'])]")
  94. primary_format = fields.Char(
  95. string='Format',
  96. help='Python Format String valid with str.format()\n'
  97. 'ie: \'{:,} Kgs\' will output \'1,000 Kgs\' if value is 1000.')
  98. primary_value = fields.Char(
  99. string='Value',
  100. compute='_compute_data')
  101. primary_helper = fields.Char(
  102. string='Helper',
  103. compute='_compute_helper')
  104. # Secondary Value
  105. secondary_function = fields.Selection(
  106. FIELD_FUNCTION_SELECTION,
  107. string='Secondary Function')
  108. secondary_field_id = fields.Many2one(
  109. 'ir.model.fields',
  110. string='Secondary Field',
  111. domain="[('model_id', '=', model_id),"
  112. " ('ttype', 'in', ['float', 'integer'])]")
  113. secondary_format = fields.Char(
  114. string='Secondary Format',
  115. help='Python Format String valid with str.format()\n'
  116. 'ie: \'{:,} Kgs\' will output \'1,000 Kgs\' if value is 1000.')
  117. secondary_value = fields.Char(
  118. string='Secondary Value',
  119. compute='_compute_data')
  120. secondary_helper = fields.Char(
  121. string='Secondary Helper',
  122. compute='_compute_helper')
  123. error = fields.Char(
  124. string='Error Details',
  125. compute='_compute_data')
  126. @api.one
  127. def _compute_data(self):
  128. if not self.active:
  129. return
  130. model = self.env[self.model_id.model]
  131. eval_context = self._get_eval_context()
  132. domain = self.domain or '[]'
  133. try:
  134. count = model.search_count(eval(domain, eval_context))
  135. except Exception as e:
  136. self.primary_value = self.secondary_value = 'ERR!'
  137. self.error = str(e)
  138. return
  139. if any([
  140. self.primary_function and
  141. self.primary_function != 'count',
  142. self.secondary_function and
  143. self.secondary_function != 'count'
  144. ]):
  145. records = model.search(eval(domain, eval_context))
  146. for f in ['primary_', 'secondary_']:
  147. f_function = f+'function'
  148. f_field_id = f+'field_id'
  149. f_format = f+'format'
  150. f_value = f+'value'
  151. value = 0
  152. if self[f_function] == 'count':
  153. value = count
  154. elif self[f_function]:
  155. func = FIELD_FUNCTIONS[self[f_function]]['func']
  156. if func and self[f_field_id] and count:
  157. vals = [x[self[f_field_id].name] for x in records]
  158. value = func(vals)
  159. if self[f_function]:
  160. try:
  161. self[f_value] = (self[f_format] or '{:,}').format(value)
  162. except ValueError as e:
  163. self[f_value] = 'F_ERR!'
  164. self.error = str(e)
  165. return
  166. else:
  167. self[f_value] = False
  168. @api.one
  169. @api.onchange('primary_function', 'primary_field_id',
  170. 'secondary_function', 'secondary_field_id')
  171. def _compute_helper(self):
  172. for f in ['primary_', 'secondary_']:
  173. f_function = f+'function'
  174. f_field_id = f+'field_id'
  175. f_helper = f+'helper'
  176. self[f_helper] = ''
  177. field_func = FIELD_FUNCTIONS.get(self[f_function], {})
  178. help = field_func.get('help', False)
  179. if help:
  180. if self[f_function] != 'count' and self[f_field_id]:
  181. desc = self[f_field_id].field_description
  182. self[f_helper] = help % desc
  183. else:
  184. self[f_helper] = help
  185. @api.one
  186. def _compute_active(self):
  187. ima = self.env['ir.model.access']
  188. self.active = ima.check(self.model_id.model, 'read', False)
  189. def _search_active(self, operator, value):
  190. cr = self.env.cr
  191. if operator != '=':
  192. raise except_orm(
  193. _('Unimplemented Feature. Search on Active field disabled.'))
  194. ima = self.env['ir.model.access']
  195. ids = []
  196. cr.execute("""
  197. SELECT tt.id, im.model
  198. FROM tile_tile tt
  199. INNER JOIN ir_model im
  200. ON tt.model_id = im.id""")
  201. for result in cr.fetchall():
  202. if (ima.check(result[1], 'read', False) == value):
  203. ids.append(result[0])
  204. return [('id', 'in', ids)]
  205. # Constraints and onchanges
  206. @api.one
  207. @api.constrains('model_id', 'primary_field_id', 'secondary_field_id')
  208. def _check_model_id_field_id(self):
  209. if any([
  210. self.primary_field_id and
  211. self.primary_field_id.model_id.id != self.model_id.id,
  212. self.secondary_field_id and
  213. self.secondary_field_id.model_id.id != self.model_id.id
  214. ]):
  215. raise ValidationError(
  216. _("Please select a field from the selected model."))
  217. @api.onchange('model_id')
  218. def _onchange_model_id(self):
  219. self.primary_field_id = False
  220. self.secondary_field_id = False
  221. @api.onchange('primary_function', 'secondary_function')
  222. def _onchange_function(self):
  223. if self.primary_function in [False, 'count']:
  224. self.primary_field_id = False
  225. if self.secondary_function in [False, 'count']:
  226. self.secondary_field_id = False
  227. # Action methods
  228. @api.multi
  229. def open_link(self):
  230. res = {
  231. 'name': self.name,
  232. 'view_type': 'form',
  233. 'view_mode': 'tree',
  234. 'view_id': [False],
  235. 'res_model': self.model_id.model,
  236. 'type': 'ir.actions.act_window',
  237. 'context': self.env.context,
  238. 'nodestroy': True,
  239. 'target': 'current',
  240. 'domain': self.domain,
  241. }
  242. if self.action_id:
  243. res.update(self.action_id.read(
  244. ['view_type', 'view_mode', 'type'])[0])
  245. return res
  246. @api.model
  247. def add(self, vals):
  248. if 'model_id' in vals and not vals['model_id'].isdigit():
  249. # need to replace model_name with its id
  250. vals['model_id'] = self.env['ir.model'].search(
  251. [('model', '=', vals['model_id'])]).id
  252. self.create(vals)