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