3f3a93d21a68f3934f9823371c9c85e4b4d868de
[odoo/odoo.git] / addons / hr_holidays / report / holidays_summary_report.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 datetime
23 import time
24
25 from openerp.osv import fields, osv
26 from openerp.report.interface import report_rml
27 from openerp.report.interface import toxml
28
29 from openerp import pooler
30 import time
31 from openerp.report import report_sxw
32 from openerp.tools import ustr
33 from openerp.tools.translate import _
34 from openerp.tools import to_xml
35
36 def lengthmonth(year, month):
37     if month == 2 and ((year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))):
38         return 29
39     return [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
40
41 def strToDate(dt):
42     if dt:
43         dt_date=datetime.date(int(dt[0:4]),int(dt[5:7]),int(dt[8:10]))
44         return dt_date
45     else:
46         return
47
48
49 def emp_create_xml(self, cr, uid, dept, holiday_type, row_id, empid, name, som, eom):
50     display={}
51     if dept==0:
52         count=0
53         p_id=pooler.get_pool(cr.dbname).get('hr.holidays').search(cr, uid, [('employee_id','in',[empid,False]), ('type', '=', 'remove')])
54         ids_date = pooler.get_pool(cr.dbname).get('hr.holidays').read(cr, uid, p_id, ['date_from','date_to','holiday_status_id','state'])
55
56         for index in range(1,61):
57             diff=index-1
58             current=som+datetime.timedelta(diff)
59
60             for item in ids_date:
61                 if current >= strToDate(item['date_from']) and current <= strToDate(item['date_to']):
62                     if item['state'] in holiday_type:
63                         display[index]=item['holiday_status_id'][0]
64                         count=count +1
65                     else:
66                         display[index]=' '
67                     break
68                 else:
69                     display[index]=' '
70     else:
71          for index in range(1,61):
72               display[index]=' '
73               count=''
74               
75     data_xml=['<info id="%d" number="%d" val="%s" />' % (row_id,x,display[x]) for x in range(1,len(display)+1) ]
76     
77     # Computing the xml
78     xml = '''
79     %s
80     <employee row="%d" id="%d" name="%s" sum="%s">
81     </employee>
82     ''' % (data_xml,row_id,dept, ustr(toxml(name)),count)
83
84     return xml
85
86 class report_custom(report_rml):
87     def create_xml(self, cr, uid, ids, data, context):
88         obj_dept = pooler.get_pool(cr.dbname).get('hr.department')
89         obj_emp = pooler.get_pool(cr.dbname).get('hr.employee')
90         depts=[]
91         emp_id={}
92 #        done={}
93         rpt_obj = pooler.get_pool(cr.dbname).get('hr.holidays')
94         rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context)
95         cr.execute("SELECT name FROM res_company")
96         res=cr.fetchone()[0]
97         date_xml=[]
98         date_today=time.strftime('%Y-%m-%d %H:%M:%S')
99         date_xml +=['<res name="%s" today="%s" />' % (to_xml(res),date_today)]
100
101         cr.execute("SELECT id, name, color_name FROM hr_holidays_status ORDER BY id")
102         legend=cr.fetchall()
103         today=datetime.datetime.today()
104
105         first_date=data['form']['date_from']
106         som = strToDate(first_date)
107         eom = som+datetime.timedelta(59)
108         day_diff=eom-som
109
110         name = ''
111         if len(data['form'].get('emp', ())) == 1:
112             name = obj_emp.read(cr, uid, data['form']['emp'][0], ['name'])['name']
113
114         if data['form']['holiday_type']!='both':
115             type=data['form']['holiday_type']
116             if data['form']['holiday_type']=='Confirmed':
117                 holiday_type=('confirm')
118             else:
119                 holiday_type=('validate')
120         else:
121             type="Confirmed and Approved"
122             holiday_type=('confirm','validate')
123         date_xml.append('<from>%s</from>\n'% (str(rml_obj.formatLang(som.strftime("%Y-%m-%d"),date=True))))
124         date_xml.append('<to>%s</to>\n' %(str(rml_obj.formatLang(eom.strftime("%Y-%m-%d"),date=True))))
125         date_xml.append('<type>%s</type>'%(type))
126         date_xml.append('<name>%s</name>'%(name))
127
128 #        date_xml=[]
129         for l in range(0,len(legend)):
130             date_xml += ['<legend row="%d" id="%d" name="%s" color="%s" />' % (l+1,legend[l][0],_(legend[l][1]),legend[l][2])]
131         date_xml += ['<date month="%s" year="%d" />' % (ustr(som.strftime('%B')), som.year),'<days>']
132
133         cell=1
134         if day_diff.days>=30:
135             date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)]
136         else:
137             if day_diff.days>=(lengthmonth(som.year, som.month)-som.day):
138                 date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)]
139             else:
140                 date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, eom.day+1)]
141
142         cell=x-som.day+1
143         day_diff1=day_diff.days-cell+1
144
145         width_dict={}
146         month_dict={}
147
148         i=1
149         j=1
150         year=som.year
151         month=som.month
152         month_dict[j]=som.strftime('%B')
153         width_dict[j]=cell
154
155         while day_diff1>0:
156             if month+i<=12:
157                 if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example
158                     som1=datetime.date(year,month+i,1)
159                     date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)]
160                     i=i+1
161                     j=j+1
162                     month_dict[j]=som1.strftime('%B')
163                     cell=cell+x
164                     width_dict[j]=x
165
166                 else:
167                     som1=datetime.date(year,month+i,1)
168                     date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)]
169                     i=i+1
170                     j=j+1
171                     month_dict[j]=som1.strftime('%B')
172                     cell=cell+x
173                     width_dict[j]=x
174
175                 day_diff1=day_diff1-x
176             else:
177                 years=year+1
178                 year=years
179                 month=0
180                 i=1
181                 if day_diff1>=30:
182                     som1=datetime.date(years,i,1)
183                     date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(years,i)+1)]
184                     i=i+1
185                     j=j+1
186                     month_dict[j]=som1.strftime('%B')
187                     cell=cell+x
188                     width_dict[j]=x
189
190                 else:
191                     som1=datetime.date(years,i,1)
192                     i=i+1
193                     j=j+1
194                     month_dict[j]=som1.strftime('%B')
195                     date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)]
196                     cell=cell+x
197                     width_dict[j]=x
198
199                 day_diff1=day_diff1-x
200
201         date_xml.append('</days>')
202         date_xml.append('<cols>3.5cm%s,0.4cm</cols>\n' % (',0.4cm' * (60)))
203         date_xml = ''.join(date_xml)
204
205         st='<cols_months>3.5cm'
206         for m in range(1,len(width_dict)+1):
207             st+=',' + str(0.4 *width_dict[m])+'cm'
208         st+=',0.4cm</cols_months>\n'
209
210         months_xml =['<months  number="%d" name="%s"/>' % (x, _(month_dict[x])) for x in range(1,len(month_dict)+1) ]
211         months_xml.append(st)
212         
213         emp_xml=''
214         row_id=1
215         
216         if data['model']=='hr.employee':
217             for id in data['form']['emp']:
218                  items = obj_emp.read(cr, uid, id, ['id','name'])
219                  
220                  emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, items['id'], items['name'], som, eom)
221                  row_id = row_id +1
222
223         elif data['model']=='ir.ui.menu':
224             for id in data['form']['depts']:
225                 dept = obj_dept.browse(cr, uid, id, context=context)
226                 emp_ids = obj_emp.search(cr, uid, [('department_id', '=', id)])
227                 if emp_ids==[]:
228                     continue
229                 dept_done=0
230                 for item in obj_emp.read(cr, uid, emp_ids, ['id', 'name']):
231                     if dept_done==0:
232                         emp_xml += emp_create_xml(self, cr, uid, 1, holiday_type, row_id, dept.id, dept.name, som, eom)
233                         row_id = row_id +1
234                     dept_done=1
235                     emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, item['id'], item['name'], som, eom)
236                     row_id = row_id +1
237                     
238         header_xml = '''
239         <header>
240         <date>%s</date>
241         <company>%s</company>
242         </header>
243         ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(pooler.get_pool(cr.dbname).get('res.users').browse(cr,uid,uid).company_id.name))
244
245         # Computing the xml
246         xml='''<?xml version="1.0" encoding="UTF-8" ?>
247         <report>
248         %s
249         %s
250         %s
251         %s
252         </report>
253         ''' % (header_xml,months_xml,date_xml, ustr(emp_xml))
254
255         return xml
256
257 report_custom('report.holidays.summary', 'hr.holidays', '', 'addons/hr_holidays/report/holidays_summary.xsl')
258
259 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
260