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 osv import osv, fields
23 from osv.orm import except_orm
33 from tools.translate import _
34 from document.nodes import node_content
36 from tools.safe_eval import safe_eval
45 'last-modified':'normal' ,
47 'attendee':'multiple',
49 'categories': 'normal',
50 'description':'normal',
52 # TODO: handle the 'duration' property
56 ('field', 'Use the field'),
57 ('const', 'Expression as constant'),
58 ('hours', 'Interval in hours'),
61 class document_directory_ics_fields(osv.osv):
62 _name = 'document.directory.ics.fields'
64 'field_id': fields.many2one('ir.model.fields', 'Open ERP Field'),
65 'name': fields.selection(map(lambda x: (x, x), ICS_TAGS.keys()), 'ICS Value', required=True),
66 'content_id': fields.many2one('document.directory.content', 'Content', required=True, ondelete='cascade'),
67 'expr': fields.char("Expression", size=64),
68 'fn': fields.selection(ICS_FUNCTIONS,'Function',help="Alternate method of calculating the value", required=True)
71 'fn': lambda *a: 'field',
74 document_directory_ics_fields()
76 class document_directory_content(osv.osv):
77 _inherit = 'document.directory.content'
78 __rege = re.compile(r'OpenERP-([\w|\.]+)_([0-9]+)@(\w+)$')
80 'object_id': fields.many2one('ir.model', 'Object', oldname= 'ics_object_id'),
81 'obj_iterate': fields.boolean('Iterate object',help="If set, a separate instance will be created for each record of Object"),
82 'fname_field': fields.char("Filename field",size=16,help="The field of the object used in the filename. Has to be a unique identifier."),
83 'ics_domain': fields.char('Domain', size=64),
84 'ics_field_ids': fields.one2many('document.directory.ics.fields', 'content_id', 'Fields Mapping')
87 'ics_domain': lambda *args: '[]'
89 def _file_get(self, cr, node, nodename, content, context=None):
90 if not content.obj_iterate:
91 return super(document_directory_content, self)._file_get(cr, node, nodename, content)
93 if not content.object_id:
95 mod = self.pool.get(content.object_id.model)
96 uid = node.context.uid
97 fname_fld = content.fname_field or 'id'
100 where += eval(node.domain)
102 # Reverse-parse the nodename to deduce the clause:
103 prefix = (content.prefix or '')
104 suffix = (content.suffix or '') + (content.extension or '')
105 if not nodename.startswith(prefix):
107 if not nodename.endswith(suffix):
109 tval = nodename[len(prefix):0 - len(suffix)]
110 where.append((fname_fld,'=',tval))
111 # print "ics iterate clause:", where
112 resids = mod.search(cr, uid, where, context=context)
117 for ro in mod.read(cr,uid,resids,['id', fname_fld]):
118 tname = (content.prefix or '') + str(ro[fname_fld])
119 tname += (content.suffix or '') + (content.extension or '')
120 dctx2 = { 'active_id': ro['id'] }
122 dctx2['active_'+fname_fld] = ro[fname_fld]
123 n = node_content(tname, node, node.context,content,dctx=dctx2, act_id = ro['id'])
124 n.fill_fields(cr, dctx2)
128 def process_write(self, cr, uid, node, data, context=None):
129 if node.extension != '.ics':
130 return super(document_directory_content, self).process_write(cr, uid, node, data, context)
132 parsedCal = vobject.readOne(data)
136 content = self.browse(cr, uid, node.cnt_id, context)
139 ctx = (context or {})
140 ctx.update(node.context.context.copy())
141 ctx.update(node.dctx)
142 # print "ICS domain: ", type(content.ics_domain), content.ics_domain
143 if content.ics_domain:
144 for d in safe_eval(content.ics_domain,ctx):
147 for n in content.ics_field_ids:
148 fields[n.name] = n.field_id.name and str(n.field_id.name)
150 fexprs[n.name] = n.expr
152 if 'uid' not in fields:
153 print "uid not in ", fields
156 for child in parsedCal.getChildren():
160 for event in child.getChildren():
161 enl = event.name.lower()
164 if not enl in fields:
167 if fields[enl] and funcs[enl] == 'field':
168 if ICS_TAGS[enl]=='normal':
169 result[fields[enl]] = event.value.encode('utf8')
170 elif ICS_TAGS[enl]=='date':
171 result[fields[enl]] = event.value.strftime('%Y-%m-%d %H:%M:%S')
173 # print "Field ",enl, result[fields[enl]]
174 elif fields[enl] and funcs[enl] == 'hours':
175 ntag = fexprs[enl] or 'dtstart'
176 ts_start = child.getChildValue(ntag, default=False)
178 raise Exception("Cannot parse hours (for %s) without %s" % (enl, ntag))
180 assert isinstance(ts_start, datetime.datetime)
181 assert isinstance(ts_end, datetime.datetime)
182 td = ts_end - ts_start
183 result[fields[enl]] = td.days * 24.0 + ( td.seconds / 3600.0)
185 # put other functions here..
187 # print "Unhandled tag in ICS:", enl
192 print "Skipping cal", child
196 cmodel = content.object_id.model
199 wexpr = [(fields['uid'], '=', uuid.encode('utf8'))]
201 # Parse back the uid from 'OpenERP-%s_%s@%s'
202 wematch = self.__rege.match(uuid.encode('utf8'))
203 # TODO: perhaps also add the domain to wexpr, restrict.
205 raise Exception("Cannot locate UID in %s" % uuid)
206 if wematch.group(3) != cr.dbname:
207 raise Exception("Object is not for our db!")
208 if content.object_id:
209 if wematch.group(1) != cmodel:
210 raise Exception("ICS must be at the wrong folder, this one is for %s" % cmodel)
212 # TODO: perhaps guess the model from the iCal, is it safe?
215 wexpr = [ ( 'id', '=', wematch.group(2) ) ]
217 # print "Looking at ", cmodel, " for ", wexpr
218 # print "domain=", idomain
220 fobj = self.pool.get(content.object_id.model)
225 id = fobj.search(cr, uid, wexpr, context=context)
227 if isinstance(id, list):
229 raise Exception("Multiple matches found for ICS")
231 fobj.write(cr, uid, id, result, context=context)
235 fobj.create(cr, uid, r, context=context)
239 def process_read(self, cr, uid, node, context=None):
240 def ics_datetime(idate, short=False):
242 return datetime.date.fromtimestamp(time.mktime(time.strptime(idate, '%Y-%m-%d')))
244 return datetime.datetime.strptime(idate, '%Y-%m-%d %H:%M:%S')
246 if node.extension != '.ics':
247 return super(document_directory_content, self).process_read(cr, uid, node, context)
250 ctx = (context or {})
251 ctx.update(node.context.context.copy())
252 ctx.update(node.dctx)
253 content = self.browse(cr, uid, node.cnt_id, ctx)
254 if not content.object_id:
255 return super(document_directory_content, self).process_read(cr, uid, node, context)
256 obj_class = self.pool.get(content.object_id.model)
258 if content.ics_domain:
259 domain = safe_eval(content.ics_domain,ctx)
263 domain.append(('id','=',node.act_id))
264 # print "process read clause:",domain
265 ids = obj_class.search(cr, uid, domain, context=ctx)
266 cal = vobject.iCalendar()
267 for obj in obj_class.browse(cr, uid, ids):
268 event = cal.add('vevent')
269 # Fix dtstamp et last-modified with create and write date on the object line
270 perm = obj_class.perm_read(cr, uid, [obj.id], context)
271 event.add('created').value = ics_datetime(time.strftime('%Y-%m-%d %H:%M:%S'))
272 event.add('dtstamp').value = ics_datetime(perm[0]['create_date'][:19])
273 if perm[0]['write_date']:
274 event.add('last-modified').value = ics_datetime(perm[0]['write_date'][:19])
275 for field in content.ics_field_ids:
276 if field.field_id.name:
277 value = getattr(obj, field.field_id.name)
279 if (not value) and field.name=='uid':
280 value = 'OpenERP-%s_%s@%s' % (content.object_id.model, str(obj.id), cr.dbname,)
281 # Why? obj_class.write(cr, uid, [obj.id], {field.field_id.name: value})
282 if ICS_TAGS[field.name]=='normal':
283 if type(value)==type(obj):
285 event.add(field.name).value = tools.ustr(value) or ''
286 elif ICS_TAGS[field.name]=='date' and value:
287 if field.name == 'dtstart':
288 date_start = start_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(value , "%Y-%m-%d %H:%M:%S")))
289 if field.name == 'dtend' and ( isinstance(value, float) or field.fn == 'hours'):
290 value = (start_date + datetime.timedelta(hours=value)).strftime('%Y-%m-%d %H:%M:%S')
292 value = ics_datetime(value, True)
294 value = ics_datetime(value)
295 event.add(field.name).value = value
298 document_directory_content()
300 class crm_case(osv.osv):
301 _inherit = 'crm.case'
303 'code': fields.char('Calendar Code', size=64),
304 'date_deadline': fields.datetime('Deadline', help="Deadline Date is automatically computed from Start Date + Duration"),
308 'code': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'crm.case'),
311 def copy(self, cr, uid, id, default=None, context=None):
313 code field must be unique in ICS file
315 if not default: default = {}
316 if not context: context = {}
317 default.update({'code': self.pool.get('ir.sequence').get(cr, uid, 'crm.case'), 'id': False})
318 return super(crm_case, self).copy(cr, uid, id, default, context)
320 def on_change_duration(self, cr, uid, id, date, duration):
323 start_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S")))
325 end = start_date + datetime.timedelta(hours=duration)
327 raise osv.except_osv(_('Warning !'),
328 _('You can not set negative Duration.'))
330 res = {'value' : {'date_deadline' : end.strftime('%Y-%m-%d %H:%M:%S')}}
335 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: