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.

283 lines
9.7 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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.multi
  127. def _compute_data(self):
  128. for rec in self:
  129. if not rec.active:
  130. return
  131. model = self.env[rec.model_id.model]
  132. eval_context = self._get_eval_context()
  133. domain = rec.domain or '[]'
  134. try:
  135. count = model.search_count(eval(domain, eval_context))
  136. except Exception as e:
  137. rec.primary_value = rec.secondary_value = 'ERR!'
  138. rec.error = str(e)
  139. return
  140. if any([
  141. rec.primary_function and
  142. rec.primary_function != 'count',
  143. rec.secondary_function and
  144. rec.secondary_function != 'count'
  145. ]):
  146. records = model.search(eval(domain, eval_context))
  147. for f in ['primary_', 'secondary_']:
  148. f_function = f + 'function'
  149. f_field_id = f + 'field_id'
  150. f_format = f + 'format'
  151. f_value = f + 'value'
  152. value = 0
  153. if rec[f_function] == 'count':
  154. value = count
  155. elif rec[f_function]:
  156. func = FIELD_FUNCTIONS[rec[f_function]]['func']
  157. if func and rec[f_field_id] and count:
  158. vals = [x[rec[f_field_id].name] for x in records]
  159. value = func(vals)
  160. if rec[f_function]:
  161. try:
  162. rec[f_value] = (rec[f_format] or '{:,}').format(value)
  163. except ValueError as e:
  164. rec[f_value] = 'F_ERR!'
  165. rec.error = str(e)
  166. return
  167. else:
  168. rec[f_value] = False
  169. @api.multi
  170. @api.onchange('primary_function', 'primary_field_id',
  171. 'secondary_function', 'secondary_field_id')
  172. def _compute_helper(self):
  173. for rec in self:
  174. for f in ['primary_', 'secondary_']:
  175. f_function = f + 'function'
  176. f_field_id = f + 'field_id'
  177. f_helper = f + 'helper'
  178. rec[f_helper] = ''
  179. field_func = FIELD_FUNCTIONS.get(rec[f_function], {})
  180. help = field_func.get('help', False)
  181. if help:
  182. if rec[f_function] != 'count' and rec[f_field_id]:
  183. desc = rec[f_field_id].field_description
  184. rec[f_helper] = help % desc
  185. else:
  186. rec[f_helper] = help
  187. @api.multi
  188. def _compute_active(self):
  189. ima = self.env['ir.model.access']
  190. for rec in self:
  191. rec.active = ima.check(rec.model_id.model, 'read', False)
  192. def _search_active(self, operator, value):
  193. cr = self.env.cr
  194. if operator != '=':
  195. raise except_orm(
  196. _('Unimplemented Feature. Search on Active field disabled.'))
  197. ima = self.env['ir.model.access']
  198. ids = []
  199. cr.execute("""
  200. SELECT tt.id, im.model
  201. FROM tile_tile tt
  202. INNER JOIN ir_model im
  203. ON tt.model_id = im.id""")
  204. for result in cr.fetchall():
  205. if (ima.check(result[1], 'read', False) == value):
  206. ids.append(result[0])
  207. return [('id', 'in', ids)]
  208. # Constraints and onchanges
  209. @api.multi
  210. @api.constrains('model_id', 'primary_field_id', 'secondary_field_id')
  211. def _check_model_id_field_id(self):
  212. for rec in self:
  213. if any([
  214. rec.primary_field_id and
  215. rec.primary_field_id.model_id.id != rec.model_id.id,
  216. rec.secondary_field_id and
  217. rec.secondary_field_id.model_id.id != rec.model_id.id
  218. ]):
  219. raise ValidationError(
  220. _("Please select a field from the selected model."))
  221. @api.onchange('model_id')
  222. def _onchange_model_id(self):
  223. self.primary_field_id = False
  224. self.secondary_field_id = False
  225. @api.onchange('primary_function', 'secondary_function')
  226. def _onchange_function(self):
  227. if self.primary_function in [False, 'count']:
  228. self.primary_field_id = False
  229. if self.secondary_function in [False, 'count']:
  230. self.secondary_field_id = False
  231. # Action methods
  232. @api.multi
  233. def open_link(self):
  234. res = {
  235. 'name': self.name,
  236. 'view_type': 'form',
  237. 'view_mode': 'tree',
  238. 'view_id': [False],
  239. 'res_model': self.model_id.model,
  240. 'type': 'ir.actions.act_window',
  241. 'context': self.env.context,
  242. 'nodestroy': True,
  243. 'target': 'current',
  244. 'domain': self.domain,
  245. }
  246. if self.action_id:
  247. res.update(self.action_id.read(
  248. ['view_type', 'view_mode', 'type'])[0])
  249. return res
  250. @api.model
  251. def add(self, vals):
  252. if 'model_id' in vals and not vals['model_id'].isdigit():
  253. # need to replace model_name with its id
  254. vals['model_id'] = self.env['ir.model'].search(
  255. [('model', '=', vals['model_id'])]).id
  256. self.create(vals)