[IMP] mail : Improved the Search View.
[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         if data['form']['holiday_type']!='both':
110             type=data['form']['holiday_type']
111             if data['form']['holiday_type']=='Confirmed':
112                 holiday_type=('confirm')
113             else:
114                 holiday_type=('validate')
115         else:
116             type="Confirmed and Validated"
117             holiday_type=('confirm','validate')
118         date_xml.append('<from>%s</from>\n'% (str(rml_obj.formatLang(som.strftime("%Y-%m-%d"),date=True))))
119         date_xml.append('<to>%s</to>\n' %(str(rml_obj.formatLang(eom.strftime("%Y-%m-%d"),date=True))))
120         date_xml.append('<type>%s</type>'%(type))
121
122 #        date_xml=[]
123         for l in range(0,len(legend)):
124             date_xml += ['<legend row="%d" id="%d" name="%s" color="%s" />' % (l+1,legend[l][0],_(legend[l][1]),legend[l][2])]
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 id in data['form']['emp']:
211                  items = obj_emp.read(cr, uid, 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 id in data['form']['depts']:
218                 dept = obj_dept.browse(cr, uid, id, context=context)
219                 cr.execute("""SELECT id FROM hr_employee \
220                 WHERE department_id = %s""", (id,))
221                 emp_ids = [x[0] for x in cr.fetchall()]
222                 if emp_ids==[]:
223                     continue
224                 dept_done=0
225                 for item in obj_emp.read(cr, uid, emp_ids, ['id', 'name']):
226                     if dept_done==0:
227                         emp_xml += emp_create_xml(self, cr, uid, 1, holiday_type, row_id, dept.id, dept.name, som, eom)
228                         row_id = row_id +1
229                     dept_done=1
230                     emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, item['id'], item['name'], som, eom)
231                     row_id = row_id +1
232                     
233         header_xml = '''
234         <header>
235         <date>%s</date>
236         <company>%s</company>
237         </header>
238         '''  % (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)
239
240         # Computing the xml
241         xml='''<?xml version="1.0" encoding="UTF-8" ?>
242         <report>
243         %s
244         %s
245         %s
246         %s
247         </report>
248         ''' % (header_xml,months_xml,date_xml, ustr(emp_xml))
249
250         return xml
251
252 report_custom('report.holidays.summary', 'hr.holidays', '', 'addons/hr_holidays/report/holidays_summary.xsl')
253
254 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
255