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