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 ##############################################################################
22 from datetime import datetime, timedelta
23 from datetime import datetime, timedelta
24 from dateutil import parser
25 from osv import fields, osv
26 from base_calendar import base_calendar
27 from service import web_services
28 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 caldav_id2real_id(caldav_id=None, with_date=False):
40 if caldav_id and isinstance(caldav_id, (str, unicode)):
41 res = caldav_id.split('-')
45 real_date = time.strftime("%Y-%m-%d %H:%M:%S", \
46 time.strptime(res[1], "%Y%m%d%H%M%S"))
47 start = datetime.strptime(real_date, "%Y-%m-%d %H:%M:%S")
48 end = start + timedelta(hours=with_date)
49 return (int(real_id), real_date, end.strftime("%Y-%m-%d %H:%M:%S"))
51 return caldav_id and int(caldav_id) or caldav_id
53 def real_id2caldav_id(real_id, recurrent_date):
54 if real_id and recurrent_date:
55 recurrent_date = time.strftime("%Y%m%d%H%M%S", \
56 time.strptime(recurrent_date, "%Y-%m-%d %H:%M:%S"))
57 return '%d-%s' % (real_id, recurrent_date)
61 def _links_get(self, cr, uid, context={}):
62 obj = self.pool.get('res.request.link')
63 ids = obj.search(cr, uid, [])
64 res = obj.read(cr, uid, ids, ['object', 'name'], context)
65 return [(r['object'], r['name']) for r in res]
67 class calendar_attendee(osv.osv):
68 _name = 'calendar.attendee'
69 _description = 'Attendee information'
74 def _get_address(self, name=None, email=None):
77 return (name or '') + (email and ('MAILTO:' + email) or '')
79 def _compute_data(self, cr, uid, ids, name, arg, context):
83 def get_delegate_data(user):
84 email = user.address_id and user.address_id.email or ''
85 return self._get_address(user.name, email)
87 for attdata in self.browse(cr, uid, ids, context=context):
91 if not attdata.sent_by_uid:
95 result[id][name] = self._get_address(attdata.sent_by_uid.name, \
96 attdata.sent_by_uid.address_id.email)
99 result[id][name] = self._get_address(attdata.user_id.name, attdata.email)
100 elif attdata.partner_address_id:
101 result[id][name] = self._get_address(attdata.partner_id.name, attdata.email)
103 result[id][name] = self._get_address(None, attdata.email)
104 if name == 'delegated_to':
105 user_obj = self.pool.get('res.users')
106 todata = map(get_delegate_data, attdata.del_to_user_ids)
107 result[id][name] = ', '.join(todata)
108 if name == 'delegated_from':
110 user_obj = self.pool.get('res.users')
111 fromdata = map(get_delegate_data, attdata.del_from_user_ids)
112 result[id][name] = ', '.join(fromdata)
113 if name == 'event_date':
114 # TO fix date for project task
116 model, res_id = tuple(attdata.ref.split(','))
117 model_obj = self.pool.get(model)
118 obj = model_obj.read(cr, uid, res_id, ['date'])[0]
119 result[id][name] = None#obj['date']
121 result[id][name] = None
122 if name == 'event_end_date':
124 model, res_id = tuple(attdata.ref.split(','))
125 model_obj = self.pool.get(model)
126 obj = model_obj.read(cr, uid, res_id, ['date_deadline'])[0]
127 result[id][name] = obj['date_deadline']
129 result[id][name] = None
130 if name == 'sent_by_uid':
132 model, res_id = tuple(attdata.ref.split(','))
133 model_obj = self.pool.get(model)
134 obj = model_obj.read(cr, uid, res_id, ['user_id'])[0]
135 result[id][name] = obj['user_id']
137 result[id][name] = uid
140 def _links_get(self, cr, uid, context={}):
141 obj = self.pool.get('res.request.link')
142 ids = obj.search(cr, uid, [])
143 res = obj.read(cr, uid, ids, ['object', 'name'], context)
144 return [(r['object'], r['name']) for r in res]
146 def _lang_get(self, cr, uid, context={}):
147 obj = self.pool.get('res.lang')
148 ids = obj.search(cr, uid, [])
149 res = obj.read(cr, uid, ids, ['code', 'name'], context)
150 res = [((r['code']).replace('_', '-'), r['name']) for r in res]
154 'cutype': fields.selection([('individual', 'Individual'), \
155 ('group', 'Group'), ('resource', 'Resource'), \
156 ('room', 'Room'), ('unknown', 'Unknown') ], \
157 'User Type', help="Specify the type of calendar user"),
158 'member': fields.char('Member', size=124,
159 help="Indicate the groups that the attendee belongs to"),
160 'role': fields.selection([('req-participant', 'Participation required'), \
161 ('chair', 'Chair Person'), \
162 ('opt-participant', 'Optional Participation'), \
163 ('non-participant', 'For information Purpose')], 'Role', \
164 help='Participation role for the calendar user'),
165 'state': fields.selection([('tentative', 'Tentative'),
166 ('needs-action', 'Needs Action'),
167 ('accepted', 'Accepted'),
168 ('declined', 'Declined'),
169 ('delegated', 'Delegated')], 'State', readonly=True,
170 help="Status of the attendee's participation"),
171 'rsvp': fields.boolean('Required Reply?',
172 help="Indicats whether the favor of a reply is requested"),
173 'delegated_to': fields.function(_compute_data, method=True, \
174 string='Delegated To', type="char", size=124, store=True, \
175 multi='delegated_to', help="The users that the original \
176 request was delegated to"),
177 'del_to_user_ids': fields.many2many('res.users', 'att_del_to_user_rel',
178 'attendee_id', 'user_id', 'Users'),
179 'delegated_from': fields.function(_compute_data, method=True, string=\
180 'Delegated From', type="char", store=True, size=124, multi='delegated_from'),
181 'del_from_user_ids': fields.many2many('res.users', 'att_del_from_user_rel', \
182 'attendee_id', 'user_id', 'Users'),
183 '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"),
184 'sent_by_uid': fields.many2one('res.users', 'Sent by User'),
185 'cn': fields.function(_compute_data, method=True, string='Common name', type="char", size=124, multi='cn', store=True),
186 'dir': fields.char('URI Reference', size=124, help="Reference to the URI that points to the directory information corresponding to the attendee."),
187 'language': fields.selection(_lang_get, 'Language',
188 help="To specify the language for text values in a property or property parameter."),
189 'user_id': fields.many2one('res.users', 'User'),
190 'partner_address_id': fields.many2one('res.partner.address', 'Contact'),
191 'partner_id':fields.related('partner_address_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
192 'email': fields.char('Email', size=124),
193 'event_date': fields.function(_compute_data, method=True, string='Event Date', type="datetime", multi='event_date'),
194 'event_end_date': fields.function(_compute_data, method=True, string='Event End Date', type="datetime", multi='event_end_date'),
195 'ref': fields.reference('Document Ref', selection=_links_get, size=128),
196 'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"),
199 'state': lambda *x: 'needs-action',
202 def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
204 return {'value': {'email': ''}}
205 usr_obj = self.pool.get('res.users')
206 user = usr_obj.browse(cr, uid, user_id, *args)
207 return {'value': {'email': user.address_id.email, 'availability':user.availability}}
209 def do_tentative(self, cr, uid, ids, context=None, *args):
210 self.write(cr, uid, ids, {'state': 'tentative'}, context)
212 def do_accept(self, cr, uid, ids, context=None, *args):
213 self.write(cr, uid, ids, {'state': 'accepted'}, context)
215 def do_decline(self, cr, uid, ids, context=None, *args):
216 self.write(cr, uid, ids, {'state': 'declined'}, context)
220 class res_alarm(osv.osv):
222 _description = 'Basic Alarm Information'
224 'name':fields.char('Name', size=256, required=True),
225 'trigger_occurs': fields.selection([('before', 'Before'), ('after', 'After')], \
226 'Triggers', required=True),
227 'trigger_interval': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), \
228 ('days', 'Days')], 'Interval', required=True),
229 'trigger_duration': fields.integer('Duration', required=True),
230 'trigger_related': fields.selection([('start', 'The event starts'), ('end', \
231 'The event ends')], 'Related to', required=True),
232 'duration': fields.integer('Duration', help="""Duration' and 'Repeat' \
233 are both optional, but if one occurs, so MUST the other"""),
234 'repeat': fields.integer('Repeat'),
235 '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."),
240 'trigger_interval': lambda *x: 'minutes',
241 'trigger_duration': lambda *x: 5,
242 'trigger_occurs': lambda *x: 'before',
243 'trigger_related': lambda *x: 'start',
244 'active': lambda *x: 1,
247 def do_alarm_create(self, cr, uid, ids, model, date, context={}):
248 alarm_obj = self.pool.get('calendar.alarm')
249 ir_obj = self.pool.get('ir.model')
250 model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
252 model_obj = self.pool.get(model)
253 for data in model_obj.browse(cr, uid, ids):
254 basic_alarm = data.alarm_id
255 self.do_alarm_unlink(cr, uid, [data.id], model)
259 'description': data.description,
261 'attendee_ids': [(6, 0, map(lambda x:x.id, data.attendee_ids))],
262 'trigger_related': basic_alarm.trigger_related,
263 'trigger_duration': basic_alarm.trigger_duration,
264 'trigger_occurs': basic_alarm.trigger_occurs,
265 'trigger_interval': basic_alarm.trigger_interval,
266 'duration': basic_alarm.duration,
267 'repeat': basic_alarm.repeat,
269 'event_date': data[date],
271 'model_id': model_id,
274 alarm_id = alarm_obj.create(cr, uid, vals)
275 cr.execute('Update %s set caldav_alarm_id=%s, alarm_id=%s \
276 where id=%s' % (model_obj._table, \
277 alarm_id, basic_alarm.id, data.id))
281 def do_alarm_unlink(self, cr, uid, ids, model, context={}):
282 alarm_obj = self.pool.get('calendar.alarm')
283 ir_obj = self.pool.get('ir.model')
284 model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
285 model_obj = self.pool.get(model)
286 for datas in model_obj.browse(cr, uid, ids):
287 alarm_ids = alarm_obj.search(cr, uid, [('model_id', '=', model_id), ('res_id', '=', datas.id)])
288 if alarm_ids and len(alarm_ids):
289 alarm_obj.unlink(cr, uid, alarm_ids)
290 cr.execute('Update %s set caldav_alarm_id=NULL, alarm_id=NULL\
291 where id=%s' % (model_obj._table, datas.id))
297 class calendar_alarm(osv.osv):
298 _name = 'calendar.alarm'
299 _description = 'Event alarm information'
300 _inherits = {'res.alarm': "alarm_id"}
304 'alarm_id': fields.many2one('res.alarm', 'Basic Alarm', ondelete='cascade'),
305 'name': fields.char('Summary', size=124, help="""Contains the text to be used as the message subject for email
306 or contains the text to be used for display"""),
307 'action': fields.selection([('audio', 'Audio'), ('display', 'Display'), \
308 ('procedure', 'Procedure'), ('email', 'Email') ], 'Action', \
309 required=True, help="Defines the action to be invoked when an alarm is triggered"),
310 'description': fields.text('Description', help='Provides a more complete description of the calendar component, than that provided by the "SUMMARY" property'),
311 'attendee_ids': fields.many2many('calendar.attendee', 'alarm_attendee_rel', \
312 'alarm_id', 'attendee_id', 'Attendees', readonly=True),
313 'attach': fields.binary('Attachment', help="""* Points to a sound resource, which is rendered when the alarm is triggered for audio,
314 * File which is intended to be sent as message attachments for email,
315 * Points to a procedure resource, which is invoked when the alarm is triggered for procedure."""),
316 'res_id': fields.integer('Resource ID'),
317 'model_id': fields.many2one('ir.model', 'Model'),
318 'user_id': fields.many2one('res.users', 'Owner'),
319 'event_date': fields.datetime('Event Date'),
320 'event_end_date': fields.datetime('Event End Date'),
321 'trigger_date': fields.datetime('Trigger Date', readonly="True"),
322 'state':fields.selection([
327 ], 'State', select=True, readonly=True),
331 'action': lambda *x: 'email',
332 'state': lambda *x: 'run',
335 def create(self, cr, uid, vals, context={}):
336 event_date = vals.get('event_date', False)
338 dtstart = datetime.strptime(vals['event_date'], "%Y-%m-%d %H:%M:%S")
339 if vals['trigger_interval'] == 'days':
340 delta = timedelta(days=vals['trigger_duration'])
341 if vals['trigger_interval'] == 'hours':
342 delta = timedelta(hours=vals['trigger_duration'])
343 if vals['trigger_interval'] == 'minutes':
344 delta = timedelta(minutes=vals['trigger_duration'])
345 trigger_date = dtstart + (vals['trigger_occurs'] == 'after' and delta or -delta)
346 vals['trigger_date'] = trigger_date
347 res = super(calendar_alarm, self).create(cr, uid, vals, context)
350 def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False, \
354 current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
355 cr.execute("select alarm.id as id \
356 from calendar_alarm alarm \
357 where alarm.state = %s and alarm.trigger_date <= %s", ('run', current_datetime))
358 res = cr.dictfetchall()
359 alarm_ids = map(lambda x: x['id'], res)
360 attendee_obj = self.pool.get('calendar.attendee')
361 request_obj = self.pool.get('res.request')
363 for alarm in self.browse(cr, uid, alarm_ids):
364 if alarm.action == 'display':
367 'act_from': alarm.user_id.id,
368 'act_to': alarm.user_id.id,
369 'body': alarm.description,
370 'trigger_date': alarm.trigger_date,
371 'ref_doc1': '%s,%s' % (alarm.model_id.model, alarm.res_id)
373 request_id = request_obj.create(cr, uid, value)
374 request_ids = [request_id]
375 for attendee in alarm.attendee_ids:
376 value['act_to'] = attendee.user_id.id
377 request_id = request_obj.create(cr, uid, value)
378 request_ids.append(request_id)
379 request_obj.request_send(cr, uid, request_ids)
381 if alarm.action == 'email':
382 sub = '[Openobject Remainder] %s' % (alarm.name)
392 """ % (alarm.name, alarm.trigger_date, alarm.description, \
393 alarm.user_id.name, alarm.user_id.sign)
394 mail_to = [alarm.user_id.address_id.email]
395 for att in alarm.attendee_ids:
396 mail_to.append(att.user_id.address_id.email)
399 tools.confirm['from_mail'],
404 self.write(cr, uid, [alarm.id], {'state':'done'})
410 class calendar_event(osv.osv):
411 _name = "calendar.event"
412 _description = "Calendar Event"
415 def onchange_rrule_type(self, cr, uid, ids, rtype, *args, **argv):
416 if rtype == 'none' or not rtype:
417 return {'value': {'rrule': ''}}
418 if rtype == 'custom':
420 rrule = self.pool.get('calendar.custom.rrule')
421 rrulestr = rrule.compute_rule_string(cr, uid, {'freq': rtype.upper(), \
423 return {'value': {'rrule': rrulestr}}
425 def _get_duration(self, cr, uid, ids, name, arg, context):
427 for event in self.browse(cr, uid, ids, context=context):
428 start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
430 if event.date_deadline:
431 end = datetime.strptime(event.date_deadline[:19], "%Y-%m-%d %H:%M:%S")
433 duration = float(diff.days)* 24 + (float(diff.seconds) / 3600)
434 res[event.id] = round(duration, 2)
437 def _set_duration(self, cr, uid, id, name, value, arg, context):
438 event = self.browse(cr, uid, id, context=context)
439 start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
440 end = start + timedelta(hours=value)
441 cr.execute("UPDATE %s set date_deadline='%s' \
442 where id=%s"% (self._table, end.strftime("%Y-%m-%d %H:%M:%S"), id))
446 'id': fields.integer('ID'),
447 'name': fields.char('Description', size=64, required=True),
448 'date': fields.datetime('Date'),
449 'date_deadline': fields.datetime('Deadline'),
450 'duration': fields.function(_get_duration, method=True, \
451 fnct_inv=_set_duration, string='Duration'),
452 'description': fields.text('Your action'),
453 'class': fields.selection([('public', 'Public'), ('private', 'Private'), \
454 ('confidential', 'Confidential')], 'Mark as'),
455 'location': fields.char('Location', size=264, help="Location of Event"),
456 'show_as': fields.selection([('free', 'Free'), \
459 'caldav_url': fields.char('Caldav URL', size=264),
460 'exdate': fields.text('Exception Date/Times', help="This property \
461 defines the list of date/time exceptions for arecurring calendar component."),
462 'exrule': fields.char('Exception Rule', size=352, help="defines a \
463 rule or repeating pattern for anexception to a recurrence set"),
464 'rrule': fields.char('Recurrent Rule', size=124),
465 'rrule_type': fields.selection([('none', 'None'), ('daily', 'Daily'), \
466 ('weekly', 'Weekly'), ('monthly', 'Monthly'), \
467 ('yearly', 'Yearly'), ('custom', 'Custom')], 'Recurrency'),
468 'alarm_id': fields.many2one('res.alarm', 'Alarm'),
469 'caldav_alarm_id': fields.many2one('calendar.alarm', 'Alarm'),
470 'recurrent_uid': fields.integer('Recurrent ID'),
471 'recurrent_id': fields.datetime('Recurrent ID date'),
475 'class': lambda *a: 'public',
476 'show_as': lambda *a: 'busy',
479 def export_cal(self, cr, uid, ids, context={}):
480 ids = map(lambda x: caldav_id2real_id(x), ids)
481 event_data = self.read(cr, uid, ids)
482 event_obj = self.pool.get('basic.calendar.event')
483 ical = event_obj.export_ical(cr, uid, event_data, context={'model': self._name})
484 cal_val = ical.serialize()
485 cal_val = cal_val.replace('"', '').strip()
488 def import_cal(self, cr, uid, data, context={}):
489 file_content = base64.decodestring(data)
490 event_obj = self.pool.get('basic.calendar.event')
491 vals = event_obj.import_ical(cr, uid, file_content)
494 exists, r_id = base_calendar.uid2openobjectid(cr, val['id'], self._name, \
495 val.get('recurrent_id'))
496 if val.has_key('create_date'): val.pop('create_date')
497 val['caldav_url'] = context.get('url') or ''
500 val.update({'recurrent_uid': exists})
501 self.write(cr, uid, [r_id], val)
504 self.write(cr, uid, [exists], val)
507 event_id = self.create(cr, uid, val)
511 def modify_this(self, cr, uid, ids, defaults, context=None, *args):
512 datas = self.read(cr, uid, ids[0], context=context)
513 date = datas.get('date')
515 'recurrent_uid': caldav_id2real_id(datas['id']),
516 'recurrent_id': defaults.get('date'),
517 'rrule_type': 'none',
520 new_id = self.copy(cr, uid, ids[0], default=defaults, context=context)
523 def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100):
526 if isinstance(select, (str, int, long)):
531 if ids and (base_start_date or base_until_date):
532 cr.execute("select m.id, m.rrule, m.date, m.date_deadline, \
533 m.exdate from " + self._table + \
534 " m where m.id in ("\
535 + ','.join(map(lambda x: str(x), ids))+")")
538 for data in cr.dictfetchall():
539 start_date = base_start_date and datetime.strptime(base_start_date, "%Y-%m-%d") or False
540 until_date = base_until_date and datetime.strptime(base_until_date, "%Y-%m-%d") or False
543 event_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
544 if start_date and start_date <= event_date:
545 start_date = event_date
546 if not data['rrule']:
547 if start_date and (event_date < start_date):
549 if until_date and (event_date > until_date):
551 idval = real_id2caldav_id(data['id'], data['date'])
555 exdate = data['exdate'] and data['exdate'].split(',') or []
556 event_obj = self.pool.get('basic.calendar.event')
557 rrule_str = data['rrule']
559 rrule_until_date = False
561 for rule in rrule_str.split(';'):
562 name, value = rule.split('=')
565 value = parser.parse(value)
566 rrule_until_date = parser.parse(value.strftime("%Y-%m-%d"))
567 if until_date and until_date >= rrule_until_date:
568 until_date = rrule_until_date
570 value = until_date.strftime("%Y%m%d%H%M%S")
571 new_rule = '%s=%s' % (name, value)
572 new_rrule_str.append(new_rule)
573 if not is_until and until_date:
574 value = until_date.strftime("%Y%m%d%H%M%S")
576 new_rule = '%s=%s' % (name, value)
577 new_rrule_str.append(new_rule)
578 new_rrule_str = ';'.join(new_rrule_str)
579 start_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
580 rdates = event_obj.get_recurrent_dates(str(new_rrule_str), exdate, start_date)
582 r_date = datetime.strptime(rdate, "%Y-%m-%d %H:%M:%S")
583 if start_date and r_date < start_date:
585 if until_date and r_date > until_date:
587 idval = real_id2caldav_id(data['id'], rdate)
592 if isinstance(select, (str, int, long)):
593 return ids and ids[0] or False
596 def search(self, cr, uid, args, offset=0, limit=100, order=None,
597 context=None, count=False):
598 args_without_date = []
602 if arg[0] not in ('date', unicode('date')):
603 args_without_date.append(arg)
605 if arg[1] in ('>', '>='):
607 elif arg[1] in ('<', '<='):
609 res = super(calendar_event, self).search(cr, uid, args_without_date, offset,
610 limit, order, context, count)
611 return self.get_recurrent_ids(cr, uid, res, start_date, until_date, limit)
614 def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
615 if isinstance(ids, (str, int, long)):
621 id = caldav_id2real_id(id)
622 if not id in new_ids:
624 res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
625 if vals.has_key('alarm_id'):
626 alarm_obj = self.pool.get('res.alarm')
627 alarm_obj.do_alarm_create(cr, uid, new_ids, self._name, 'date')
630 def browse(self, cr, uid, ids, context=None, list_class=None, fields_process={}):
631 if isinstance(ids, (str, int, long)):
635 select = map(lambda x: caldav_id2real_id(x), select)
636 res = super(calendar_event, self).browse(cr, uid, select, context, list_class, fields_process)
637 if isinstance(ids, (str, int, long)):
638 return res and res[0] or False
641 def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'):
642 if isinstance(ids, (str, int, long)):
646 select = map(lambda x: (x, caldav_id2real_id(x)), select)
648 if fields and 'date' not in fields:
649 fields.append('date')
650 for caldav_id, real_id in select:
651 res = super(calendar_event, self).read(cr, uid, real_id, fields=fields, context=context, \
653 ls = caldav_id2real_id(caldav_id, with_date=res.get('duration', 0))
654 if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
656 res['date_deadline'] = ls[2]
657 res['id'] = caldav_id
660 if isinstance(ids, (str, int, long)):
661 return result and result[0] or False
664 def copy(self, cr, uid, id, default=None, context={}):
665 res = super(calendar_event, self).copy(cr, uid, caldav_id2real_id(id), default, context)
666 alarm_obj = self.pool.get('res.alarm')
667 alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
670 def unlink(self, cr, uid, ids, context=None):
673 ls = caldav_id2real_id(id)
674 if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
676 for record in self.read(cr, uid, [caldav_id2real_id(id)], \
677 ['date', 'rrule', 'exdate']):
679 exdate = (record['exdate'] and (record['exdate'] + ',') or '') + \
680 ''.join((re.compile('\d')).findall(date_new)) + 'Z'
681 if record['date'] == date_new:
682 res = self.write(cr, uid, [caldav_id2real_id(id)], {'exdate': exdate})
684 ids = map(lambda x: caldav_id2real_id(x), ids)
685 res = super(calendar_event, self).unlink(cr, uid, caldav_id2real_id(ids))
686 alarm_obj = self.pool.get('res.alarm')
687 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
689 ids = map(lambda x: caldav_id2real_id(x), ids)
690 res = super(calendar_event, self).unlink(cr, uid, ids)
691 alarm_obj = self.pool.get('res.alarm')
692 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
695 def create(self, cr, uid, vals, context={}):
696 res = super(calendar_event, self).create(cr, uid, vals, context)
697 alarm_obj = self.pool.get('res.alarm')
698 alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
703 class calendar_todo(osv.osv):
704 _name = "calendar.todo"
705 _inherit = "calendar.event"
706 _description = "Calendar Task"
708 def _get_date(self, cr, uid, ids, name, arg, context):
710 for event in self.browse(cr, uid, ids, context=context):
711 res[event.id] = event.date_start
714 def _set_date(self, cr, uid, id, name, value, arg, context):
715 event = self.browse(cr, uid, id, context=context)
716 cr.execute("UPDATE %s set date_start='%s' where id=%s" \
717 % (self._table, value, id))
721 'date': fields.function(_get_date, method=True, fnct_inv=_set_date, \
722 string='Duration', store=True, type='datetime'),
723 'duration': fields.integer('Duration'),
728 def import_cal(self, cr, uid, data, context={}):
729 file_content = base64.decodestring(data)
730 todo_obj = self.pool.get('basic.calendar.todo')
731 vals = todo_obj.import_ical(cr, uid, file_content)
733 obj_tm = self.pool.get('res.users').browse(cr, uid, uid, context).company_id.project_time_mode_id
734 if not val.has_key('planned_hours'):
735 # 'Computes duration' in days
736 start = datetime.strptime(val['date'], '%Y-%m-%d %H:%M:%S')
737 end = datetime.strptime(val['date_deadline'], '%Y-%m-%d %H:%M:%S')
739 plan = (diff.seconds/float(86400) + diff.days) * obj_tm.factor
740 val['planned_hours'] = plan
742 # Converts timedelta into hours
743 hours = (val['planned_hours'].seconds / float(3600)) + \
744 (val['planned_hours'].days * 24)
745 val['planned_hours'] = hours
746 exists, r_id = base_calendar.uid2openobjectid(cr, val['id'], self._name, val.get('recurrent_id'))
749 self.write(cr, uid, [exists], val)
751 task_id = self.create(cr, uid, val)
752 return {'count': len(vals)}
754 def export_cal(self, cr, uid, ids, context={}):
755 task_datas = self.read(cr, uid, ids, [], context ={'read': True})
757 for task in task_datas:
758 if task.get('planned_hours', None) and task.get('date_deadline', None):
759 task.pop('planned_hours')
761 todo_obj = self.pool.get('basic.calendar.todo')
762 ical = todo_obj.export_ical(cr, uid, tasks, context={'model': self._name})
763 calendar_val = ical.serialize()
764 calendar_val = calendar_val.replace('"', '').strip()
769 class ir_attachment(osv.osv):
770 _name = 'ir.attachment'
771 _inherit = 'ir.attachment'
773 def search_count(self, cr, user, args, context=None):
776 args1.append(map(lambda x:str(x).split('-')[0], arg))
777 return super(ir_attachment, self).search_count(cr, user, args1, context)
779 def search(self, cr, uid, args, offset=0, limit=None, order=None,
780 context=None, count=False):
782 for i, arg in enumerate(new_args):
783 if arg[0] == 'res_id':
784 new_args[i] = (arg[0], arg[1], caldav_id2real_id(arg[2]))
785 return super(ir_attachment, self).search(cr, uid, new_args, offset=offset,
786 limit=limit, order=order,
787 context=context, count=False)
790 class ir_values(osv.osv):
791 _inherit = 'ir.values'
793 def set(self, cr, uid, key, key2, name, models, value, replace=True, \
794 isobject=False, meta=False, preserve_user=False, company=False):
797 if type(data) in (list, tuple):
798 new_model.append((data[0], caldav_id2real_id(data[1])))
800 new_model.append(data)
801 return super(ir_values, self).set(cr, uid, key, key2, name, new_model, \
802 value, replace, isobject, meta, preserve_user, company)
804 def get(self, cr, uid, key, key2, models, meta=False, context={}, \
805 res_id_req=False, without_user=True, key2_req=True):
808 if type(data) in (list, tuple):
809 new_model.append((data[0], caldav_id2real_id(data[1])))
811 new_model.append(data)
812 return super(ir_values, self).get(cr, uid, key, key2, new_model, \
813 meta, context, res_id_req, without_user, key2_req)
817 class ir_model(osv.osv):
819 _inherit = 'ir.model'
821 def read(self, cr, uid, ids, fields=None, context={},
822 load='_classic_read'):
823 data = super(ir_model, self).read(cr, uid, ids, fields=fields, \
824 context=context, load=load)
827 val['id'] = caldav_id2real_id(val['id'])
832 class virtual_report_spool(web_services.report_spool):
834 def exp_report(self, db, uid, object, ids, datas=None, context=None):
835 if object == 'printscreen.list':
836 return super(virtual_report_spool, self).exp_report(db, uid, \
837 object, ids, datas, context)
840 new_ids.append(caldav_id2real_id(id))
841 datas['id'] = caldav_id2real_id(datas['id'])
842 super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
843 return super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
845 virtual_report_spool()
847 class calendar_custom_rrule(osv.osv):
848 _name = "calendar.custom.rrule"
849 _description = "Custom Recurrency Rule"
852 'freq': fields.selection([('None', 'No Repeat'), \
853 ('secondly', 'Secondly'), \
854 ('minutely', 'Minutely'), \
855 ('hourly', 'Hourly'), \
856 ('daily', 'Daily'), \
857 ('weekly', 'Weekly'), \
858 ('monthly', 'Monthly'), \
859 ('yearly', 'Yearly')], 'Frequency', required=True),
860 'interval': fields.integer('Interval'),
861 'count': fields.integer('Count'),
862 'mo': fields.boolean('Mon'),
863 'tu': fields.boolean('Tue'),
864 'we': fields.boolean('Wed'),
865 'th': fields.boolean('Thu'),
866 'fr': fields.boolean('Fri'),
867 'sa': fields.boolean('Sat'),
868 'su': fields.boolean('Sun'),
869 'select1': fields.selection([('date', 'Date of month'), \
870 ('day', 'Day of month')], 'Option'),
871 'day': fields.integer('Date of month'),
872 'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), \
873 ('WE', 'Wednesday'), ('TH', 'Thursday'), \
874 ('FR', 'Friday'), ('SA', 'Saturday'), \
875 ('SU', 'Sunday')], 'Weekday'),
876 'byday': fields.selection([('1', 'First'), ('2', 'Second'), \
877 ('3', 'Third'), ('4', 'Fourth'), \
878 ('5', 'Fifth'), ('-1', 'Last')], 'By day'),
879 'month_list': fields.selection(months.items(), 'Month'),
880 'end_date': fields.date('Repeat Until')
884 'freq': lambda *x: 'daily',
885 'select1': lambda *x: 'date',
886 'interval': lambda *x: 1,
889 def compute_rule_string(self, cr, uid, datas, context=None, *args):
890 weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
895 # logic for computing rrule string
897 freq = datas.get('freq')
899 obj.write(cr, uid, [res_obj.id], {'rrule': ''})
903 byday = map(lambda x: x.upper(), filter(lambda x: datas.get(x) and x in weekdays, datas))
905 weekstring = ';BYDAY=' + ','.join(byday)
907 elif freq == 'monthly':
908 if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
909 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
910 if datas.get('select1')=='day':
911 monthstring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
912 elif datas.get('select1')=='date':
913 monthstring = ';BYMONTHDAY=' + str(datas.get('day'))
915 elif freq == 'yearly':
916 if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
917 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
918 bymonth = ';BYMONTH=' + str(datas.get('month_list'))
919 if datas.get('select1')=='day':
920 bystring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
921 elif datas.get('select1')=='date':
922 bystring = ';BYMONTHDAY=' + str(datas.get('day'))
923 yearstring = bymonth + bystring
925 if datas.get('end_date'):
926 datas['end_date'] = ''.join((re.compile('\d')).findall(datas.get('end_date'))) + '235959Z'
927 enddate = (datas.get('count') and (';COUNT=' + str(datas.get('count'))) or '') +\
928 ((datas.get('end_date') and (';UNTIL=' + datas.get('end_date'))) or '')
930 rrule_string = 'FREQ=' + freq.upper() + weekstring + ';INTERVAL=' + \
931 str(datas.get('interval')) + enddate + monthstring + yearstring
936 def do_add(self, cr, uid, ids, context={}):
937 datas = self.read(cr, uid, ids)[0]
938 if datas.get('interval') <= 0:
939 raise osv.except_osv(_('Error!'), ("Please select proper Interval"))
942 if not context or not context.get('model'):
945 model = context.get('model')
946 obj = self.pool.get(model)
947 res_obj = obj.browse(cr, uid, context['active_id'])
949 rrule_string = self.compute_rule_string(cr, uid, datas)
950 obj.write(cr, uid, [res_obj.id], {'rrule': rrule_string})
953 calendar_custom_rrule()
955 class res_users(osv.osv):
956 _inherit = 'res.users'
958 def _get_user_avail(self, cr, uid, ids, context=None):
959 current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
961 attendee_obj = self.pool.get('calendar.attendee')
962 attendee_ids = attendee_obj.search(cr, uid, [
963 ('event_date', '<=', current_datetime), ('event_end_date', '<=', current_datetime),
964 ('state', '=', 'accepted'), ('user_id', 'in', ids)
967 result = cr.dictfetchall()
968 for attendee_data in attendee_obj.read(cr, uid, attendee_ids, ['user_id']):
969 user_id = attendee_data['user_id']
971 res.update({user_id:status})
973 #TOCHECK: Delegrated Event
974 #cr.execute("SELECT user_id,'busy' FROM att_del_to_user_rel where user_id = ANY(%s)", (ids,))
975 #res.update(cr.dictfetchall())
977 if user_id not in res:
978 res[user_id] = 'free'
982 def _get_user_avail_fun(self, cr, uid, ids, name, args, context=None):
983 return self._get_user_avail(cr, uid, ids, context=context)
986 'availability': fields.function(_get_user_avail_fun, type='selection', \
987 selection=[('free', 'Free'), ('busy', 'Busy')], \
988 string='Free/Busy', method=True),
992 class invite_attendee_wizard(osv.osv_memory):
993 _name = "caldav.invite.attendee"
994 _description = "Invite Attendees"
997 'type': fields.selection([('internal', 'Internal User'), \
998 ('external', 'External Email'), \
999 ('partner', 'Partner Contacts')], 'Type', required=True),
1000 'user_ids': fields.many2many('res.users', 'invite_user_rel',
1001 'invite_id', 'user_id', 'Users'),
1002 'partner_id': fields.many2one('res.partner', 'Partner'),
1003 'email': fields.char('Email', size=124),
1004 'contact_ids': fields.many2many('res.partner.address', 'invite_contact_rel',
1005 'invite_id', 'contact_id', 'Contacts'),
1008 def do_invite(self, cr, uid, ids, context={}):
1009 datas = self.read(cr, uid, ids)[0]
1010 if not context or not context.get('model'):
1013 model = context.get('model')
1014 obj = self.pool.get(model)
1015 res_obj = obj.browse(cr, uid, context['active_id'])
1016 type = datas.get('type')
1017 att_obj = self.pool.get('calendar.attendee')
1018 vals = {'ref': '%s,%s' % (model, caldav_id2real_id(context['active_id']))}
1019 if type == 'internal':
1020 user_obj = self.pool.get('res.users')
1021 for user_id in datas.get('user_ids', []):
1022 user = user_obj.browse(cr, uid, user_id)
1023 if not user.address_id.email:
1024 raise osv.except_osv(_('Error!'), \
1025 ("User does not have an email Address"))
1026 vals.update({'user_id': user_id,
1027 'email': user.address_id.email})
1028 att_id = att_obj.create(cr, uid, vals)
1029 obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1031 elif type == 'external' and datas.get('email'):
1032 vals.update({'email': datas['email']})
1033 att_id = att_obj.create(cr, uid, vals)
1034 obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1035 elif type == 'partner':
1036 add_obj = self.pool.get('res.partner.address')
1037 for contact in add_obj.browse(cr, uid, datas['contact_ids']):
1039 'partner_address_id': contact.id,
1040 'email': contact.email})
1041 att_id = att_obj.create(cr, uid, vals)
1042 obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1046 def onchange_partner_id(self, cr, uid, ids, partner_id, *args, **argv):
1048 return {'value': {'contact_ids': []}}
1049 cr.execute('select id from res_partner_address \
1050 where partner_id=%s' % (partner_id))
1051 contacts = map(lambda x: x[0], cr.fetchall())
1053 raise osv.except_osv(_('Error!'), \
1054 ("Partner does not have any Contacts"))
1056 return {'value': {'contact_ids': contacts}}
1058 invite_attendee_wizard()
1061 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: