1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
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 _
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"}
39 def get_recurrent_dates(rrulestring, exdate, startdate=None):
41 val = parser.parse(''.join((re.compile('\d')).findall(date)))
44 startdate = datetime.now()
45 rset1 = rrule.rrulestr(rrulestring, dtstart=startdate, forceset=True)
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())
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('-')
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"))
65 return base_calendar_id and int(base_calendar_id) or base_calendar_id
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)
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]
84 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
85 <title>%(name)s</title>
88 <table border="0" cellspacing="10" cellpadding="0" width="100%%"
89 style="font-family: Arial, Sans-serif; font-size: 14">
91 <td width="100%%">Hello,</td>
94 <td width="100%%">You are invited for <i>%(company)s</i> Event.</td>
97 <td width="100%%">Below are the details of event:</td>
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">
110 <table cellpadding="8" cellspacing="0" border="0"
111 style="font-size: 14" summary="Eventdetails" bgcolor="f6f6f6"
115 <div><b>Start Date</b></div>
118 <td>%(start_date)s</td>
120 <div><b>End Date</b></div>
123 <td width="25%%">%(end_date)s</td>
126 <td><b>Description</b></td>
128 <td colspan="3">%(description)s</td>
132 <div><b>Location</b></div>
135 <td colspan="3">%(location)s</td>
139 <div><b>Event Attendees</b></div>
144 <div>%(attendees)s</div>
149 <td><b>Are you coming?</b></td>
163 <table border="0" cellspacing="10" cellpadding="0" width="100%%"
164 style="font-family: Arial, Sans-serif; font-size: 14">
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>
171 <td width="100%%">From:</td>
174 <td width="100%%">%(user)s</td>
177 <td width="100%%">-<font color="a7a7a7">-------------------------</font></td>
180 <td width="100%%"> <font color="a7a7a7">%(sign)s</font></td>
187 class invite_attendee_wizard(osv.osv_memory):
188 _name = "base_calendar.invite.attendee"
189 _description = "Invite Attendees"
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')
206 'type': lambda *x: 'internal'
209 def do_invite(self, cr, uid, ids, context={}):
211 datas = self.read(cr, uid, att_id)
214 if not context or not context.get('model'):
217 model = context.get('model')
218 model_field = context.get('attendee_field', False)
219 obj = self.pool.get(model)
220 res_obj = obj.browse(cr, uid, context['active_id'])
221 type = datas.get('type')
222 att_obj = self.pool.get('calendar.attendee')
225 if not model == 'calendar.attendee':
226 vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
228 if type == 'internal':
229 user_obj = self.pool.get('res.users')
230 if not datas.get('user_ids'):
231 raise osv.except_osv(_('Error!'), ("Please select any User"))
232 for user_id in datas.get('user_ids'):
233 user = user_obj.browse(cr, uid, user_id)
234 vals.update({'user_id': user_id,
235 'email': user.address_id.email})
236 if user.address_id.email:
237 mail_to.append(user.address_id.email)
239 elif type == 'external' and datas.get('email'):
240 vals.update({'email': datas['email']})
241 mail_to.append(datas['email'])
242 elif type == 'partner':
243 add_obj = self.pool.get('res.partner.address')
244 for contact in add_obj.browse(cr, uid, datas['contact_ids']):
246 'partner_address_id': contact.id,
247 'email': contact.email})
249 mail_to.append(contact.email)
251 if model == 'calendar.attendee':
252 att = att_obj.browse(cr, uid, context['active_id'])
254 'parent_ids' : [(4, att.id)],
257 if datas.get('send_mail'):
259 name = map(lambda x: x[1], filter(lambda x: type==x[0], \
260 self._columns['type'].selection))
261 raise osv.except_osv(_('Error!'), ("%s must have an email \
262 Address to send mail") % (name[0]))
263 att_obj._send_mail(cr, uid, [att_id], mail_to, \
264 email_from=tools.config.get('email_from', False))
265 att_id = att_obj.create(cr, uid, vals)
267 obj.write(cr, uid, res_obj.id, {model_field: [(4, att_id)]})
271 def onchange_partner_id(self, cr, uid, ids, partner_id, *args, **argv):
273 return {'value': {'contact_ids': []}}
274 cr.execute('select id from res_partner_address \
275 where partner_id=%s' % (partner_id))
276 contacts = map(lambda x: x[0], cr.fetchall())
277 return {'value': {'contact_ids': contacts}}
279 invite_attendee_wizard()
281 class calendar_attendee(osv.osv):
282 _name = 'calendar.attendee'
283 _description = 'Attendee information'
288 def _get_address(self, name=None, email=None):
291 return (name or '') + (email and ('MAILTO:' + email) or '')
293 def _compute_data(self, cr, uid, ids, name, arg, context):
297 for attdata in self.browse(cr, uid, ids, context=context):
300 if name == 'sent_by':
301 if not attdata.sent_by_uid:
302 result[id][name] = ''
305 result[id][name] = self._get_address(attdata.sent_by_uid.name, \
306 attdata.sent_by_uid.address_id.email)
309 result[id][name] = self._get_address(attdata.user_id.name, attdata.email)
310 elif attdata.partner_address_id:
311 result[id][name] = self._get_address(attdata.partner_id.name, attdata.email)
313 result[id][name] = self._get_address(None, attdata.email)
314 if name == 'delegated_to':
316 for parent in attdata.parent_ids:
318 todata.append('MAILTO:' + parent.email)
319 result[id][name] = ', '.join(todata)
320 if name == 'delegated_from':
322 for child in attdata.child_ids:
324 fromdata.append('MAILTO:' + child.email)
325 result[id][name] = ', '.join(fromdata)
326 if name == 'event_date':
328 result[id][name] = attdata.ref.date
330 result[id][name] = False
331 if name == 'event_end_date':
333 result[id][name] = attdata.ref.date_deadline
335 result[id][name] = False
336 if name == 'sent_by_uid':
338 result[id][name] = (attdata.ref.user_id.id,attdata.ref.user_id.name)
340 result[id][name] = uid
341 if name == 'language':
342 user_obj = self.pool.get('res.users')
343 lang = user_obj.read(cr, uid, uid, ['context_lang'])['context_lang']
344 result[id][name] = lang.replace('_', '-')
347 def _links_get(self, cr, uid, context={}):
348 obj = self.pool.get('res.request.link')
349 ids = obj.search(cr, uid, [])
350 res = obj.read(cr, uid, ids, ['object', 'name'], context)
351 return [(r['object'], r['name']) for r in res]
353 def _lang_get(self, cr, uid, context={}):
354 obj = self.pool.get('res.lang')
355 ids = obj.search(cr, uid, [])
356 res = obj.read(cr, uid, ids, ['code', 'name'], context)
357 res = [((r['code']).replace('_', '-'), r['name']) for r in res]
361 'cutype': fields.selection([('individual', 'Individual'), \
362 ('group', 'Group'), ('resource', 'Resource'), \
363 ('room', 'Room'), ('unknown', '') ], \
364 'Invite Type', help="Specify the type of Invitation"),
365 'member': fields.char('Member', size=124,
366 help="Indicate the groups that the attendee belongs to"),
367 'role': fields.selection([('req-participant', 'Participation required'), \
368 ('chair', 'Chair Person'), \
369 ('opt-participant', 'Optional Participation'), \
370 ('non-participant', 'For information Purpose')], 'Role', \
371 help='Participation role for the calendar user'),
372 'state': fields.selection([('tentative', 'Tentative'),
373 ('needs-action', 'Needs Action'),
374 ('accepted', 'Accepted'),
375 ('declined', 'Declined'),
376 ('delegated', 'Delegated')], 'State', readonly=True,
377 help="Status of the attendee's participation"),
378 'rsvp': fields.boolean('Required Reply?',
379 help="Indicats whether the favor of a reply is requested"),
380 'delegated_to': fields.function(_compute_data, method=True, \
381 string='Delegated To', type="char", size=124, store=True, \
382 multi='delegated_to', help="The users that the original \
383 request was delegated to"),
384 'delegated_from': fields.function(_compute_data, method=True, string=\
385 'Delegated From', type="char", store=True, size=124, multi='delegated_from'),
386 'parent_ids': fields.many2many('calendar.attendee', 'calendar_attendee_parent_rel', 'attendee_id', 'parent_id', 'Delegrated From'),
387 'child_ids': fields.many2many('calendar.attendee', 'calendar_attendee_child_rel', 'attendee_id', 'child_id', 'Delegrated To'),
388 '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"),
389 'sent_by_uid': fields.function(_compute_data, method=True, string='Sent By User', type="many2one", relation="res.users", multi='sent_by_uid'),
390 'cn': fields.function(_compute_data, method=True, string='Common name', type="char", size=124, multi='cn', store=True),
391 'dir': fields.char('URI Reference', size=124, help="Reference to the URI that points to the directory information corresponding to the attendee."),
392 '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."),
393 'user_id': fields.many2one('res.users', 'User'),
394 'partner_address_id': fields.many2one('res.partner.address', 'Contact'),
395 'partner_id': fields.related('partner_address_id', 'partner_id', type='many2one', relation='res.partner', string='Partner', help="Partner related to contact"),
396 'email': fields.char('Email', size=124, help="Email of Invited Person"),
397 'event_date': fields.function(_compute_data, method=True, string='Event Date', type="datetime", multi='event_date'),
398 'event_end_date': fields.function(_compute_data, method=True, string='Event End Date', type="datetime", multi='event_end_date'),
399 'ref': fields.reference('Event Ref', selection=_links_get, size=128),
400 'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"),
403 'state': lambda *x: 'needs-action',
406 response_re = re.compile("Are you coming\?.*\n*.*(YES|NO|MAYBE).*", re.UNICODE)
408 def msg_new(self, cr, uid, msg):
411 def msg_act_get(self, msg):
412 mailgate_obj = self.pool.get('mail.gateway')
413 body = mailgate_obj.msg_body_get(msg)
415 res = self.response_re.findall(body['body'])
417 actions['state'] = res[0]
420 def msg_update(self, cr, uid, ids, msg, data={}, default_act='None'):
421 msg_actions = self.msg_act_get(msg)
422 if msg_actions.get('state'):
423 if msg_actions['state'] in ['YES', 'NO', 'MAYBE']:
424 mapping = {'YES': 'accepted', 'NO': 'declined', 'MAYBE': 'tentative'}
425 status = mapping[msg_actions['state']]
426 print 'Got response for invitation id: %s as %s' % (ids, status)
427 self.write(cr, uid, ids, {'state': status})
430 def _send_mail(self, cr, uid, ids, mail_to, email_from=tools.config.get('email_from', False), context={}):
431 company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.name
432 for att in self.browse(cr, uid, ids, context=context):
433 sign = att.sent_by_uid and att.sent_by_uid.signature or ''
434 sign = '<br>'.join(sign and sign.split('\n') or [])
436 if res_obj and len(res_obj):
438 sub = '[%s Invitation][%d] %s' % (company, att.id, res_obj.name)
440 other_invitaion_ids = self.search(cr, uid, [('ref','=',att.ref)])
441 for att2 in self.browse(cr, uid, other_invitaion_ids):
442 att_infos.append(((att2.user_id and att2.user_id.name) or \
443 (att2.partner_id and att2.partner_id.name) or \
444 att2.email) + ' - Status: ' + att2.state.title())
445 body_vals = {'name': res_obj.name,
446 'start_date': res_obj.date,
447 'end_date': res_obj.date_deadline or False,
448 'description': res_obj.description or '-',
449 'location': res_obj.location or '-',
450 'attendees': '<br>'.join(att_infos),
451 'user': res_obj.user_id and res_obj.user_id.name or 'OpenERP User',
455 body = html_invitation % body_vals
456 if mail_to and email_from:
466 def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
468 return {'value': {'email': ''}}
469 usr_obj = self.pool.get('res.users')
470 user = usr_obj.browse(cr, uid, user_id, *args)
471 return {'value': {'email': user.address_id.email, 'availability':user.availability}}
473 def do_tentative(self, cr, uid, ids, context=None, *args):
474 self.write(cr, uid, ids, {'state': 'tentative'}, context)
476 def do_accept(self, cr, uid, ids, context=None, *args):
478 vals = self.read(cr, uid, invite, context=context)
479 user = vals.get('user_id')
481 ref = vals.get('ref', None)
484 if event_ref.user_id.id != user[0]:
485 defaults = {'user_id': user[0]}
486 new_event = model_obj.copy(cr, uid, event, default=defaults, context=context)
487 self.write(cr, uid, invite, {'state': 'accepted'}, context)
490 def do_decline(self, cr, uid, ids, context=None, *args):
491 self.write(cr, uid, ids, {'state': 'declined'}, context)
493 def create(self, cr, uid, vals, context={}):
494 if not vals.get("email") and vals.get("cn"):
495 cnval = vals.get("cn").split(':')
496 email = filter(lambda x:x.__contains__('@'), cnval)
497 vals['email'] = email[0]
498 vals['cn'] = vals.get("cn")
499 res = super(calendar_attendee, self).create(cr, uid, vals, context)
504 class res_alarm(osv.osv):
506 _description = 'Basic Alarm Information'
508 'name':fields.char('Name', size=256, required=True),
509 'trigger_occurs': fields.selection([('before', 'Before'), ('after', 'After')], \
510 'Triggers', required=True),
511 'trigger_interval': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), \
512 ('days', 'Days')], 'Interval', required=True),
513 'trigger_duration': fields.integer('Duration', required=True),
514 'trigger_related': fields.selection([('start', 'The event starts'), ('end', \
515 'The event ends')], 'Related to', required=True),
516 'duration': fields.integer('Duration', help="""Duration' and 'Repeat' \
517 are both optional, but if one occurs, so MUST the other"""),
518 'repeat': fields.integer('Repeat'),
519 '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."),
524 'trigger_interval': lambda *x: 'minutes',
525 'trigger_duration': lambda *x: 5,
526 'trigger_occurs': lambda *x: 'before',
527 'trigger_related': lambda *x: 'start',
528 'active': lambda *x: 1,
531 def do_alarm_create(self, cr, uid, ids, model, date, context={}):
532 alarm_obj = self.pool.get('calendar.alarm')
533 ir_obj = self.pool.get('ir.model')
534 model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
536 model_obj = self.pool.get(model)
537 for data in model_obj.browse(cr, uid, ids):
538 basic_alarm = data.alarm_id
539 if not context.get('alarm_id'):
540 self.do_alarm_unlink(cr, uid, [data.id], model)
542 self.do_alarm_unlink(cr, uid, [data.id], model)
546 'description': data.description,
548 'attendee_ids': [(6, 0, map(lambda x:x.id, data.attendee_ids))],
549 'trigger_related': basic_alarm.trigger_related,
550 'trigger_duration': basic_alarm.trigger_duration,
551 'trigger_occurs': basic_alarm.trigger_occurs,
552 'trigger_interval': basic_alarm.trigger_interval,
553 'duration': basic_alarm.duration,
554 'repeat': basic_alarm.repeat,
556 'event_date': data[date],
558 'model_id': model_id,
561 alarm_id = alarm_obj.create(cr, uid, vals)
562 cr.execute('Update %s set base_calendar_alarm_id=%s, alarm_id=%s \
563 where id=%s' % (model_obj._table, \
564 alarm_id, basic_alarm.id, data.id))
567 def do_alarm_unlink(self, cr, uid, ids, model, context={}):
568 alarm_obj = self.pool.get('calendar.alarm')
569 ir_obj = self.pool.get('ir.model')
570 model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
571 model_obj = self.pool.get(model)
572 for datas in model_obj.browse(cr, uid, ids):
573 alarm_ids = alarm_obj.search(cr, uid, [('model_id', '=', model_id), ('res_id', '=', datas.id)])
575 alarm_obj.unlink(cr, uid, alarm_ids)
576 cr.execute('Update %s set base_calendar_alarm_id=NULL, alarm_id=NULL\
577 where id=%s' % (model_obj._table, datas.id))
583 class calendar_alarm(osv.osv):
584 _name = 'calendar.alarm'
585 _description = 'Event alarm information'
586 _inherit = 'res.alarm'
590 'alarm_id': fields.many2one('res.alarm', 'Basic Alarm', ondelete='cascade'),
591 'name': fields.char('Summary', size=124, help="""Contains the text to be used as the message subject for email
592 or contains the text to be used for display"""),
593 'action': fields.selection([('audio', 'Audio'), ('display', 'Display'), \
594 ('procedure', 'Procedure'), ('email', 'Email') ], 'Action', \
595 required=True, help="Defines the action to be invoked when an alarm is triggered"),
596 'description': fields.text('Description', help='Provides a more complete description of the calendar component, than that provided by the "SUMMARY" property'),
597 'attendee_ids': fields.many2many('calendar.attendee', 'alarm_attendee_rel', \
598 'alarm_id', 'attendee_id', 'Attendees', readonly=True),
599 'attach': fields.binary('Attachment', help="""* Points to a sound resource, which is rendered when the alarm is triggered for audio,
600 * File which is intended to be sent as message attachments for email,
601 * Points to a procedure resource, which is invoked when the alarm is triggered for procedure."""),
602 'res_id': fields.integer('Resource ID'),
603 'model_id': fields.many2one('ir.model', 'Model'),
604 'user_id': fields.many2one('res.users', 'Owner'),
605 'event_date': fields.datetime('Event Date'),
606 'event_end_date': fields.datetime('Event End Date'),
607 'trigger_date': fields.datetime('Trigger Date', readonly="True"),
608 'state':fields.selection([
613 ], 'State', select=True, readonly=True),
617 'action': lambda *x: 'email',
618 'state': lambda *x: 'run',
621 def create(self, cr, uid, vals, context={}):
622 event_date = vals.get('event_date', False)
624 dtstart = datetime.strptime(vals['event_date'], "%Y-%m-%d %H:%M:%S")
625 if vals['trigger_interval'] == 'days':
626 delta = timedelta(days=vals['trigger_duration'])
627 if vals['trigger_interval'] == 'hours':
628 delta = timedelta(hours=vals['trigger_duration'])
629 if vals['trigger_interval'] == 'minutes':
630 delta = timedelta(minutes=vals['trigger_duration'])
631 trigger_date = dtstart + (vals['trigger_occurs'] == 'after' and delta or -delta)
632 vals['trigger_date'] = trigger_date
633 res = super(calendar_alarm, self).create(cr, uid, vals, context)
636 def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False,\
640 current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
641 cr.execute("select alarm.id as id \
642 from calendar_alarm alarm \
643 where alarm.state = %s and alarm.trigger_date <= %s", ('run', current_datetime))
644 res = cr.dictfetchall()
645 alarm_ids = map(lambda x: x['id'], res)
646 attendee_obj = self.pool.get('calendar.attendee')
647 request_obj = self.pool.get('res.request')
649 for alarm in self.browse(cr, uid, alarm_ids):
650 if alarm.action == 'display':
653 'act_from': alarm.user_id.id,
654 'act_to': alarm.user_id.id,
655 'body': alarm.description,
656 'trigger_date': alarm.trigger_date,
657 'ref_doc1': '%s,%s' % (alarm.model_id.model, alarm.res_id)
659 request_id = request_obj.create(cr, uid, value)
660 request_ids = [request_id]
661 for attendee in alarm.attendee_ids:
663 value['act_to'] = attendee.user_id.id
664 request_id = request_obj.create(cr, uid, value)
665 request_ids.append(request_id)
666 request_obj.request_send(cr, uid, request_ids)
668 if alarm.action == 'email':
669 sub = '[Openobject Remainder] %s' % (alarm.name)
679 """ % (alarm.name, alarm.trigger_date, alarm.description, \
680 alarm.user_id.name, alarm.user_id.signature)
681 mail_to = [alarm.user_id.address_id.email]
682 for att in alarm.attendee_ids:
683 mail_to.append(att.user_id.address_id.email)
686 tools.config.get('email_from', False),
691 self.write(cr, uid, [alarm.id], {'state':'done'})
697 class calendar_event(osv.osv):
698 _name = "calendar.event"
699 _description = "Calendar Event"
702 def _tz_get(self, cr, uid, context={}):
703 return [(x.lower(), x) for x in pytz.all_timezones]
706 def onchange_dates(self, cr, uid, ids, start_date, duration=False, end_date=False, context={}):
709 start = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
711 if end_date and not duration:
712 end = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
714 duration = float(diff.days)* 24 + (float(diff.seconds) / 3600)
715 value['duration'] = round(duration, 2)
717 end = start + timedelta(hours=duration)
718 value['date_deadline'] = end.strftime("%Y-%m-%d %H:%M:%S")
719 return {'value': value}
721 def _get_rulestring(self, cr, uid, ids, name, arg, context=None):
724 datas = self.read(cr, uid, event)
725 if datas.get('rrule_type'):
726 if datas.get('rrule_type') == 'none':
727 result[event] = False
728 elif datas.get('rrule_type') == 'custom':
729 rrule_custom = self.compute_rule_string(cr, uid, datas)
730 result[event] = rrule_custom
732 result[event] = self.compute_rule_string(cr, uid, {'freq':\
733 datas.get('rrule_type').upper(), \
734 'interval': 1}, context=context)
738 'id': fields.integer('ID'),
739 'sequence': fields.integer('Sequence'),
740 'name': fields.char('Description', size=64, required=True),
741 'date': fields.datetime('Date'),
742 'date_deadline': fields.datetime('Deadline'),
743 'create_date': fields.datetime('Created', readonly=True),
744 'duration': fields.float('Duration'),
745 'description': fields.text('Your action'),
746 'class': fields.selection([('public', 'Public'), ('private', 'Private'), \
747 ('confidential', 'Confidential')], 'Mark as'),
748 'location': fields.char('Location', size=264, help="Location of Event"),
749 'show_as': fields.selection([('free', 'Free'), \
752 'base_calendar_url': fields.char('Caldav URL', size=264),
753 'exdate': fields.text('Exception Date/Times', help="This property \
754 defines the list of date/time exceptions for arecurring calendar component."),
755 'exrule': fields.char('Exception Rule', size=352, help="defines a \
756 rule or repeating pattern for anexception to a recurrence set"),
757 'rrule': fields.function(_get_rulestring, type='char', size=124, method=True, string='Recurrent Rule', store=True),
758 'rrule_type': fields.selection([('none', ''), ('daily', 'Daily'), \
759 ('weekly', 'Weekly'), ('monthly', 'Monthly'), \
760 ('yearly', 'Yearly'), ('custom', 'Custom')], 'Recurrency'),
761 'alarm_id': fields.many2one('res.alarm', 'Alarm'),
762 'base_calendar_alarm_id': fields.many2one('calendar.alarm', 'Alarm'),
763 'recurrent_uid': fields.integer('Recurrent ID'),
764 'recurrent_id': fields.datetime('Recurrent ID date'),
765 'vtimezone': fields.related('user_id', 'context_tz', type='char', size=24, string='Timezone'),
766 'user_id': fields.many2one('res.users', 'Responsible'),
767 'freq': fields.selection([('None', 'No Repeat'), \
768 ('secondly', 'Secondly'), \
769 ('minutely', 'Minutely'), \
770 ('hourly', 'Hourly'), \
771 ('daily', 'Daily'), \
772 ('weekly', 'Weekly'), \
773 ('monthly', 'Monthly'), \
774 ('yearly', 'Yearly')], 'Frequency'),
775 'interval': fields.integer('Interval'),
776 'count': fields.integer('Count'),
777 'mo': fields.boolean('Mon'),
778 'tu': fields.boolean('Tue'),
779 'we': fields.boolean('Wed'),
780 'th': fields.boolean('Thu'),
781 'fr': fields.boolean('Fri'),
782 'sa': fields.boolean('Sat'),
783 'su': fields.boolean('Sun'),
784 'select1': fields.selection([('date', 'Date of month'), \
785 ('day', 'Day of month')], 'Option'),
786 'day': fields.integer('Date of month'),
787 'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), \
788 ('WE', 'Wednesday'), ('TH', 'Thursday'), \
789 ('FR', 'Friday'), ('SA', 'Saturday'), \
790 ('SU', 'Sunday')], 'Weekday'),
791 'byday': fields.selection([('1', 'First'), ('2', 'Second'), \
792 ('3', 'Third'), ('4', 'Fourth'), \
793 ('5', 'Fifth'), ('-1', 'Last')], 'By day'),
794 'month_list': fields.selection(months.items(), 'Month'),
795 'end_date': fields.date('Repeat Until')
799 'class': lambda *a: 'public',
800 'show_as': lambda *a: 'busy',
801 'freq': lambda *x: 'None',
802 'select1': lambda *x: 'date',
803 'interval': lambda *x: 1,
806 def modify_this(self, cr, uid, event_id, defaults, real_date, context=None, *args):
807 event_id = base_calendar_id2real_id(event_id)
808 datas = self.read(cr, uid, event_id, context=context)
810 'recurrent_uid': base_calendar_id2real_id(datas['id']),
811 'recurrent_id': defaults.get('date') or real_date,
812 'rrule_type': 'none',
815 exdate = datas['exdate'] and datas['exdate'].split(',') or []
816 if real_date and defaults.get('date'):
817 exdate.append(real_date)
818 self.write(cr, uid, event_id, {'exdate': ','.join(exdate)}, context=context)
819 new_id = self.copy(cr, uid, event_id, default=defaults, context=context)
822 def modify_all(self, cr, uid, event_id, defaults, context=None, *args):
823 event_id = base_calendar_id2real_id(event_id)
825 defaults.update({'table': self._table})
827 qry = "UPDATE %(table)s set name='%(name)s', \
828 date='%(date)s', date_deadline='%(date_deadline)s'"
829 if defaults.get('alarm_id'):
830 qry += ", alarm_id=%(alarm_id)s"
831 if defaults.get('location'):
832 qry += ", location='%(location)s'"
833 qry += "WHERE id=%s" % (event_id)
834 cr.execute(qry % (defaults))
837 def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100):
840 if isinstance(select, (str, int, long)):
845 if ids and (base_start_date or base_until_date):
846 cr.execute("select m.id, m.rrule, m.date, m.date_deadline, \
847 m.exdate from " + self._table + \
848 " m where m.id in ("\
849 + ','.join(map(lambda x: str(x), ids))+")")
852 for data in cr.dictfetchall():
853 start_date = base_start_date and datetime.strptime(base_start_date, "%Y-%m-%d") or False
854 until_date = base_until_date and datetime.strptime(base_until_date, "%Y-%m-%d") or False
857 event_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
858 if start_date and start_date <= event_date:
859 start_date = event_date
860 if not data['rrule']:
861 if start_date and (event_date < start_date):
863 if until_date and (event_date > until_date):
865 idval = real_id2base_calendar_id(data['id'], data['date'])
869 exdate = data['exdate'] and data['exdate'].split(',') or []
870 rrule_str = data['rrule']
872 rrule_until_date = False
874 for rule in rrule_str.split(';'):
875 name, value = rule.split('=')
878 value = parser.parse(value)
879 rrule_until_date = parser.parse(value.strftime("%Y-%m-%d"))
880 if until_date and until_date >= rrule_until_date:
881 until_date = rrule_until_date
883 value = until_date.strftime("%Y%m%d%H%M%S")
884 new_rule = '%s=%s' % (name, value)
885 new_rrule_str.append(new_rule)
886 if not is_until and until_date:
887 value = until_date.strftime("%Y%m%d%H%M%S")
889 new_rule = '%s=%s' % (name, value)
890 new_rrule_str.append(new_rule)
891 new_rrule_str = ';'.join(new_rrule_str)
892 start_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
893 rdates = get_recurrent_dates(str(new_rrule_str), exdate, start_date)
895 r_date = datetime.strptime(rdate, "%Y-%m-%d %H:%M:%S")
896 if start_date and r_date < start_date:
898 if until_date and r_date > until_date:
900 idval = real_id2base_calendar_id(data['id'], rdate)
905 if isinstance(select, (str, int, long)):
906 return ids and ids[0] or False
909 def compute_rule_string(self, cr, uid, datas, context=None, *args):
910 weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
914 # logic for computing rrule string
915 freq = datas.get('freq')
920 byday = map(lambda x: x.upper(), filter(lambda x: datas.get(x) and x in weekdays, datas))
922 weekstring = ';BYDAY=' + ','.join(byday)
924 elif freq == 'monthly':
925 if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
926 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
927 if datas.get('select1')=='day':
928 monthstring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
929 elif datas.get('select1')=='date':
930 monthstring = ';BYMONTHDAY=' + str(datas.get('day'))
932 elif freq == 'yearly':
933 if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
934 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
935 bymonth = ';BYMONTH=' + str(datas.get('month_list'))
936 if datas.get('select1')=='day':
937 bystring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
938 elif datas.get('select1')=='date':
939 bystring = ';BYMONTHDAY=' + str(datas.get('day'))
940 yearstring = bymonth + bystring
942 if datas.get('end_date'):
943 datas['end_date'] = ''.join((re.compile('\d')).findall(datas.get('end_date'))) + '235959Z'
944 enddate = (datas.get('count') and (';COUNT=' + str(datas.get('count'))) or '') +\
945 ((datas.get('end_date') and (';UNTIL=' + datas.get('end_date'))) or '')
947 rrule_string = 'FREQ=' + freq.upper() + weekstring + ';INTERVAL=' + \
948 str(datas.get('interval')) + enddate + monthstring + yearstring
953 def search(self, cr, uid, args, offset=0, limit=100, order=None,
954 context=None, count=False):
955 args_without_date = []
959 if arg[0] not in ('date', unicode('date')):
960 args_without_date.append(arg)
962 if arg[1] in ('>', '>='):
964 elif arg[1] in ('<', '<='):
966 res = super(calendar_event, self).search(cr, uid, args_without_date, \
967 offset, limit, order, context, count)
968 return self.get_recurrent_ids(cr, uid, res, start_date, until_date, limit)
971 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
974 if isinstance(ids, (str, int, long)):
979 for event_id in select:
980 if len(str(event_id).split('-')) > 1:
981 data = self.read(cr, uid, event_id, ['date', 'date_deadline', \
982 'rrule', 'duration'])
983 if data.get('rrule'):
984 real_date = data.get('date')
986 new_id = self.modify_this(cr, uid, event_id, data, \
988 context.update({'active_id': new_id,'active_ids': [new_id]})
990 event_id = base_calendar_id2real_id(event_id)
991 if not event_id in new_ids:
992 new_ids.append(event_id)
993 res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
994 if vals.has_key('alarm_id') or vals.has_key('base_calendar_alarm_id'):
995 alarm_obj = self.pool.get('res.alarm')
996 context.update({'alarm_id': vals.get('alarm_id')})
997 alarm_obj.do_alarm_create(cr, uid, new_ids, self._name, 'date', \
1001 def browse(self, cr, uid, ids, context=None, list_class=None, fields_process={}):
1002 if isinstance(ids, (str, int, long)):
1006 select = map(lambda x: base_calendar_id2real_id(x), select)
1007 res = super(calendar_event, self).browse(cr, uid, select, context, \
1008 list_class, fields_process)
1009 if isinstance(ids, (str, int, long)):
1010 return res and res[0] or False
1013 def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'):
1014 if isinstance(ids, (str, int, long)):
1018 select = map(lambda x: (x, base_calendar_id2real_id(x)), select)
1020 if fields and 'date' not in fields:
1021 fields.append('date')
1022 for base_calendar_id, real_id in select:
1023 res = super(calendar_event, self).read(cr, uid, real_id, fields=fields, context=context, \
1025 ls = base_calendar_id2real_id(base_calendar_id, with_date=res.get('duration', 0))
1026 if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
1028 res['date_deadline'] = ls[2]
1029 res['id'] = base_calendar_id
1032 if isinstance(ids, (str, int, long)):
1033 return result and result[0] or False
1036 def copy(self, cr, uid, id, default=None, context={}):
1037 res = super(calendar_event, self).copy(cr, uid, base_calendar_id2real_id(id), default, context)
1038 alarm_obj = self.pool.get('res.alarm')
1039 alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
1042 def unlink(self, cr, uid, ids, context=None):
1045 ls = base_calendar_id2real_id(id)
1046 if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
1048 for record in self.read(cr, uid, [base_calendar_id2real_id(id)], \
1049 ['date', 'rrule', 'exdate']):
1051 exdate = (record['exdate'] and (record['exdate'] + ',') or '') + ''.join((re.compile('\d')).findall(date_new)) + 'Z'
1052 if record['date'] == date_new:
1053 res = self.write(cr, uid, [base_calendar_id2real_id(id)], {'exdate': exdate})
1055 ids = map(lambda x: base_calendar_id2real_id(x), ids)
1056 res = super(calendar_event, self).unlink(cr, uid, \
1057 base_calendar_id2real_id(ids))
1058 alarm_obj = self.pool.get('res.alarm')
1059 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
1061 ids = map(lambda x: base_calendar_id2real_id(x), ids)
1062 res = super(calendar_event, self).unlink(cr, uid, ids)
1063 alarm_obj = self.pool.get('res.alarm')
1064 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
1067 def create(self, cr, uid, vals, context={}):
1068 res = super(calendar_event, self).create(cr, uid, vals, context)
1069 alarm_obj = self.pool.get('res.alarm')
1070 alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
1075 class calendar_todo(osv.osv):
1076 _name = "calendar.todo"
1077 _inherit = "calendar.event"
1078 _description = "Calendar Task"
1080 def _get_date(self, cr, uid, ids, name, arg, context):
1082 for event in self.browse(cr, uid, ids, context=context):
1083 res[event.id] = event.date_start
1086 def _set_date(self, cr, uid, id, name, value, arg, context):
1087 event = self.browse(cr, uid, id, context=context)
1088 cr.execute("UPDATE %s set date_start='%s' where id=%s" \
1089 % (self._table, value, id))
1093 'date': fields.function(_get_date, method=True, fnct_inv=_set_date, \
1094 string='Duration', store=True, type='datetime'),
1095 'duration': fields.integer('Duration'),
1103 class ir_attachment(osv.osv):
1104 _name = 'ir.attachment'
1105 _inherit = 'ir.attachment'
1107 def search_count(self, cr, user, args, context=None):
1110 args1.append(map(lambda x:str(x).split('-')[0], arg))
1111 return super(ir_attachment, self).search_count(cr, user, args1, context)
1113 def search(self, cr, uid, args, offset=0, limit=None, order=None,
1114 context=None, count=False):
1116 for i, arg in enumerate(new_args):
1117 if arg[0] == 'res_id':
1118 new_args[i] = (arg[0], arg[1], base_calendar_id2real_id(arg[2]))
1119 return super(ir_attachment, self).search(cr, uid, new_args, offset=offset,
1120 limit=limit, order=order,
1121 context=context, count=False)
1124 class ir_values(osv.osv):
1125 _inherit = 'ir.values'
1127 def set(self, cr, uid, key, key2, name, models, value, replace=True, \
1128 isobject=False, meta=False, preserve_user=False, company=False):
1131 if type(data) in (list, tuple):
1132 new_model.append((data[0], base_calendar_id2real_id(data[1])))
1134 new_model.append(data)
1135 return super(ir_values, self).set(cr, uid, key, key2, name, new_model,\
1136 value, replace, isobject, meta, preserve_user, company)
1138 def get(self, cr, uid, key, key2, models, meta=False, context={}, \
1139 res_id_req=False, without_user=True, key2_req=True):
1142 if type(data) in (list, tuple):
1143 new_model.append((data[0], base_calendar_id2real_id(data[1])))
1145 new_model.append(data)
1146 return super(ir_values, self).get(cr, uid, key, key2, new_model, \
1147 meta, context, res_id_req, without_user, key2_req)
1151 class ir_model(osv.osv):
1153 _inherit = 'ir.model'
1155 def read(self, cr, uid, ids, fields=None, context={},
1156 load='_classic_read'):
1157 data = super(ir_model, self).read(cr, uid, ids, fields=fields, \
1158 context=context, load=load)
1161 val['id'] = base_calendar_id2real_id(val['id'])
1166 class virtual_report_spool(web_services.report_spool):
1168 def exp_report(self, db, uid, object, ids, datas=None, context=None):
1169 if object == 'printscreen.list':
1170 return super(virtual_report_spool, self).exp_report(db, uid, \
1171 object, ids, datas, context)
1174 new_ids.append(base_calendar_id2real_id(id))
1177 if datas.get('id',False):
1178 datas['id'] = base_calendar_id2real_id(datas['id'])
1179 return super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
1181 virtual_report_spool()
1183 class res_users(osv.osv):
1184 _inherit = 'res.users'
1186 def _get_user_avail(self, cr, uid, ids, context=None):
1187 current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
1189 attendee_obj = self.pool.get('calendar.attendee')
1190 attendee_ids = attendee_obj.search(cr, uid, [
1191 ('event_date', '<=', current_datetime), ('event_end_date', '<=', current_datetime),
1192 ('state', '=', 'accepted'), ('user_id', 'in', ids)
1195 result = cr.dictfetchall()
1196 for attendee_data in attendee_obj.read(cr, uid, attendee_ids, ['user_id']):
1197 user_id = attendee_data['user_id']
1199 res.update({user_id:status})
1201 #TOCHECK: Delegated Event
1203 if user_id not in res:
1204 res[user_id] = 'free'
1208 def _get_user_avail_fun(self, cr, uid, ids, name, args, context=None):
1209 return self._get_user_avail(cr, uid, ids, context=context)
1212 'availability': fields.function(_get_user_avail_fun, type='selection', \
1213 selection=[('free', 'Free'), ('busy', 'Busy')], \
1214 string='Free/Busy', method=True),
1218 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: