[FIX] stock: put proper action in make picking button
[odoo/odoo.git] / addons / document_ics / document_ics.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
19 #
20 ##############################################################################
21
22 from osv import osv, fields
23 from osv.orm import except_orm
24 import os
25 import StringIO
26 import base64
27 import datetime
28 import time
29 import random
30 import tools
31 import re
32
33 from tools.translate import _
34 from document.nodes import node_content
35
36 from tools.safe_eval import safe_eval
37
38 ICS_TAGS = {
39     'summary':'normal',
40     'uid':'normal' ,
41     'dtstart':'date' ,
42     'dtend':'date' ,
43     'created':'date' ,
44     'dtstamp':'date' ,
45     'last-modified':'normal' ,
46     'url':'normal' ,
47     'attendee':'multiple',
48     'location':'normal',
49     'categories': 'normal',
50     'description':'normal',
51
52     # TODO: handle the 'duration' property
53 }
54
55 ICS_FUNCTIONS = [
56     ('field', 'Use the field'),
57     ('const', 'Expression as constant'),
58     ('hours', 'Interval in hours'),
59     ]
60
61 class document_directory_ics_fields(osv.osv):
62     _name = 'document.directory.ics.fields'
63     _columns = {
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)
69     }
70     _defaults = {
71         'fn': lambda *a: 'field',
72     }
73    
74 document_directory_ics_fields()
75
76 class document_directory_content(osv.osv):
77     _inherit = 'document.directory.content'
78     __rege = re.compile(r'OpenERP-([\w|\.]+)_([0-9]+)@(\w+)$')
79     _columns = {
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')
85     }
86     _defaults = {
87         'ics_domain': lambda *args: '[]'
88     }
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)
92         else:
93             if not content.object_id:
94                 return False
95             mod = self.pool.get(content.object_id.model)
96             uid = node.context.uid
97             fname_fld = content.fname_field or 'id'
98             where = []            
99             if node.domain:
100                 where += eval(node.domain)
101             if nodename:
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):
106                     return False
107                 if not nodename.endswith(suffix):
108                     return False
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)
113             if not resids:
114                 return False
115         
116             res2 = []
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'] }
121                 if fname_fld:
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)
125                 res2.append(n)
126             return res2
127
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)
131         import vobject
132         parsedCal = vobject.readOne(data)        
133         fields = {}
134         funcs = {}
135         fexprs = {}
136         content = self.browse(cr, uid, node.cnt_id, context)
137
138         idomain = {}
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):
145                 # TODO: operator?
146                 idomain[d[0]]=d[2]
147         for n in content.ics_field_ids:
148             fields[n.name] = n.field_id.name and str(n.field_id.name)
149             funcs[n.name] = n.fn
150             fexprs[n.name] = n.expr
151
152         if 'uid' not in fields:
153             print "uid not in ", fields
154             # FIXME: should pass
155             return True
156         for child in parsedCal.getChildren():
157             result = {}
158             uuid = None
159             
160             for event in child.getChildren():
161                 enl = event.name.lower()
162                 if enl =='uid':
163                     uuid = event.value
164                 if not enl in fields:
165                         # print "skip", enl
166                         continue
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')
172         
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)
177                     if not ts_start:
178                         raise Exception("Cannot parse hours (for %s) without %s" % (enl, ntag))
179                     ts_end = event.value
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)
184
185                 # put other functions here..
186                 else:
187                     # print "Unhandled tag in ICS:", enl
188                     pass
189             # end for 
190
191             if not uuid:
192                 print "Skipping cal", child
193                 # FIXME: should pass
194                 continue
195
196             cmodel = content.object_id.model
197             wexpr = False
198             if fields['uid']:
199                 wexpr = [(fields['uid'], '=', uuid.encode('utf8'))]
200             else:
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.
204                 if not wematch:
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)
211                 else:
212                     # TODO: perhaps guess the model from the iCal, is it safe?
213                     pass
214
215                 wexpr = [ ( 'id', '=', wematch.group(2) ) ]
216                 
217             # print "Looking at ", cmodel, " for ", wexpr
218             # print "domain=", idomain
219
220             fobj = self.pool.get(content.object_id.model)
221
222             if not wexpr:
223                 id = False
224             else:
225                 id = fobj.search(cr, uid, wexpr, context=context)
226         
227             if isinstance(id, list):
228                 if len(id) > 1:
229                     raise Exception("Multiple matches found for ICS")
230             if id:                
231                 fobj.write(cr, uid, id, result, context=context)
232             else:
233                 r = idomain.copy()
234                 r.update(result)                
235                 fobj.create(cr, uid, r, context=context)
236
237         return True
238
239     def process_read(self, cr, uid, node, context=None):
240         def ics_datetime(idate, short=False):
241             if short:
242                 return datetime.date.fromtimestamp(time.mktime(time.strptime(idate, '%Y-%m-%d')))
243             else:
244                 return datetime.datetime.strptime(idate, '%Y-%m-%d %H:%M:%S')
245
246         if node.extension != '.ics':
247             return super(document_directory_content, self).process_read(cr, uid, node, context)
248
249         import vobject
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)
257
258         if content.ics_domain:
259             domain = safe_eval(content.ics_domain,ctx)
260         else:
261             domain = []
262         if node.act_id:
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)
278                 else: value = None
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):
284                         value=value.name
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')
291                     if len(value)==10:
292                         value = ics_datetime(value, True)
293                     else:
294                         value = ics_datetime(value)
295                     event.add(field.name).value = value
296         s = cal.serialize()        
297         return s
298 document_directory_content()
299
300 class crm_case(osv.osv):
301     _inherit = 'crm.case'
302     _columns = {
303         'code': fields.char('Calendar Code', size=64),
304         'date_deadline': fields.datetime('Deadline', help="Deadline Date is automatically computed from Start Date + Duration"),
305     }
306
307     _defaults = {
308         'code': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'crm.case'),
309     }
310
311     def copy(self, cr, uid, id, default=None, context=None):
312         """
313         code field must be unique in ICS file
314         """
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)
319
320     def on_change_duration(self, cr, uid, id, date, duration):
321         if not date:
322             return {}
323         start_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S")))
324         if duration >= 0 :
325             end = start_date + datetime.timedelta(hours=duration)
326         if duration < 0:
327             raise osv.except_osv(_('Warning !'),
328                     _('You can not set negative Duration.'))
329
330         res = {'value' : {'date_deadline' : end.strftime('%Y-%m-%d %H:%M:%S')}}
331         return res
332
333 crm_case()
334
335 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
336