[FIX] Typo
[odoo/odoo.git] / addons / mrp / report / workcenter_load.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 from openerp.report.render import render
23 from openerp.report.interface import report_int
24 import time
25 from datetime import date, datetime, timedelta
26 from dateutil.relativedelta import relativedelta
27
28 from openerp.report.misc import choice_colors
29
30 import StringIO
31
32 from pychart import *
33
34 theme.use_color = 1
35
36 #
37 # TODO: Bad code, seems buggy, TO CHECK !
38 #
39
40 class external_pdf(render):
41     def __init__(self, pdf):
42         render.__init__(self)
43         self.pdf = pdf
44         self.output_type='pdf'
45
46     def _render(self):
47         return self.pdf
48
49 class report_custom(report_int):
50     def _compute_dates(self, time_unit, start, stop):
51         if not stop:
52             stop = start
53         if time_unit == 'month':
54             dates = {}
55             a = int(start.split("-")[0])*12 + int(start.split("-")[1])
56             z = int(stop.split("-")[0])*12 + int(stop.split("-")[1]) + 1
57             for i in range(a,z):
58                 year = i/12
59                 month = i%12
60                 if month == 0:
61                     year -= 1
62                     month = 12
63                 months = {1:"January",2:"February",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October",11:"November",12:"December"}
64                 dates[i] = {
65                     'name' :months[month],
66                     'start':(datetime(year, month, 2) + relativedelta(day=1)).strftime('%Y-%m-%d'),
67                     'stop' :(datetime(year, month, 2) + relativedelta(day=31)).strftime('%Y-%m-%d'),
68                 }
69             return dates
70         elif time_unit == 'week':
71             dates = {}
72             start_week = date(int(start.split("-")[0]),int(start.split("-")[1]),int(start.split("-")[2])).isocalendar()
73             end_week = date(int(stop.split("-")[0]),int(stop.split("-")[1]),int(stop.split("-")[2])).isocalendar()
74             a = int(start.split("-")[0])*52 + start_week[1]
75             z = int(stop.split("-")[0])*52 + end_week[1]
76             for i in range(a,z+1):
77                 year = i/52
78                 week = i%52
79                 d = date(year, 1, 1)
80
81                 dates[i] = {
82                     'name' :"Week #%d" % week,
83                     'start':(d + timedelta(days=-d.weekday(), weeks=week)).strftime('%Y-%m-%d'),
84                     'stop' :(d + timedelta(days=6-d.weekday(), weeks=week)).strftime('%Y-%m-%d'),
85                 }
86             return dates
87         else: # time_unit = day
88             dates = {}
89             a = datetime(int(start.split("-")[0]),int(start.split("-")[1]),int(start.split("-")[2]))
90             z = datetime(int(stop.split("-")[0]),int(stop.split("-")[1]),int(stop.split("-")[2]))
91             i = a
92             while i <= z:
93                 dates[map(int,i.strftime('%Y%m%d').split())[0]] = {
94                     'name' :i.strftime('%Y-%m-%d'),
95                     'start':i.strftime('%Y-%m-%d'),
96                     'stop' :i.strftime('%Y-%m-%d'),
97                 }
98                 i = i + relativedelta(days=+1)
99             return dates
100         return {}
101
102     def create(self, cr, uid, ids, datas, context=None):
103         assert len(ids), 'You should provide some ids!'
104         colors = choice_colors(len(ids))
105         cr.execute(
106             "SELECT MAX(mrp_production.date_planned) AS stop,MIN(mrp_production.date_planned) AS start "\
107             "FROM mrp_workcenter, mrp_production, mrp_production_workcenter_line "\
108             "WHERE mrp_production_workcenter_line.production_id=mrp_production.id "\
109             "AND mrp_production_workcenter_line.workcenter_id=mrp_workcenter.id "\
110             "AND mrp_production.state NOT IN ('cancel','done') "\
111             "AND mrp_workcenter.id IN %s",(tuple(ids),))
112         res = cr.dictfetchone()
113         if not res['stop']:
114             res['stop'] = time.strftime('%Y-%m-%d %H:%M:%S')
115         if not res['start']:
116             res['start'] = time.strftime('%Y-%m-%d %H:%M:%S')
117         dates = self._compute_dates(datas['form']['time_unit'], res['start'][:10], res['stop'][:10])
118         dates_list = dates.keys()
119         dates_list.sort()
120         x_index = []
121         for date in dates_list:
122             x_index.append((dates[date]['name'], date))
123         pdf_string = StringIO.StringIO()
124         can = canvas.init(fname=pdf_string, format='pdf')
125         can.set_title("Work Center Loads")
126         chart_object.set_defaults(line_plot.T, line_style=None)
127         if datas['form']['measure_unit'] == 'cycles':
128             y_label = "Load (Cycles)"
129         else:
130             y_label = "Load (Hours)"
131
132         # For add the report header on the top of the report.
133         tb = text_box.T(loc=(300, 500), text="/hL/15/bWork Center Loads", line_style=None)
134         tb.draw()
135         ar = area.T(legend = legend.T(),
136                     x_grid_style = line_style.gray70_dash1,
137                     x_axis = axis.X(label="Periods", format="/a90/hC%s"),
138                     x_coord = category_coord.T(x_index, 0),
139                     y_axis = axis.Y(label=y_label),
140                     y_range = (0, None),
141                     size = (640,480))
142         bar_plot.fill_styles.reset();
143         # select workcenters
144         cr.execute(
145             "SELECT mw.id, rs.name FROM mrp_workcenter mw, resource_resource rs " \
146             "WHERE mw.id IN %s and mw.resource_id=rs.id " \
147             "ORDER BY mw.id" ,(tuple(ids),))
148         workcenters = cr.dictfetchall()
149
150         data = []
151         for date in dates_list:
152             vals = []
153             for workcenter in workcenters:
154                 cr.execute("SELECT SUM(mrp_production_workcenter_line.hour) AS hours, SUM(mrp_production_workcenter_line.cycle) AS cycles, \
155                                 resource_resource.name AS name, mrp_workcenter.id AS id \
156                             FROM mrp_production_workcenter_line, mrp_production, mrp_workcenter, resource_resource \
157                             WHERE (mrp_production_workcenter_line.production_id=mrp_production.id) \
158                                 AND (mrp_production_workcenter_line.workcenter_id=mrp_workcenter.id) \
159                                 AND (mrp_workcenter.resource_id=resource_resource.id) \
160                                 AND (mrp_workcenter.id=%s) \
161                                 AND (mrp_production.date_planned BETWEEN %s AND %s) \
162                             GROUP BY mrp_production_workcenter_line.workcenter_id, resource_resource.name, mrp_workcenter.id \
163                             ORDER BY mrp_workcenter.id", (workcenter['id'], dates[date]['start'] + ' 00:00:00', dates[date]['stop'] + ' 23:59:59'))
164                 res = cr.dictfetchall()
165                 if not res:
166                     vals.append(0.0)
167                 else:
168                     if datas['form']['measure_unit'] == 'cycles':
169                         vals.append(res[0]['cycles'] or 0.0)
170                     else:
171                         vals.append(res[0]['hours'] or 0.0)
172
173             toto = [dates[date]['name']]
174             for val in vals:
175                 toto.append(val)
176             data.append(toto)
177
178         workcenter_num = 0
179         for workcenter in workcenters:
180             f = fill_style.Plain()
181             f.bgcolor = colors[workcenter_num]
182             ar.add_plot(bar_plot.T(label=workcenter['name'], data=data, fill_style=f, hcol=workcenter_num+1, cluster=(workcenter_num, len(res))))
183             workcenter_num += 1
184
185         if (not data) or (len(data[0]) <= 1):
186             ar = self._empty_graph(time.strftime('%Y-%m-%d'))
187         ar.draw(can)
188         # close canvas so that the file is written to "disk"
189         can.close()
190         self.obj = external_pdf(pdf_string.getvalue())
191         self.obj.render()
192         pdf_string.close()
193         return (self.obj.pdf, 'pdf')
194
195     def _empty_graph(self, date):
196         data = [[date, 0]]
197         ar = area.T(x_coord = category_coord.T(data, 0), y_range = (0, None),
198                     x_axis = axis.X(label="Periods"),
199                     y_axis = axis.Y(label="Load"))
200         ar.add_plot(bar_plot.T(data = data, label="No production order"))
201         return ar
202
203 report_custom('report.mrp.workcenter.load')
204
205
206 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
207