[IMP] sale, crm: remove remaining interval filters, continuing 366a30d
[odoo/odoo.git] / addons / crm / report / report_businessopp.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import os, time
23
24 import random
25 import StringIO
26
27 from openerp.report.render import render
28 from openerp.report.interface import report_int
29 from pychart import *
30
31 theme.use_color = 1
32
33 class external_pdf(render):
34
35     """ Generate External PDF """
36
37     def __init__(self, pdf):
38         render.__init__(self)
39         self.pdf = pdf
40         self.output_type = 'pdf'
41
42     def _render(self):
43         return self.pdf
44
45 class report_custom(report_int):
46
47     """ Create Custom Report """
48
49     def create(self, cr, uid, ids, datas, context=None):
50
51         """ @param cr: the current row, from the database cursor,
52             @param uid: the current user’s ID for security checks,
53             @param ids: List of IDs
54             @param context: A standard dictionary for contextual values """
55
56         assert len(ids), 'You should provide some ids!'
57         responsible_data = {}
58         responsible_names = {}
59         data = []
60         minbenef = 999999999999999999999
61         maxbenef = 0
62
63         cr.execute('select probability, planned_revenue, planned_cost, user_id,\
64                  res_users.name as name from crm_case left join res_users on \
65                  (crm_case.user_id=res_users.id) where crm_case.id IN %s order by user_id',(tuple(ids),))
66
67         res = cr.dictfetchall()
68         for row in res:
69             proba = row['probability'] or 0 / 100.0
70             cost = row['planned_cost'] or 0
71             revenue = row['planned_revenue'] or 0
72             userid = row['user_id'] or 0
73
74             benefit = revenue - cost
75             if benefit > maxbenef:
76                 maxbenef = benefit
77             if benefit < minbenef:
78                 minbenef = benefit
79
80             tuple_benefit = (proba * 100,  benefit)
81             responsible_data.setdefault(userid, [])
82             responsible_data[userid].append(tuple_benefit)
83
84             tuple_benefit = (proba * 100, cost, benefit)
85             data.append(tuple_benefit)
86
87             responsible_names[userid] = (row['name'] or '/').replace('/','//')
88
89         minbenef -= maxbenef * 0.05
90         maxbenef *= 1.2
91
92         ratio = 0.5
93         minmaxdiff2 = (maxbenef - minbenef)/2
94
95         for l in responsible_data.itervalues():
96             for i in range(len(l)):
97                 percent, benef = l[i]
98                 proba = percent/100
99
100                 current_ratio = 1 + (ratio-1) * proba
101
102                 newbenef = minmaxdiff2 + ((benef - minbenef - minmaxdiff2) * current_ratio)
103
104                 l[i] = (percent, newbenef)
105
106 #TODO:
107 #-group by "categorie de probabilites ds graphe du haut"
108 #-echelle variable
109
110         pdf_string = StringIO.StringIO()
111         can = canvas.init(fname = pdf_string, format = 'pdf')
112
113         chart_object.set_defaults(line_plot.T, line_style=None)
114
115         xaxis = axis.X(label=None, format="%d%%", tic_interval=20)
116         yaxis = axis.Y()
117
118         x_range_a, x_range_b = (0, 100)
119         y_range_a, y_range_b = (minbenef, maxbenef)
120         if y_range_a == 0.0:
121             y_range_a += 0.0001
122
123         ar = area.T(
124             size = (300,200),
125             y_grid_interval = 10000,
126             y_grid_style = None,
127             x_range = (x_range_a, x_range_b),
128             y_range = (y_range_a, y_range_b),
129             x_axis = xaxis,
130             y_axis = None,
131             legend = legend.T()
132         )
133
134         #import pydb; pydb.debugger()
135         for k, d in responsible_data.iteritems():
136             fill = fill_style.Plain(bgcolor=color.T(r=random.random(), g=random.random(), b=random.random()))
137             tick = tick_mark.Square(size=6, fill_style=fill)
138             ar.add_plot(line_plot.T(label=responsible_names[k], data=d, tick_mark=tick))
139
140         ar.draw(can)
141
142         # second graph (top right)
143         ar = area.T(legend = legend.T(),
144                     size = (200,100),
145                     loc = (100,250),
146                     x_grid_interval = lambda min, max: [40,60,80,100],
147                     x_grid_style = line_style.gray70_dash1,
148                     x_range = (33, 100),
149                     x_axis = axis.X(label=None, minor_tic_interval = lambda min,max: [50, 70, 90],\
150                                      format=lambda x: ""),
151                     y_axis = axis.Y(label="Planned amounts"))
152
153         bar_plot.fill_styles.reset();
154         plot1 = bar_plot.T(label="Cost", data=data, fill_style=fill_style.red)
155         plot2 = bar_plot.T(label="Revenue", data=data, hcol=2, stack_on = plot1, fill_style=fill_style.blue)
156
157         ar.add_plot(plot1, plot2)
158
159         ar.draw(can)
160
161         # diagonal "pipeline" lines
162         can.line(line_style.black, 0, 200, 300, 150)
163         can.line(line_style.black, 0, 0, 300, 50)
164
165         # vertical lines
166         ls = line_style.T(width=0.4, color=color.gray70, dash=(2, 2))
167         for x in range(120, 300, 60):
168             can.line(ls, x, 0, x, 250)
169
170         # draw arrows to the right
171         a = arrow.fat1
172         for y in range(60, 150, 10):
173             a.draw([(285, y), (315, y)], can=can)
174
175         # close canvas so that the file is written to "disk"
176         can.close()
177
178         self.obj = external_pdf(pdf_string.getvalue())
179         self.obj.render()
180
181         pdf_string.close()
182         return (self.obj.pdf, 'pdf')
183
184 report_custom('report.crm.case')
185
186 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
187