[FIX]: base_calendar: Missing function
[odoo/odoo.git] / addons / base_calendar / base_calendar.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 from datetime import datetime, timedelta
22 from dateutil import parser
23 from dateutil import rrule
24 from osv import fields, osv
25 from service import web_services
26 from tools.translate import _
27 import base64
28 import pooler
29 import pytz
30 import re
31 import time
32 import tools
33
34 months = {
35         1:"January", 2:"February", 3:"March", 4:"April", \
36         5:"May", 6:"June", 7:"July", 8:"August", 9:"September", \
37         10:"October", 11:"November", 12:"December"}
38
39 def get_recurrent_dates(rrulestring, exdate, startdate=None):
40     def todate(date):
41         val = parser.parse(''.join((re.compile('\d')).findall(date)) + 'Z')
42         return val
43     if not startdate:
44         startdate = datetime.now()
45     rset1 = rrule.rrulestr(rrulestring, dtstart=startdate, forceset=True)
46
47     for date in exdate:
48         datetime_obj = todate(date)
49         rset1._exdate.append(datetime_obj)
50     re_dates = map(lambda x:x.strftime('%Y-%m-%d %H:%M:%S'), rset1._iter())
51     return re_dates
52
53 def base_calendar_id2real_id(base_calendar_id=None, with_date=False):
54     if base_calendar_id and isinstance(base_calendar_id, (str, unicode)):
55         res = base_calendar_id.split('-')
56         if len(res) >= 2:
57             real_id = res[0]
58             if with_date:
59                 real_date = time.strftime("%Y-%m-%d %H:%M:%S", \
60                                  time.strptime(res[1], "%Y%m%d%H%M%S"))
61                 start = datetime.strptime(real_date, "%Y-%m-%d %H:%M:%S")
62                 end = start + timedelta(hours=with_date)
63                 return (int(real_id), real_date, end.strftime("%Y-%m-%d %H:%M:%S"))
64             return int(real_id)
65     return base_calendar_id and int(base_calendar_id) or base_calendar_id
66
67 def real_id2base_calendar_id(real_id, recurrent_date):
68     if real_id and recurrent_date:
69         recurrent_date = time.strftime("%Y%m%d%H%M%S", \
70                          time.strptime(recurrent_date, "%Y-%m-%d %H:%M:%S"))
71         return '%d-%s' % (real_id, recurrent_date)
72     return real_id
73
74
75 def _links_get(self, cr, uid, context={}):
76     obj = self.pool.get('res.request.link')
77     ids = obj.search(cr, uid, [])
78     res = obj.read(cr, uid, ids, ['object', 'name'], context)
79     return [(r['object'], r['name']) for r in res]
80
81 html_invitation = """
82 <html>
83 <head>
84 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
85 <title>%(name)s</title>
86 </head>
87 <body>
88 <table border="0" cellspacing="10" cellpadding="0" width="100%%"
89     style="font-family: Arial, Sans-serif; font-size: 14">
90     <tr>
91         <td width="100%%">Hello,</td>
92     </tr>
93     <tr>
94         <td width="100%%">You are invited for <i>%(company)s</i> Event.</td>
95     </tr>
96     <tr>
97         <td width="100%%">Below are the details of event:</td>
98     </tr>
99 </table>
100
101 <table cellspacing="0" cellpadding="5" border="0" summary=""
102     style="width: 90%%; font-family: Arial, Sans-serif; border: 1px Solid #ccc; background-color: #f6f6f6">
103     <tr valign="center" align="center">
104         <td bgcolor="DFDFDF">
105         <h3>%(name)s</h3>
106         </td>
107     </tr>
108     <tr>
109         <td>
110         <table cellpadding="8" cellspacing="0" border="0"
111             style="font-size: 14" summary="Eventdetails" bgcolor="f6f6f6"
112             width="90%%">
113             <tr>
114                 <td width="21%%">
115                 <div><b>Start Date</b></div>
116                 </td>
117                 <td><b>:</b></td>
118                 <td>%(start_date)s</td>
119                 <td width="15%%">
120                 <div><b>End Date</b></div>
121                 </td>
122                 <td><b>:</b></td>
123                 <td width="25%%">%(end_date)s</td>
124             </tr>
125             <tr valign="top">
126                 <td><b>Description</b></td>
127                 <td><b>:</b></td>
128                 <td colspan="3">%(description)s</td>
129             </tr>
130             <tr valign="top">
131                 <td>
132                 <div><b>Location</b></div>
133                 </td>
134                 <td><b>:</b></td>
135                 <td colspan="3">%(location)s</td>
136             </tr>
137             <tr valign="top">
138                 <td>
139                 <div><b>Event Attendees</b></div>
140                 </td>
141                 <td><b>:</b></td>
142                 <td colspan="3">
143                 <div>
144                 <div>%(attendees)s</div>
145                 </div>
146                 </td>
147             </tr>
148             <tr valign="top">
149                 <td><b>Are you coming?</b></td>
150                 <td><b>:</b></td>
151                 <td colspan="3">
152                 <UL>
153                     <LI>YES</LI>
154                     <LI>NO</LI>
155                     <LI>MAYBE</LI>
156                 </UL>
157                 </td>
158             </tr>
159         </table>
160         </td>
161     </tr>
162 </table>
163 <table border="0" cellspacing="10" cellpadding="0" width="100%%"
164     style="font-family: Arial, Sans-serif; font-size: 14">
165     <tr>
166         <td width="100%%"><b>Note:</b> If you are interested please reply this
167         mail and keep only your response from options <i>YES, NO</i>
168         and <i>MAYBE</i>.</td>
169     </tr>
170     <tr>
171         <td width="100%%">From:</td>
172     </tr>
173     <tr>
174         <td width="100%%">%(user)s</td>
175     </tr>
176     <tr valign="top">
177         <td width="100%%">-<font color="a7a7a7">-------------------------</font></td>
178     </tr>
179     <tr>
180         <td width="100%%"> <font color="a7a7a7">%(sign)s</font></td>
181     </tr>
182 </table>
183 </body>
184 </html>
185 """
186
187 class invite_attendee_wizard(osv.osv_memory):
188     _name = "base_calendar.invite.attendee"
189     _description = "Invite Attendees"
190
191     _columns = {
192         'type': fields.selection([('internal', 'Internal User'), \
193               ('external', 'External Email'), \
194               ('partner', 'Partner Contacts')], 'Type', required=True), 
195         'user_ids': fields.many2many('res.users', 'invite_user_rel', 
196                                   'invite_id', 'user_id', 'Users'), 
197         'partner_id': fields.many2one('res.partner', 'Partner'), 
198         'email': fields.char('Email', size=124), 
199         'contact_ids': fields.many2many('res.partner.address', 'invite_contact_rel', 
200                                   'invite_id', 'contact_id', 'Contacts'), 
201         'send_mail': fields.boolean('Send mail?', help='Check this if you want\
202  to send an Email to Invited Person')
203               }
204
205     def do_invite(self, cr, uid, ids, context={}):
206         datas = self.read(cr, uid, ids)[0]
207         model = False
208         model_field = False
209         if not context or not context.get('model'):
210             return {}
211         else:
212             model = context.get('model')
213         model_field = context.get('attendee_field', False)
214         obj = self.pool.get(model)
215         res_obj = obj.browse(cr, uid, context['active_id'])
216         type = datas.get('type')
217         att_obj = self.pool.get('calendar.attendee')
218         vals = {}
219         mail_to = []
220         if not model == 'calendar.attendee':
221             vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
222
223         if type == 'internal':
224             user_obj = self.pool.get('res.users')
225             for user_id in datas.get('user_ids', []):
226                 user = user_obj.browse(cr, uid, user_id)
227                 if not user.address_id.email:
228                     raise osv.except_osv(_('Error!'), \
229                                     ("User does not have an email Address"))
230                 vals.update({'user_id': user_id, 
231                                      'email': user.address_id.email})
232                 mail_to.append(user.address_id.email)
233                 
234         elif  type == 'external' and datas.get('email'):
235             vals.update({'email': datas['email']})
236             mail_to.append(datas['email'])
237         elif  type == 'partner':
238             add_obj = self.pool.get('res.partner.address')
239             for contact in  add_obj.browse(cr, uid, datas['contact_ids']):
240                 if not contact.email:
241                     raise osv.except_osv(_('Error!'), \
242                                     ("Partner does not have an email Address"))
243                 vals.update({
244                              'partner_address_id': contact.id, 
245                              'email': contact.email})
246                 mail_to.append(contact.email)
247
248         if model == 'calendar.attendee':
249             att = att_obj.browse(cr, uid, context['active_id'])
250             vals.update({
251                 'parent_ids' : [(4, att.id)],
252                 'ref': att.ref
253             })
254         att_id = att_obj.create(cr, uid, vals)
255         if model_field:
256             obj.write(cr, uid, res_obj.id, {model_field: [(4, att_id)]})
257         
258         if datas.get('send_mail'):
259             att_obj._send_mail(cr, uid, [att_id], mail_to, \
260                    email_from=tools.config.get('email_from', False))
261                 
262         return {}
263
264
265     def onchange_partner_id(self, cr, uid, ids, partner_id, *args, **argv):
266         if not partner_id:
267             return {'value': {'contact_ids': []}}
268         cr.execute('select id from res_partner_address \
269                          where partner_id=%s' % (partner_id))
270         contacts = map(lambda x: x[0], cr.fetchall())
271         if not contacts:
272             raise osv.except_osv(_('Error!'), \
273                                 ("Partner does not have any Contacts"))
274
275         return {'value': {'contact_ids': contacts}}
276
277 invite_attendee_wizard()
278
279 class calendar_attendee(osv.osv):
280     _name = 'calendar.attendee'
281     _description = 'Attendee information'
282     _rec_name = 'cutype'
283
284     __attribute__ = {}
285
286     def _get_address(self, name=None, email=None):
287         if name and email:
288             name += ':'
289         return (name or '') + (email and ('MAILTO:' + email) or '')
290
291     def _compute_data(self, cr, uid, ids, name, arg, context):
292         name = name[0]
293         result = {}
294
295         for attdata in self.browse(cr, uid, ids, context=context):
296             id = attdata.id
297             result[id] = {}
298             if name == 'sent_by':
299                 if not attdata.sent_by_uid:
300                     result[id][name] = ''
301                     continue
302                 else:
303                     result[id][name] =  self._get_address(attdata.sent_by_uid.name, \
304                                         attdata.sent_by_uid.address_id.email)
305             if name == 'cn':
306                 if attdata.user_id:
307                     result[id][name] = self._get_address(attdata.user_id.name, attdata.email)
308                 elif attdata.partner_address_id:
309                     result[id][name] = self._get_address(attdata.partner_id.name, attdata.email)
310                 else:
311                     result[id][name] = self._get_address(None, attdata.email)
312             if name == 'delegated_to':
313                 todata = []
314                 for parent in attdata.parent_ids:
315                     todata.append('MAILTO:' + parent.email)
316                 result[id][name] = ', '.join(todata)
317             if name == 'delegated_from':
318                 fromdata = []
319                 for child in attdata.child_ids:
320                     fromdata.append('MAILTO:' + child.email)
321                 result[id][name] = ', '.join(fromdata)
322             if name == 'event_date':
323                 if attdata.ref:
324                     model, res_id = tuple(attdata.ref.split(','))
325                     model_obj = self.pool.get(model)
326                     obj = model_obj.read(cr, uid, res_id, ['date'])[0]
327                     result[id][name] = obj.get('date')
328                 else:
329                     result[id][name] = False
330             if name == 'event_end_date':
331                 if attdata.ref:
332                     model, res_id = tuple(attdata.ref.split(','))
333                     model_obj = self.pool.get(model)
334                     obj = model_obj.read(cr, uid, res_id, ['date_deadline'])[0]
335                     result[id][name] = obj.get('date_deadline')
336                 else:
337                     result[id][name] = False
338             if name == 'sent_by_uid':
339                 if attdata.ref:
340                     model, res_id = tuple(attdata.ref.split(','))
341                     model_obj = self.pool.get(model)
342                     obj = model_obj.read(cr, uid, res_id, ['user_id'])[0]
343                     result[id][name] = obj.get('user_id')
344                 else:
345                     result[id][name] = uid
346             if name == 'language':
347                 user_obj = self.pool.get('res.users')
348                 lang = user_obj.read(cr, uid, uid, ['context_lang'])['context_lang']
349                 result[id][name] = lang.replace('_', '-')
350         return result
351
352     def _links_get(self, cr, uid, context={}):
353         obj = self.pool.get('res.request.link')
354         ids = obj.search(cr, uid, [])
355         res = obj.read(cr, uid, ids, ['object', 'name'], context)
356         return [(r['object'], r['name']) for r in res]
357
358     def _lang_get(self, cr, uid, context={}):
359         obj = self.pool.get('res.lang')
360         ids = obj.search(cr, uid, [])
361         res = obj.read(cr, uid, ids, ['code', 'name'], context)
362         res = [((r['code']).replace('_', '-'), r['name']) for r in res]
363         return res
364
365     _columns = {
366         'cutype': fields.selection([('individual', 'Individual'), \
367                     ('group', 'Group'), ('resource', 'Resource'), \
368                     ('room', 'Room'), ('unknown', '') ], \
369                     'Invite Type', help="Specify the type of Invitation"), 
370         'member': fields.char('Member', size=124, 
371                     help="Indicate the groups that the attendee belongs to"), 
372         'role': fields.selection([('req-participant', 'Participation required'), \
373                     ('chair', 'Chair Person'), \
374                     ('opt-participant', 'Optional Participation'), \
375                     ('non-participant', 'For information Purpose')], 'Role', \
376                     help='Participation role for the calendar user'), 
377         'state': fields.selection([('tentative', 'Tentative'), 
378                         ('needs-action', 'Needs Action'), 
379                         ('accepted', 'Accepted'), 
380                         ('declined', 'Declined'), 
381                         ('delegated', 'Delegated')], 'State', readonly=True, 
382                         help="Status of the attendee's participation"), 
383         'rsvp':  fields.boolean('Required Reply?', 
384                     help="Indicats whether the favor of a reply is requested"), 
385         'delegated_to': fields.function(_compute_data, method=True, \
386                 string='Delegated To', type="char", size=124, store=True, \
387                 multi='delegated_to', help="The users that the original \
388 request was delegated to"),         
389         'delegated_from': fields.function(_compute_data, method=True, string=\
390             'Delegated From', type="char", store=True, size=124, multi='delegated_from'),        
391         'parent_ids': fields.many2many('calendar.attendee', 'calendar_attendee_parent_rel', 'attendee_id', 'parent_id', 'Delegrated From'),
392         'child_ids': fields.many2many('calendar.attendee', 'calendar_attendee_child_rel', 'attendee_id', 'child_id', 'Delegrated To'),  
393         'sent_by': fields.function(_compute_data, method=True, string='Sent By', type="char", multi='sent_by', store=True, size=124, help="Specify the user that is acting on behalf of the calendar user"), 
394         'sent_by_uid': fields.function(_compute_data, method=True, string='Sent By User', type="many2one", relation="res.users", multi='sent_by_uid'), 
395         'cn': fields.function(_compute_data, method=True, string='Common name', type="char", size=124, multi='cn', store=True), 
396         'dir': fields.char('URI Reference', size=124, help="Reference to the URI that points to the directory information corresponding to the attendee."), 
397         'language':  fields.function(_compute_data, method=True, string='Language', type="selection", selection=_lang_get, multi='language', store=True, help="To specify the language for text values in a property or property parameter."), 
398         'user_id': fields.many2one('res.users', 'User'), 
399         'partner_address_id': fields.many2one('res.partner.address', 'Contact'), 
400         'partner_id': fields.related('partner_address_id', 'partner_id', type='many2one', relation='res.partner', string='Partner', help="Partner related to contact"), 
401         'email': fields.char('Email', size=124, required=True, help="Email of Invited Person"), 
402         'event_date': fields.function(_compute_data, method=True, string='Event Date', type="datetime", multi='event_date'), 
403         'event_end_date': fields.function(_compute_data, method=True, string='Event End Date', type="datetime", multi='event_end_date'), 
404         'ref': fields.reference('Event Ref', selection=_links_get, size=128), 
405         'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"), 
406      }
407     _defaults = {
408         'state':  lambda *x: 'needs-action', 
409     }
410     
411     response_re = re.compile("Are you coming\?.*\n*.*(YES|NO|MAYBE).*", re.UNICODE)
412     
413     def msg_new(self, cr, uid, msg):        
414         return False
415         
416     def msg_act_get(self, msg):
417         mailgate_obj = self.pool.get('mail.gateway')
418         body = mailgate_obj.msg_body_get(msg)
419         actions = {}
420         res = self.response_re.findall(body['body'])
421         if res:
422                 actions['state'] = res[0]
423         return actions
424
425     def msg_update(self, cr, uid, ids, msg, data={}, default_act='None'):
426         msg_actions = self.msg_act_get(msg)
427         if msg_actions.get('state'):
428             if msg_actions['state'] in ['YES', 'NO', 'MAYBE']:
429                 mapping = {'YES': 'accepted', 'NO': 'declined', 'MAYBE': 'tentative'}
430                 status = mapping[msg_actions['state']]
431                 print 'Got response for invitation id: %s as %s'  % (ids, status)
432                 self.write(cr, uid, ids, {'state': status})
433         return True
434
435     def _send_mail(self, cr, uid, ids, mail_to, email_from=tools.config.get('email_from', False), context={}):
436         company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.name
437         for att in self.browse(cr, uid, ids, context=context):
438             sign = att.sent_by_uid and att.sent_by_uid.signature or ''
439             sign = '<br>'.join(sign and sign.split('\n') or [])
440             model, res_id = tuple(att.ref.split(','))            
441             res_obj = self.pool.get(model).browse(cr, uid, res_id)
442             if res_obj and len(res_obj):
443                 res_obj = res_obj[0]
444             sub = '[%s Invitation][%d] %s'  % (company, att.id, res_obj.name)
445             att_infos = []
446             other_invitaion_ids = self.search(cr, uid, [('ref','=',att.ref)])
447             for att2 in self.browse(cr, uid, other_invitaion_ids):
448                 att_infos.append(((att2.user_id and att2.user_id.name) or \
449                              (att2.partner_id and att2.partner_id.name) or \
450                                 att2.email) +  ' - Status: ' + att2.state.title())
451             body_vals = {'name': res_obj.name, 
452                         'start_date': res_obj.date, 
453                         'end_date': res_obj.date_deadline or False, 
454                         'description': res_obj.description or '-', 
455                         'location': res_obj.location or '-', 
456                         'attendees': '<br>'.join(att_infos), 
457                         'user': res_obj.user_id and res_obj.user_id.name or 'OpenERP User', 
458                         'sign': sign, 
459                         'company': company
460             }
461             body = html_invitation % body_vals
462             if mail_to and email_from:
463                 tools.email_send(
464                         email_from, 
465                         mail_to, 
466                         sub, 
467                         body, 
468                         subtype='html', 
469                         reply_to=email_from
470                     ) 
471             return True
472     def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
473         if not user_id:
474             return {'value': {'email': ''}}
475         usr_obj = self.pool.get('res.users')
476         user = usr_obj.browse(cr, uid, user_id, *args)
477         return {'value': {'email': user.address_id.email, 'availability':user.availability}}
478
479     def do_tentative(self, cr, uid, ids, context=None, *args):
480         self.write(cr, uid, ids, {'state': 'tentative'}, context)
481
482     def do_accept(self, cr, uid, ids, context=None, *args):
483         self.write(cr, uid, ids, {'state': 'accepted'}, context)
484
485     def do_decline(self, cr, uid, ids, context=None, *args):
486         self.write(cr, uid, ids, {'state': 'declined'}, context)
487
488     def create(self, cr, uid, vals, context={}):
489         if not vals.get("email") and vals.get("cn"):
490             cnval = vals.get("cn").split(':')
491             email =  filter(lambda x:x.__contains__('@'), cnval)
492             vals['email'] = email[0]
493             vals['cn'] = vals.get("cn")
494         res = super(calendar_attendee, self).create(cr, uid, vals, context)
495         return res
496     
497 calendar_attendee()
498
499 class res_alarm(osv.osv):
500     _name = 'res.alarm'
501     _description = 'Basic Alarm Information'
502     _columns = {
503         'name':fields.char('Name', size=256, required=True), 
504         'trigger_occurs': fields.selection([('before', 'Before'), ('after', 'After')], \
505                                         'Triggers', required=True), 
506         'trigger_interval': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), \
507                 ('days', 'Days')], 'Interval', required=True), 
508         'trigger_duration':  fields.integer('Duration', required=True), 
509         'trigger_related':  fields.selection([('start', 'The event starts'), ('end', \
510                                        'The event ends')], 'Related to', required=True), 
511         'duration': fields.integer('Duration', help="""Duration' and 'Repeat' \
512 are both optional, but if one occurs, so MUST the other"""), 
513         'repeat': fields.integer('Repeat'), 
514         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the event alarm information without removing it."), 
515
516
517     }
518     _defaults = {
519         'trigger_interval':  lambda *x: 'minutes', 
520         'trigger_duration': lambda *x: 5, 
521         'trigger_occurs': lambda *x: 'before', 
522         'trigger_related': lambda *x: 'start', 
523         'active': lambda *x: 1, 
524     }
525
526     def do_alarm_create(self, cr, uid, ids, model, date, context={}):
527         alarm_obj = self.pool.get('calendar.alarm')
528         ir_obj = self.pool.get('ir.model')
529         model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
530         
531         model_obj = self.pool.get(model)
532         for data in model_obj.browse(cr, uid, ids):
533             basic_alarm = data.alarm_id
534             if not context.get('alarm_id'):
535                 self.do_alarm_unlink(cr, uid, [data.id], model)
536                 return True
537             self.do_alarm_unlink(cr, uid, [data.id], model)
538             if basic_alarm:
539                 vals = {
540                     'action': 'display', 
541                     'description': data.description, 
542                     'name': data.name, 
543                     'attendee_ids': [(6, 0, map(lambda x:x.id, data.attendee_ids))], 
544                     'trigger_related': basic_alarm.trigger_related, 
545                     'trigger_duration': basic_alarm.trigger_duration, 
546                     'trigger_occurs': basic_alarm.trigger_occurs, 
547                     'trigger_interval': basic_alarm.trigger_interval, 
548                     'duration': basic_alarm.duration, 
549                     'repeat': basic_alarm.repeat, 
550                     'state': 'run', 
551                     'event_date': data[date], 
552                     'res_id': data.id, 
553                     'model_id': model_id, 
554                     'user_id': uid
555                  }
556                 alarm_id = alarm_obj.create(cr, uid, vals)
557                 cr.execute('Update %s set base_calendar_alarm_id=%s, alarm_id=%s \
558                                         where id=%s' % (model_obj._table, \
559                                         alarm_id, basic_alarm.id, data.id))
560         cr.commit()
561         return True
562
563     def do_alarm_unlink(self, cr, uid, ids, model, context={}):
564         alarm_obj = self.pool.get('calendar.alarm')
565         ir_obj = self.pool.get('ir.model')
566         model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
567         model_obj = self.pool.get(model)
568         for datas in model_obj.browse(cr, uid, ids):
569             alarm_ids = alarm_obj.search(cr, uid, [('model_id', '=', model_id), ('res_id', '=', datas.id)])
570             if alarm_ids:
571                 alarm_obj.unlink(cr, uid, alarm_ids)
572                 cr.execute('Update %s set base_calendar_alarm_id=NULL, alarm_id=NULL\
573                              where id=%s' % (model_obj._table, datas.id))
574         cr.commit()
575         return True
576
577 res_alarm()
578
579 class calendar_alarm(osv.osv):
580     _name = 'calendar.alarm'
581     _description = 'Event alarm information'
582     _inherit = 'res.alarm'
583     __attribute__ = {}
584
585     _columns = {
586             'alarm_id': fields.many2one('res.alarm', 'Basic Alarm', ondelete='cascade'), 
587             'name': fields.char('Summary', size=124, help="""Contains the text to be used as the message subject for email
588 or contains the text to be used for display"""), 
589             'action': fields.selection([('audio', 'Audio'), ('display', 'Display'), \
590                     ('procedure', 'Procedure'), ('email', 'Email') ], 'Action', \
591                     required=True, help="Defines the action to be invoked when an alarm is triggered"), 
592             'description': fields.text('Description', help='Provides a more complete description of the calendar component, than that provided by the "SUMMARY" property'), 
593             'attendee_ids': fields.many2many('calendar.attendee', 'alarm_attendee_rel', \
594                                           'alarm_id', 'attendee_id', 'Attendees', readonly=True), 
595             'attach': fields.binary('Attachment', help="""* Points to a sound resource, which is rendered when the alarm is triggered for audio,
596 * File which is intended to be sent as message attachments for email,
597 * Points to a procedure resource, which is invoked when the alarm is triggered for procedure."""), 
598             'res_id': fields.integer('Resource ID'), 
599             'model_id': fields.many2one('ir.model', 'Model'), 
600             'user_id': fields.many2one('res.users', 'Owner'), 
601             'event_date': fields.datetime('Event Date'), 
602             'event_end_date': fields.datetime('Event End Date'), 
603             'trigger_date': fields.datetime('Trigger Date', readonly="True"), 
604             'state':fields.selection([
605                         ('draft', 'Draft'), 
606                         ('run', 'Run'), 
607                         ('stop', 'Stop'), 
608                         ('done', 'Done'), 
609                     ], 'State', select=True, readonly=True), 
610      }
611
612     _defaults = {
613         'action':  lambda *x: 'email', 
614         'state': lambda *x: 'run', 
615      }
616
617     def create(self, cr, uid, vals, context={}):
618         event_date = vals.get('event_date', False)
619         if event_date:
620             dtstart = datetime.strptime(vals['event_date'], "%Y-%m-%d %H:%M:%S")
621             if vals['trigger_interval'] == 'days':
622                 delta = timedelta(days=vals['trigger_duration'])
623             if vals['trigger_interval'] == 'hours':
624                 delta = timedelta(hours=vals['trigger_duration'])
625             if vals['trigger_interval'] == 'minutes':
626                 delta = timedelta(minutes=vals['trigger_duration'])
627             trigger_date =  dtstart + (vals['trigger_occurs'] == 'after' and delta or -delta)
628             vals['trigger_date'] = trigger_date
629         res = super(calendar_alarm, self).create(cr, uid, vals, context)
630         return res
631
632     def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False,\
633                        context=None):
634         if not context:
635             context = {}
636         current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
637         cr.execute("select alarm.id as id \
638                     from calendar_alarm alarm \
639                     where alarm.state = %s and alarm.trigger_date <= %s", ('run', current_datetime))
640         res = cr.dictfetchall()
641         alarm_ids = map(lambda x: x['id'], res)
642         attendee_obj = self.pool.get('calendar.attendee')
643         request_obj = self.pool.get('res.request')
644         mail_to = []
645         for alarm in self.browse(cr, uid, alarm_ids):
646             if alarm.action == 'display':
647                 value = {
648                    'name': alarm.name, 
649                    'act_from': alarm.user_id.id, 
650                    'act_to': alarm.user_id.id, 
651                    'body': alarm.description, 
652                    'trigger_date': alarm.trigger_date, 
653                    'ref_doc1':  '%s,%s'  % (alarm.model_id.model, alarm.res_id)
654                 }
655                 request_id = request_obj.create(cr, uid, value)
656                 request_ids = [request_id]
657                 for attendee in alarm.attendee_ids:
658                     if attendee.user_id:
659                         value['act_to'] = attendee.user_id.id
660                         request_id = request_obj.create(cr, uid, value)
661                         request_ids.append(request_id)
662                 request_obj.request_send(cr, uid, request_ids)
663
664             if alarm.action == 'email':
665                 sub = '[Openobject Remainder] %s'  % (alarm.name)
666                 body = """
667                 Name: %s
668                 Date: %s
669                 Description: %s
670
671                 From:
672                       %s
673                       %s
674
675                 """  % (alarm.name, alarm.trigger_date, alarm.description, \
676                     alarm.user_id.name, alarm.user_id.signature)
677                 mail_to = [alarm.user_id.address_id.email]
678                 for att in alarm.attendee_ids:
679                     mail_to.append(att.user_id.address_id.email)
680                 if mail_to:
681                     tools.email_send(
682                         tools.config.get('email_from', False), 
683                         mail_to, 
684                         sub, 
685                         body
686                     )
687             self.write(cr, uid, [alarm.id], {'state':'done'})
688         return True
689
690 calendar_alarm()
691
692
693 class calendar_event(osv.osv):
694     _name = "calendar.event"
695     _description = "Calendar Event"
696     __attribute__ = {}
697     
698     def _tz_get(self, cr, uid, context={}):
699         return [(x.lower(), x) for x in pytz.all_timezones]
700
701     def onchange_rrule_type(self, cr, uid, ids, rtype, *args, **argv):
702         if rtype == 'none' or not rtype:
703             return {'value': {'rrule': ''}}
704         if rtype == 'custom':
705             return {}
706         rrule = self.pool.get('calendar.custom.rrule')
707         rrulestr = rrule.compute_rule_string(cr, uid, {'freq': rtype.upper(), \
708                                  'interval': 1})
709         return {'value': {'rrule': rrulestr}}
710     
711     def _get_duration(self, cr, uid, ids, name, arg, context):
712         res = {}
713         for event in self.browse(cr, uid, ids, context=context):
714             start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
715             res[event.id] = 0
716             if event.date_deadline:
717                 end = datetime.strptime(event.date_deadline[:19], "%Y-%m-%d %H:%M:%S")
718                 diff = end - start
719                 duration =  float(diff.days)* 24 + (float(diff.seconds) / 3600)
720                 res[event.id] = round(duration, 2)
721         return res
722
723     def _set_duration(self, cr, uid, id, name, value, arg, context):
724         event = self.browse(cr, uid, id, context=context)
725         start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
726         end = start + timedelta(hours=value)
727         cr.execute("UPDATE %s set date_deadline='%s' \
728                         where id=%s"% (self._table, end.strftime("%Y-%m-%d %H:%M:%S"), id))
729         return True
730     
731     _columns = {
732         'id': fields.integer('ID'), 
733         'sequence': fields.integer('Sequence'), 
734         'name': fields.char('Description', size=64, required=True), 
735         'date': fields.datetime('Date'), 
736         'date_deadline': fields.datetime('Deadline'), 
737         'create_date': fields.datetime('Created', readonly=True), 
738         'duration': fields.function(_get_duration, method=True, \
739                                     fnct_inv=_set_duration, string='Duration'), 
740         'description': fields.text('Your action'), 
741         'class': fields.selection([('public', 'Public'), ('private', 'Private'), \
742                  ('confidential', 'Confidential')], 'Mark as'), 
743         'location': fields.char('Location', size=264, help="Location of Event"), 
744         'show_as': fields.selection([('free', 'Free'), \
745                                   ('busy', 'Busy')], 
746                                    'Show as'), 
747         'base_calendar_url': fields.char('Caldav URL', size=264), 
748         'exdate': fields.text('Exception Date/Times', help="This property \
749 defines the list of date/time exceptions for arecurring calendar component."), 
750         'exrule': fields.char('Exception Rule', size=352, help="defines a \
751 rule or repeating pattern for anexception to a recurrence set"), 
752         'rrule': fields.char('Recurrent Rule', size=124), 
753         'rrule_type': fields.selection([('none', ''), ('daily', 'Daily'), \
754                             ('weekly', 'Weekly'), ('monthly', 'Monthly'), \
755                             ('yearly', 'Yearly'), ('custom', 'Custom')], 'Recurrency'), 
756         'alarm_id': fields.many2one('res.alarm', 'Alarm'), 
757         'base_calendar_alarm_id': fields.many2one('calendar.alarm', 'Alarm'), 
758         'recurrent_uid': fields.integer('Recurrent ID'), 
759         'recurrent_id': fields.datetime('Recurrent ID date'), 
760         'vtimezone': fields.selection(_tz_get, 'Timezone', size=64), 
761         'user_id': fields.many2one('res.users', 'Responsible'),        
762     }
763     
764     _defaults = {
765          'class': lambda *a: 'public', 
766          'show_as': lambda *a: 'busy', 
767     }
768     
769     def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
770         if not user_id:
771             return {'value': {'vtimezone': False}}
772         value = {'vtimezone': False}
773         cr.execute('select context_tz from res_users where id=%s' % (user_id))
774         timezone = cr.fetchone()[0]
775         if timezone:
776             value.update({'vtimezone': timezone.lower()})
777         return {'value': value}    
778         
779     def modify_this(self, cr, uid, ids, defaults, context=None, *args):
780         datas = self.read(cr, uid, ids[0], context=context)
781         date = datas.get('date')
782         defaults.update({
783                'recurrent_uid': base_calendar_id2real_id(datas['id']), 
784                'recurrent_id': defaults.get('date'), 
785                'rrule_type': 'none', 
786                'rrule': ''
787                     })
788         new_id = self.copy(cr, uid, ids[0], default=defaults, context=context)
789         return new_id
790
791     def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100):
792         if not limit:
793             limit = 100
794         if isinstance(select, (str, int, long)):
795             ids = [select]
796         else:
797             ids = select
798         result = []
799         if ids and (base_start_date or base_until_date):
800             cr.execute("select m.id, m.rrule, m.date, m.date_deadline, \
801                             m.exdate  from "  + self._table + \
802                             " m where m.id in ("\
803                             + ','.join(map(lambda x: str(x), ids))+")")
804
805             count = 0
806             for data in cr.dictfetchall():
807                 start_date = base_start_date and datetime.strptime(base_start_date, "%Y-%m-%d") or False
808                 until_date = base_until_date and datetime.strptime(base_until_date, "%Y-%m-%d") or False
809                 if count > limit:
810                     break
811                 event_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
812                 if start_date and start_date <= event_date:
813                     start_date = event_date
814                 if not data['rrule']:
815                     if start_date and (event_date < start_date):
816                         continue
817                     if until_date and (event_date > until_date):
818                         continue
819                     idval = real_id2base_calendar_id(data['id'], data['date'])
820                     result.append(idval)
821                     count += 1
822                 else:
823                     exdate = data['exdate'] and data['exdate'].split(',') or []                    
824                     rrule_str = data['rrule']
825                     new_rrule_str = []
826                     rrule_until_date = False
827                     is_until = False
828                     for rule in rrule_str.split(';'):
829                         name, value = rule.split('=')
830                         if name == "UNTIL":
831                             is_until = True
832                             value = parser.parse(value)
833                             rrule_until_date = parser.parse(value.strftime("%Y-%m-%d"))
834                             if until_date and until_date >= rrule_until_date:
835                                 until_date = rrule_until_date
836                             if until_date:
837                                 value = until_date.strftime("%Y%m%d%H%M%S")
838                         new_rule = '%s=%s' % (name, value)
839                         new_rrule_str.append(new_rule)
840                     if not is_until and until_date:
841                         value = until_date.strftime("%Y%m%d%H%M%S")
842                         name = "UNTIL"
843                         new_rule = '%s=%s' % (name, value)
844                         new_rrule_str.append(new_rule)
845                     new_rrule_str = ';'.join(new_rrule_str)
846                     start_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
847                     rdates = get_recurrent_dates(str(new_rrule_str), exdate, start_date)
848                     for rdate in rdates:
849                         r_date = datetime.strptime(rdate, "%Y-%m-%d %H:%M:%S")
850                         if start_date and r_date < start_date:
851                             continue
852                         if until_date and r_date > until_date:
853                             continue
854                         idval = real_id2base_calendar_id(data['id'], rdate)
855                         result.append(idval)
856                         count += 1
857         if result:
858             ids = result
859         if isinstance(select, (str, int, long)):
860             return ids and ids[0] or False
861         return ids
862
863     def search(self, cr, uid, args, offset=0, limit=100, order=None, 
864             context=None, count=False):
865         args_without_date = []
866         start_date = False
867         until_date = False
868         for arg in args:
869             if arg[0] not in ('date', unicode('date')):
870                 args_without_date.append(arg)
871             else:
872                 if arg[1] in ('>', '>='):
873                     start_date = arg[2]
874                 elif arg[1] in ('<', '<='):
875                     until_date = arg[2]
876         res = super(calendar_event, self).search(cr, uid, args_without_date, \
877                                  offset, limit, order, context, count)
878         return self.get_recurrent_ids(cr, uid, res, start_date, until_date, limit)
879
880
881     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
882         if not context:
883             context = {}
884         if isinstance(ids, (str, int, long)):
885             select = [ids]
886         else:
887             select = ids
888         new_ids = []
889         for id in select:
890             id = base_calendar_id2real_id(id)
891             if not id in new_ids:
892                 new_ids.append(id)
893         res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
894         if vals.has_key('alarm_id') or vals.has_key('base_calendar_alarm_id'):
895             alarm_obj = self.pool.get('res.alarm')
896             context.update({'alarm_id': vals.get('alarm_id')})
897             alarm_obj.do_alarm_create(cr, uid, new_ids, self._name, 'date', context=context)
898         return res
899
900     def browse(self, cr, uid, ids, context=None, list_class=None, fields_process={}):
901         if isinstance(ids, (str, int, long)):
902             select = [ids]
903         else:
904             select = ids
905         select = map(lambda x: base_calendar_id2real_id(x), select)
906         res = super(calendar_event, self).browse(cr, uid, select, context, list_class, fields_process)
907         if isinstance(ids, (str, int, long)):
908             return res and res[0] or False
909         return res
910
911     def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'):
912         if isinstance(ids, (str, int, long)):
913             select = [ids]
914         else:
915             select = ids
916         select = map(lambda x: (x, base_calendar_id2real_id(x)), select)
917         result = []
918         if fields and 'date' not in fields:
919             fields.append('date')
920         for base_calendar_id, real_id in select:
921             res = super(calendar_event, self).read(cr, uid, real_id, fields=fields, context=context, \
922                                               load=load)
923             ls = base_calendar_id2real_id(base_calendar_id, with_date=res.get('duration', 0))
924             if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
925                 res['date'] = ls[1]
926                 res['date_deadline'] = ls[2]
927             res['id'] = base_calendar_id
928
929             result.append(res)
930         if isinstance(ids, (str, int, long)):
931             return result and result[0] or False
932         return result
933
934     def copy(self, cr, uid, id, default=None, context={}):
935         res = super(calendar_event, self).copy(cr, uid, base_calendar_id2real_id(id), default, context)
936         alarm_obj = self.pool.get('res.alarm')
937         alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
938         return res
939
940     def unlink(self, cr, uid, ids, context=None):
941         res = False
942         for id in ids:
943             ls = base_calendar_id2real_id(id)
944             if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
945                 date_new = ls[1]
946                 for record in self.read(cr, uid, [base_calendar_id2real_id(id)], \
947                                             ['date', 'rrule', 'exdate']):
948                     if record['rrule']:
949                         exdate = (record['exdate'] and (record['exdate'] + ',')  or '') + ''.join((re.compile('\d')).findall(date_new)) + 'Z'
950                         if record['date'] == date_new:
951                             res = self.write(cr, uid, [base_calendar_id2real_id(id)], {'exdate': exdate})
952                     else:
953                         ids = map(lambda x: base_calendar_id2real_id(x), ids)
954                         res = super(calendar_event, self).unlink(cr, uid, base_calendar_id2real_id(ids))
955                         alarm_obj = self.pool.get('res.alarm')
956                         alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
957             else:
958                 ids = map(lambda x: base_calendar_id2real_id(x), ids)
959                 res = super(calendar_event, self).unlink(cr, uid, ids)
960                 alarm_obj = self.pool.get('res.alarm')
961                 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
962         return res
963
964     def create(self, cr, uid, vals, context={}):
965         res = super(calendar_event, self).create(cr, uid, vals, context)
966         alarm_obj = self.pool.get('res.alarm')
967         alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
968         return res
969
970 calendar_event()
971
972 class calendar_todo(osv.osv):
973     _name = "calendar.todo"
974     _inherit = "calendar.event"
975     _description = "Calendar Task"
976
977     def _get_date(self, cr, uid, ids, name, arg, context):
978         res = {}
979         for event in self.browse(cr, uid, ids, context=context):
980             res[event.id] = event.date_start
981         return res
982
983     def _set_date(self, cr, uid, id, name, value, arg, context):
984         event = self.browse(cr, uid, id, context=context)
985         cr.execute("UPDATE %s set date_start='%s' where id=%s"  \
986                            % (self._table, value, id))
987         return True
988
989     _columns = {
990         'date': fields.function(_get_date, method=True, fnct_inv=_set_date, \
991                                         string='Duration', store=True, type='datetime'), 
992         'duration': fields.integer('Duration'), 
993     }
994     
995     __attribute__ = {}
996     
997     
998 calendar_todo()
999  
1000 class ir_attachment(osv.osv):
1001     _name = 'ir.attachment'
1002     _inherit = 'ir.attachment'
1003
1004     def search_count(self, cr, user, args, context=None):
1005         args1 = []
1006         for arg in args:
1007             args1.append(map(lambda x:str(x).split('-')[0], arg))
1008         return super(ir_attachment, self).search_count(cr, user, args1, context)
1009
1010     def search(self, cr, uid, args, offset=0, limit=None, order=None, 
1011             context=None, count=False):
1012         new_args = args
1013         for i, arg in enumerate(new_args):
1014             if arg[0] == 'res_id':
1015                 new_args[i] = (arg[0], arg[1], base_calendar_id2real_id(arg[2]))
1016         return super(ir_attachment, self).search(cr, uid, new_args, offset=offset, 
1017                             limit=limit, order=order, 
1018                             context=context, count=False)
1019 ir_attachment()
1020
1021 class ir_values(osv.osv):
1022     _inherit = 'ir.values'
1023
1024     def set(self, cr, uid, key, key2, name, models, value, replace=True, \
1025             isobject=False, meta=False, preserve_user=False, company=False):
1026         new_model = []
1027         for data in models:
1028             if type(data) in (list, tuple):
1029                 new_model.append((data[0], base_calendar_id2real_id(data[1])))
1030             else:
1031                 new_model.append(data)
1032         return super(ir_values, self).set(cr, uid, key, key2, name, new_model,\
1033                     value, replace, isobject, meta, preserve_user, company)
1034
1035     def get(self, cr, uid, key, key2, models, meta=False, context={}, \
1036              res_id_req=False, without_user=True, key2_req=True):
1037         new_model = []
1038         for data in models:
1039             if type(data) in (list, tuple):
1040                 new_model.append((data[0], base_calendar_id2real_id(data[1])))
1041             else:
1042                 new_model.append(data)
1043         return super(ir_values, self).get(cr, uid, key, key2, new_model, \
1044                          meta, context, res_id_req, without_user, key2_req)
1045
1046 ir_values()
1047
1048 class ir_model(osv.osv):
1049
1050     _inherit = 'ir.model'
1051
1052     def read(self, cr, uid, ids, fields=None, context={}, 
1053             load='_classic_read'):
1054         data = super(ir_model, self).read(cr, uid, ids, fields=fields, \
1055                         context=context, load=load)
1056         if data:
1057             for val in data:
1058                 val['id'] = base_calendar_id2real_id(val['id'])
1059         return data
1060
1061 ir_model()
1062
1063 class virtual_report_spool(web_services.report_spool):
1064
1065     def exp_report(self, db, uid, object, ids, datas=None, context=None):
1066         if object == 'printscreen.list':
1067             return super(virtual_report_spool, self).exp_report(db, uid, \
1068                             object, ids, datas, context)
1069         new_ids = []
1070         for id in ids:
1071             new_ids.append(base_calendar_id2real_id(id))
1072         datas['id'] = base_calendar_id2real_id(datas['id'])        
1073         return super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
1074
1075 virtual_report_spool()
1076
1077 class calendar_custom_rrule(osv.osv):
1078     _name = "calendar.custom.rrule"
1079     _description = "Custom Recurrency Rule"
1080
1081     _columns = {
1082         'freq': fields.selection([('None', 'No Repeat'), \
1083                             ('secondly', 'Secondly'), \
1084                             ('minutely', 'Minutely'), \
1085                             ('hourly', 'Hourly'), \
1086                             ('daily', 'Daily'), \
1087                             ('weekly', 'Weekly'), \
1088                             ('monthly', 'Monthly'), \
1089                             ('yearly', 'Yearly')], 'Frequency', required=True), 
1090         'interval': fields.integer('Interval'), 
1091         'count': fields.integer('Count'), 
1092         'mo': fields.boolean('Mon'), 
1093         'tu': fields.boolean('Tue'), 
1094         'we': fields.boolean('Wed'), 
1095         'th': fields.boolean('Thu'), 
1096         'fr': fields.boolean('Fri'), 
1097         'sa': fields.boolean('Sat'), 
1098         'su': fields.boolean('Sun'), 
1099         'select1': fields.selection([('date', 'Date of month'), \
1100                             ('day', 'Day of month')], 'Option'), 
1101         'day': fields.integer('Date of month'), 
1102         'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), \
1103                                    ('WE', 'Wednesday'), ('TH', 'Thursday'), \
1104                                    ('FR', 'Friday'), ('SA', 'Saturday'), \
1105                                    ('SU', 'Sunday')], 'Weekday'), 
1106         'byday': fields.selection([('1', 'First'), ('2', 'Second'), \
1107                                    ('3', 'Third'), ('4', 'Fourth'), \
1108                                    ('5', 'Fifth'), ('-1', 'Last')], 'By day'), 
1109         'month_list': fields.selection(months.items(), 'Month'), 
1110         'end_date': fields.date('Repeat Until')
1111     }
1112
1113     _defaults = {
1114                  'freq':  lambda *x: 'daily', 
1115                  'select1':  lambda *x: 'date', 
1116                  'interval':  lambda *x: 1, 
1117                  }
1118
1119     def compute_rule_string(self, cr, uid, datas, context=None, *args):
1120         weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
1121         weekstring = ''
1122         monthstring = ''
1123         yearstring = ''
1124
1125 #    logic for computing rrule string
1126
1127         freq = datas.get('freq')
1128         if freq == 'None':
1129             obj.write(cr, uid, [res_obj.id], {'rrule': ''})
1130             return {}
1131
1132         if freq == 'weekly':
1133             byday = map(lambda x: x.upper(), filter(lambda x: datas.get(x) and x in weekdays, datas))
1134             if byday:
1135                 weekstring = ';BYDAY=' + ','.join(byday)
1136
1137         elif freq == 'monthly':
1138             if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
1139                 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
1140             if datas.get('select1')=='day':
1141                 monthstring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
1142             elif datas.get('select1')=='date':
1143                 monthstring = ';BYMONTHDAY=' + str(datas.get('day'))
1144
1145         elif freq == 'yearly':
1146             if datas.get('select1')=='date'  and (datas.get('day') < 1 or datas.get('day') > 31):
1147                 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
1148             bymonth = ';BYMONTH=' + str(datas.get('month_list'))
1149             if datas.get('select1')=='day':
1150                 bystring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
1151             elif datas.get('select1')=='date':
1152                 bystring = ';BYMONTHDAY=' + str(datas.get('day'))
1153             yearstring = bymonth + bystring
1154
1155         if datas.get('end_date'):
1156             datas['end_date'] = ''.join((re.compile('\d')).findall(datas.get('end_date'))) + '235959Z'
1157         enddate = (datas.get('count') and (';COUNT=' +  str(datas.get('count'))) or '') +\
1158                              ((datas.get('end_date') and (';UNTIL=' + datas.get('end_date'))) or '')
1159
1160         rrule_string = 'FREQ=' + freq.upper() +  weekstring + ';INTERVAL=' + \
1161                 str(datas.get('interval')) + enddate + monthstring + yearstring
1162
1163 #        End logic
1164         return rrule_string
1165
1166     def do_add(self, cr, uid, ids, context={}):
1167         datas = self.read(cr, uid, ids)[0]
1168         if datas.get('interval') <= 0:
1169             raise osv.except_osv(_('Error!'), ("Please select proper Interval"))
1170
1171
1172         if not context or not context.get('model'):
1173             return {}
1174         else:
1175             model = context.get('model')
1176         obj = self.pool.get(model)
1177         res_obj = obj.browse(cr, uid, context['active_id'])
1178
1179         rrule_string = self.compute_rule_string(cr, uid, datas)
1180         obj.write(cr, uid, [res_obj.id], {'rrule': rrule_string})
1181         return {}
1182
1183 calendar_custom_rrule()
1184
1185 class res_users(osv.osv):
1186     _inherit = 'res.users'
1187
1188     def _get_user_avail(self, cr, uid, ids, context=None):
1189         current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
1190         res = {}
1191         attendee_obj = self.pool.get('calendar.attendee')
1192         attendee_ids = attendee_obj.search(cr, uid, [
1193                     ('event_date', '<=', current_datetime), ('event_end_date', '<=', current_datetime), 
1194                     ('state', '=', 'accepted'), ('user_id', 'in', ids)
1195                     ])
1196
1197         result = cr.dictfetchall()
1198         for attendee_data in attendee_obj.read(cr, uid, attendee_ids, ['user_id']):
1199             user_id = attendee_data['user_id']
1200             status = 'busy'
1201             res.update({user_id:status})
1202
1203         #TOCHECK: Delegrated Event        
1204         for user_id in ids:
1205             if user_id not in res:
1206                 res[user_id] = 'free'
1207
1208         return res
1209
1210     def _get_user_avail_fun(self, cr, uid, ids, name, args, context=None):
1211         return self._get_user_avail(cr, uid, ids, context=context)
1212
1213     _columns = {
1214             'availability': fields.function(_get_user_avail_fun, type='selection', \
1215                     selection=[('free', 'Free'), ('busy', 'Busy')], \
1216                     string='Free/Busy', method=True), 
1217     }
1218 res_users()
1219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: