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)) + 'Z')
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')
205 def do_invite(self, cr, uid, ids, context={}):
206 datas = self.read(cr, uid, ids)[0]
209 if not context or not context.get('model'):
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')
220 if not model == 'calendar.attendee':
221 vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
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)
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"))
244 'partner_address_id': contact.id,
245 'email': contact.email})
246 mail_to.append(contact.email)
248 if model == 'calendar.attendee':
249 att = att_obj.browse(cr, uid, context['active_id'])
251 'parent_ids' : [(4, att.id)],
254 att_id = att_obj.create(cr, uid, vals)
256 obj.write(cr, uid, res_obj.id, {model_field: [(4, att_id)]})
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))
265 def onchange_partner_id(self, cr, uid, ids, partner_id, *args, **argv):
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())
272 raise osv.except_osv(_('Error!'), \
273 ("Partner does not have any Contacts"))
275 return {'value': {'contact_ids': contacts}}
277 invite_attendee_wizard()
279 class calendar_attendee(osv.osv):
280 _name = 'calendar.attendee'
281 _description = 'Attendee information'
286 def _get_address(self, name=None, email=None):
289 return (name or '') + (email and ('MAILTO:' + email) or '')
291 def _compute_data(self, cr, uid, ids, name, arg, context):
295 for attdata in self.browse(cr, uid, ids, context=context):
298 if name == 'sent_by':
299 if not attdata.sent_by_uid:
300 result[id][name] = ''
303 result[id][name] = self._get_address(attdata.sent_by_uid.name, \
304 attdata.sent_by_uid.address_id.email)
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)
311 result[id][name] = self._get_address(None, attdata.email)
312 if name == 'delegated_to':
314 for parent in attdata.parent_ids:
315 todata.append('MAILTO:' + parent.email)
316 result[id][name] = ', '.join(todata)
317 if name == 'delegated_from':
319 for child in attdata.child_ids:
320 fromdata.append('MAILTO:' + child.email)
321 result[id][name] = ', '.join(fromdata)
322 if name == 'event_date':
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')
329 result[id][name] = False
330 if name == 'event_end_date':
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')
337 result[id][name] = False
338 if name == 'sent_by_uid':
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')
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('_', '-')
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]
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]
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"),
408 'state': lambda *x: 'needs-action',
411 response_re = re.compile("Are you coming\?.*\n*.*(YES|NO|MAYBE).*", re.UNICODE)
413 def msg_new(self, cr, uid, msg):
416 def msg_act_get(self, msg):
417 mailgate_obj = self.pool.get('mail.gateway')
418 body = mailgate_obj.msg_body_get(msg)
420 res = self.response_re.findall(body['body'])
422 actions['state'] = res[0]
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})
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):
444 sub = '[%s Invitation][%d] %s' % (company, att.id, res_obj.name)
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',
461 body = html_invitation % body_vals
462 if mail_to and email_from:
472 def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
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}}
479 def do_tentative(self, cr, uid, ids, context=None, *args):
480 self.write(cr, uid, ids, {'state': 'tentative'}, context)
482 def do_accept(self, cr, uid, ids, context=None, *args):
483 self.write(cr, uid, ids, {'state': 'accepted'}, context)
485 def do_decline(self, cr, uid, ids, context=None, *args):
486 self.write(cr, uid, ids, {'state': 'declined'}, context)
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)
499 class res_alarm(osv.osv):
501 _description = 'Basic Alarm Information'
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."),
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,
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]
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)
537 self.do_alarm_unlink(cr, uid, [data.id], model)
541 'description': data.description,
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,
551 'event_date': data[date],
553 'model_id': model_id,
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))
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)])
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))
579 class calendar_alarm(osv.osv):
580 _name = 'calendar.alarm'
581 _description = 'Event alarm information'
582 _inherit = 'res.alarm'
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([
609 ], 'State', select=True, readonly=True),
613 'action': lambda *x: 'email',
614 'state': lambda *x: 'run',
617 def create(self, cr, uid, vals, context={}):
618 event_date = vals.get('event_date', False)
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)
632 def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False,\
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')
645 for alarm in self.browse(cr, uid, alarm_ids):
646 if alarm.action == 'display':
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)
655 request_id = request_obj.create(cr, uid, value)
656 request_ids = [request_id]
657 for attendee in alarm.attendee_ids:
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)
664 if alarm.action == 'email':
665 sub = '[Openobject Remainder] %s' % (alarm.name)
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)
682 tools.config.get('email_from', False),
687 self.write(cr, uid, [alarm.id], {'state':'done'})
693 class calendar_event(osv.osv):
694 _name = "calendar.event"
695 _description = "Calendar Event"
698 def _tz_get(self, cr, uid, context={}):
699 return [(x.lower(), x) for x in pytz.all_timezones]
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':
706 rrule = self.pool.get('calendar.custom.rrule')
707 rrulestr = rrule.compute_rule_string(cr, uid, {'freq': rtype.upper(), \
709 return {'value': {'rrule': rrulestr}}
711 def _get_duration(self, cr, uid, ids, name, arg, context):
713 for event in self.browse(cr, uid, ids, context=context):
714 start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
716 if event.date_deadline:
717 end = datetime.strptime(event.date_deadline[:19], "%Y-%m-%d %H:%M:%S")
719 duration = float(diff.days)* 24 + (float(diff.seconds) / 3600)
720 res[event.id] = round(duration, 2)
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))
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'), \
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'),
765 'class': lambda *a: 'public',
766 'show_as': lambda *a: 'busy',
769 def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
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]
776 value.update({'vtimezone': timezone.lower()})
777 return {'value': value}
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')
783 'recurrent_uid': base_calendar_id2real_id(datas['id']),
784 'recurrent_id': defaults.get('date'),
785 'rrule_type': 'none',
788 new_id = self.copy(cr, uid, ids[0], default=defaults, context=context)
791 def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100):
794 if isinstance(select, (str, int, long)):
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))+")")
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
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):
817 if until_date and (event_date > until_date):
819 idval = real_id2base_calendar_id(data['id'], data['date'])
823 exdate = data['exdate'] and data['exdate'].split(',') or []
824 rrule_str = data['rrule']
826 rrule_until_date = False
828 for rule in rrule_str.split(';'):
829 name, value = rule.split('=')
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
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")
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)
849 r_date = datetime.strptime(rdate, "%Y-%m-%d %H:%M:%S")
850 if start_date and r_date < start_date:
852 if until_date and r_date > until_date:
854 idval = real_id2base_calendar_id(data['id'], rdate)
859 if isinstance(select, (str, int, long)):
860 return ids and ids[0] or False
863 def search(self, cr, uid, args, offset=0, limit=100, order=None,
864 context=None, count=False):
865 args_without_date = []
869 if arg[0] not in ('date', unicode('date')):
870 args_without_date.append(arg)
872 if arg[1] in ('>', '>='):
874 elif arg[1] in ('<', '<='):
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)
881 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
884 if isinstance(ids, (str, int, long)):
890 id = base_calendar_id2real_id(id)
891 if not id in new_ids:
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)
900 def browse(self, cr, uid, ids, context=None, list_class=None, fields_process={}):
901 if isinstance(ids, (str, int, long)):
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
911 def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'):
912 if isinstance(ids, (str, int, long)):
916 select = map(lambda x: (x, base_calendar_id2real_id(x)), select)
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, \
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:
926 res['date_deadline'] = ls[2]
927 res['id'] = base_calendar_id
930 if isinstance(ids, (str, int, long)):
931 return result and result[0] or False
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')
940 def unlink(self, cr, uid, ids, context=None):
943 ls = base_calendar_id2real_id(id)
944 if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
946 for record in self.read(cr, uid, [base_calendar_id2real_id(id)], \
947 ['date', 'rrule', 'exdate']):
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})
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)
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)
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')
972 class calendar_todo(osv.osv):
973 _name = "calendar.todo"
974 _inherit = "calendar.event"
975 _description = "Calendar Task"
977 def _get_date(self, cr, uid, ids, name, arg, context):
979 for event in self.browse(cr, uid, ids, context=context):
980 res[event.id] = event.date_start
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))
990 'date': fields.function(_get_date, method=True, fnct_inv=_set_date, \
991 string='Duration', store=True, type='datetime'),
992 'duration': fields.integer('Duration'),
1000 class ir_attachment(osv.osv):
1001 _name = 'ir.attachment'
1002 _inherit = 'ir.attachment'
1004 def search_count(self, cr, user, args, context=None):
1007 args1.append(map(lambda x:str(x).split('-')[0], arg))
1008 return super(ir_attachment, self).search_count(cr, user, args1, context)
1010 def search(self, cr, uid, args, offset=0, limit=None, order=None,
1011 context=None, count=False):
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)
1021 class ir_values(osv.osv):
1022 _inherit = 'ir.values'
1024 def set(self, cr, uid, key, key2, name, models, value, replace=True, \
1025 isobject=False, meta=False, preserve_user=False, company=False):
1028 if type(data) in (list, tuple):
1029 new_model.append((data[0], base_calendar_id2real_id(data[1])))
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)
1035 def get(self, cr, uid, key, key2, models, meta=False, context={}, \
1036 res_id_req=False, without_user=True, key2_req=True):
1039 if type(data) in (list, tuple):
1040 new_model.append((data[0], base_calendar_id2real_id(data[1])))
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)
1048 class ir_model(osv.osv):
1050 _inherit = 'ir.model'
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)
1058 val['id'] = base_calendar_id2real_id(val['id'])
1063 class virtual_report_spool(web_services.report_spool):
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)
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)
1075 virtual_report_spool()
1077 class calendar_custom_rrule(osv.osv):
1078 _name = "calendar.custom.rrule"
1079 _description = "Custom Recurrency Rule"
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')
1114 'freq': lambda *x: 'daily',
1115 'select1': lambda *x: 'date',
1116 'interval': lambda *x: 1,
1119 def compute_rule_string(self, cr, uid, datas, context=None, *args):
1120 weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
1125 # logic for computing rrule string
1127 freq = datas.get('freq')
1129 obj.write(cr, uid, [res_obj.id], {'rrule': ''})
1132 if freq == 'weekly':
1133 byday = map(lambda x: x.upper(), filter(lambda x: datas.get(x) and x in weekdays, datas))
1135 weekstring = ';BYDAY=' + ','.join(byday)
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'))
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
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 '')
1160 rrule_string = 'FREQ=' + freq.upper() + weekstring + ';INTERVAL=' + \
1161 str(datas.get('interval')) + enddate + monthstring + yearstring
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"))
1172 if not context or not context.get('model'):
1175 model = context.get('model')
1176 obj = self.pool.get(model)
1177 res_obj = obj.browse(cr, uid, context['active_id'])
1179 rrule_string = self.compute_rule_string(cr, uid, datas)
1180 obj.write(cr, uid, [res_obj.id], {'rrule': rrule_string})
1183 calendar_custom_rrule()
1185 class res_users(osv.osv):
1186 _inherit = 'res.users'
1188 def _get_user_avail(self, cr, uid, ids, context=None):
1189 current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
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)
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']
1201 res.update({user_id:status})
1203 #TOCHECK: Delegrated Event
1205 if user_id not in res:
1206 res[user_id] = 'free'
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)
1214 'availability': fields.function(_get_user_avail_fun, type='selection', \
1215 selection=[('free', 'Free'), ('busy', 'Busy')], \
1216 string='Free/Busy', method=True),
1219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: