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.

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