Merging from mga
[odoo/odoo.git] / bin / addons / base / ir / ir_actions.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 from osv import fields,osv
32 import tools
33 import time
34 from tools.config import config
35 import netsvc
36 import re
37
38 class actions(osv.osv):
39     _name = 'ir.actions.actions'
40     _table = 'ir_actions'
41     _columns = {
42         'name': fields.char('Action Name', required=True, size=64),
43         'type': fields.char('Action Type', required=True, size=32),
44         'usage': fields.char('Action Usage', size=32),
45         'parent_id': fields.many2one('ir.actions.server', 'Parent Action'),
46     }
47     _defaults = {
48         'usage': lambda *a: False,
49     }
50 actions()
51
52 class report_custom(osv.osv):
53     _name = 'ir.actions.report.custom'
54     _table = 'ir_act_report_custom'
55     _sequence = 'ir_actions_id_seq'
56     _columns = {
57         'name': fields.char('Report Name', size=64, required=True, translate=True),
58         'type': fields.char('Report Type', size=32, required=True),
59         'model':fields.char('Object', size=64, required=True),
60         'report_id': fields.integer('Report Ref.', required=True),
61         'usage': fields.char('Action Usage', size=32),
62         'multi': fields.boolean('On multiple doc.', help="If set to true, the action will not be displayed on the right toolbar of a form views.")
63     }
64     _defaults = {
65         'multi': lambda *a: False,
66         'type': lambda *a: 'ir.actions.report.custom',
67     }
68 report_custom()
69
70 class report_xml(osv.osv):
71
72     def _report_content(self, cursor, user, ids, name, arg, context=None):
73         res = {}
74         for report in self.browse(cursor, user, ids, context=context):
75             data = report[name + '_data']
76             if not data and report[name[:-8]]:
77                 try:
78                     fp = tools.file_open(report[name[:-8]], mode='rb')
79                     data = fp.read()
80                 except:
81                     data = False
82             res[report.id] = data
83         return res
84
85     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
86         self.write(cursor, user, id, {name+'_data': value}, context=context)
87
88     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
89         res = {}
90         for report in self.browse(cursor, user, ids, context=context):
91             if report.report_rml:
92                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
93             else:
94                 res[report.id] = False
95         return res
96
97     _name = 'ir.actions.report.xml'
98     _table = 'ir_act_report_xml'
99     _sequence = 'ir_actions_id_seq'
100     _columns = {
101         'name': fields.char('Name', size=64, required=True, translate=True),
102         'type': fields.char('Report Type', size=32, required=True),
103         'model': fields.char('Object', size=64, required=True),
104         'report_name': fields.char('Internal Name', size=64, required=True),
105         'report_xsl': fields.char('XSL path', size=256),
106         'report_xml': fields.char('XML path', size=256),
107         'report_rml': fields.char('RML path', size=256,
108             help="The .rml path of the file or NULL if the content is in report_rml_content"),
109         'report_sxw': fields.function(_report_sxw, method=True, type='char',
110             string='SXW path'),
111         'report_sxw_content_data': fields.binary('SXW content'),
112         'report_rml_content_data': fields.binary('RML content'),
113         'report_sxw_content': fields.function(_report_content,
114             fnct_inv=_report_content_inv, method=True,
115             type='binary', string='SXW content',),
116         'report_rml_content': fields.function(_report_content,
117             fnct_inv=_report_content_inv, method=True,
118             type='binary', string='RML content'),
119         'auto': fields.boolean('Automatic XSL:RML', required=True),
120         'usage': fields.char('Action Usage', size=32),
121         'header': fields.boolean('Add RML header',
122             help="Add or not the coporate RML header"),
123         'multi': fields.boolean('On multiple doc.',
124             help="If set to true, the action will not be displayed on the right toolbar of a form views."),
125         'report_type': fields.selection([
126             ('pdf', 'pdf'),
127             ('html', 'html'),
128             ('raw', 'raw'),
129             ('sxw', 'sxw'),
130             ], string='Type', required=True),
131         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups')
132         
133     }
134     _defaults = {
135         'type': lambda *a: 'ir.actions.report.xml',
136         'multi': lambda *a: False,
137         'auto': lambda *a: True,
138         'header': lambda *a: True,
139         'report_sxw_content': lambda *a: False,
140         'report_type': lambda *a: 'pdf',
141     }
142
143 report_xml()
144
145 class act_window(osv.osv):
146     _name = 'ir.actions.act_window'
147     _table = 'ir_act_window'
148     _sequence = 'ir_actions_id_seq'
149
150     def _views_get_fnc(self, cr, uid, ids, name, arg, context={}):
151         res={}
152         for act in self.browse(cr, uid, ids):
153             res[act.id]=[(view.view_id.id, view.view_mode) for view in act.view_ids]
154             if (not act.view_ids):
155                 modes = act.view_mode.split(',')
156                 find = False
157                 if act.view_id.id:
158                     res[act.id].append((act.view_id.id, act.view_id.type))
159                 for t in modes:
160                     if act.view_id and (t == act.view_id.type) and not find:
161                         find = True
162                         continue
163                     res[act.id].append((False, t))
164
165                 if 'calendar' not in modes:
166                     mobj = self.pool.get(act.res_model)
167                     if mobj._date_name in mobj._columns:
168                         res[act.id].append((False, 'calendar'))
169         return res
170
171     _columns = {
172         'name': fields.char('Action Name', size=64, translate=True),
173         'type': fields.char('Action Type', size=32, required=True),
174         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
175         'domain': fields.char('Domain Value', size=250),
176         'context': fields.char('Context Value', size=250),
177         'res_model': fields.char('Object', size=64),
178         'src_model': fields.char('Source Object', size=64),
179         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
180         'view_type': fields.selection((('tree','Tree'),('form','Form')),string='Type of view'),
181         'view_mode': fields.char('Mode of view', size=250),
182         'usage': fields.char('Action Usage', size=32),
183         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
184         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
185         'limit': fields.integer('Limit', help='Default limit for the list view'),
186         'auto_refresh': fields.integer('Auto-Refresh',
187             help='Add an auto-refresh on the view'),
188     }
189     _defaults = {
190         'type': lambda *a: 'ir.actions.act_window',
191         'view_type': lambda *a: 'form',
192         'view_mode': lambda *a: 'tree,form',
193         'context': lambda *a: '{}',
194         'limit': lambda *a: 80,
195         'target': lambda *a: 'current',
196         'auto_refresh': lambda *a: 0,
197     }
198 act_window()
199
200 class act_window_view(osv.osv):
201     _name = 'ir.actions.act_window.view'
202     _table = 'ir_act_window_view'
203     _rec_name = 'view_id'
204     _columns = {
205         'sequence': fields.integer('Sequence'),
206         'view_id': fields.many2one('ir.ui.view', 'View'),
207         'view_mode': fields.selection((
208             ('tree', 'Tree'),
209             ('form', 'Form'),
210             ('graph', 'Graph'),
211             ('calendar', 'Calendar')), string='Type of view', required=True),
212         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
213         'multi': fields.boolean('On multiple doc.',
214             help="If set to true, the action will not be displayed on the right toolbar of a form views."),
215     }
216     _defaults = {
217         'multi': lambda *a: False,
218     }
219     _order = 'sequence'
220 act_window_view()
221
222 class act_wizard(osv.osv):
223     _name = 'ir.actions.wizard'
224     _table = 'ir_act_wizard'
225     _sequence = 'ir_actions_id_seq'
226     _columns = {
227         'name': fields.char('Wizard info', size=64, required=True, translate=True),
228         'type': fields.char('Action type', size=32, required=True),
229         'wiz_name': fields.char('Wizard name', size=64, required=True),
230         'multi': fields.boolean('Action on multiple doc.', help="If set to true, the wizard will not be displayed on the right toolbar of a form views."),
231         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups')
232     }
233     _defaults = {
234         'type': lambda *a: 'ir.actions.wizard',
235         'multi': lambda *a: False,
236     }
237 act_wizard()
238
239 class act_url(osv.osv):
240     _name = 'ir.actions.url'
241     _table = 'ir_act_url'
242     _sequence = 'ir_actions_id_seq'
243     _columns = {
244         'name': fields.char('Action Name', size=64, translate=True),
245         'type': fields.char('Action Type', size=32, required=True),
246         'url': fields.text('Action Url',required=True),
247         'target': fields.selection((
248             ('new', 'New Window'),
249             ('self', 'This Window')),
250             'Action Target', required=True
251         )
252     }
253     _defaults = {
254         'type': lambda *a: 'ir.actions.act_url',
255         'target': lambda *a: 'new'
256     }
257 act_url()
258
259 def model_get(self, cr, uid, context={}):
260     wkf_pool = self.pool.get('workflow')
261     ids = wkf_pool.search(cr, uid, [])
262     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
263     
264     res = []
265     mpool = self.pool.get('ir.model')
266     for osv in osvs:
267         model = osv.get('osv')
268         id = mpool.search(cr, uid, [('model','=',model)])
269         name = mpool.read(cr, uid, id)[0]['name']
270         res.append((model, name))
271         
272     return res
273
274 class ir_model_fields(osv.osv):
275     _inherit = 'ir.model.fields'
276     _rec_name = 'complete_name'
277     _columns = {
278         'complete_name': fields.char('Complete Name', required=True, size=64, select=1),
279     }
280
281     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80):
282
283         def get_fields(cr, uid, field, rel):
284             result = []
285             mobj = self.pool.get('ir.model')
286             id = mobj.search(cr, uid, [('model','=',rel)])
287             
288             obj = self.pool.get('ir.model.fields')
289             ids = obj.search(cr, uid, [('model_id','in',id)])
290             records = obj.read(cr, uid, ids)
291             for record in records:
292                 id = record['id']
293                 fld = field + '/' + record['name']
294                 
295                 result.append((id, fld))
296             return result
297         
298         if not args:
299             args=[]
300         if not context:
301             context={}
302             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
303         
304         if context.get('key') != 'server_action':
305             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
306         
307         result = []
308         obj = self.pool.get('ir.model.fields')
309         ids = obj.search(cr, uid, args)
310         records = obj.read(cr, uid, ids)
311         for record in records:
312             id = record['id']
313             field = record['name']
314             
315             if record['ttype'] == 'many2one':
316                 rel = record['relation']
317                 res = get_fields(cr, uid, field, record['relation'])
318                 for rs in res:
319                     result.append(rs)
320
321             result.append((id, field))
322         
323         for rs in result:
324             obj.write(cr, uid, [rs[0]], {'complete_name':rs[1]})
325         
326         iids = []
327         for rs in result:
328             iids.append(rs[0])
329             
330         result = super(ir_model_fields, self).name_search(cr, uid, name, [('complete_name','ilike',name), ('id','in',iids)], operator, context, limit)
331         
332         return result
333
334 ir_model_fields()
335
336 class server_object_lines(osv.osv):
337     _name = 'ir.server.object.lines'
338     _sequence = 'ir_actions_id_seq'
339     _columns = {
340         'server_id': fields.many2one('ir.actions.server', 'Object Mapping'),
341         'col1': fields.many2one('ir.model.fields', 'Destination', required=True),
342         'value': fields.text('Value', required=True),
343         'type': fields.selection([
344             ('value','Value'),
345             ('equation','Formula')
346         ], 'Type', required=True, size=32, change_default=True),
347     }
348     _defaults = {
349         'type': lambda *a: 'equation',
350     }
351 server_object_lines()
352
353 ##
354 # Actions that are run on the server side
355 #
356 class actions_server(osv.osv):
357     _name = 'ir.actions.server'
358     _table = 'ir_act_server'
359     _sequence = 'ir_actions_id_seq'
360     _columns = {
361         'name': fields.char('Action Name', required=True, size=64),
362         'state': fields.selection([
363             ('python','Python Code'),
364             ('dummy','Dummy'),
365             ('trigger','Trigger'),
366             ('email','Email'),
367             ('sms','SMS'),
368             ('object_create','Create Object'),
369             ('object_write','Write Object'),
370             ('client_action','Client Action'),
371             ('other','Others Actions'),
372         ], 'Action State', required=True, size=32, change_default=True),
373         'code': fields.text('Python Code'),
374         'sequence': fields.integer('Sequence'),
375         'model_id': fields.many2one('ir.model', 'Object', required=True),
376         'trigger_name': fields.char('Trigger Name', size=128),
377         'trigger_obj_id': fields.reference('Trigger On', selection=model_get, size=128),
378         'message': fields.text('Message', translate=True),
379         'address': fields.many2one('ir.model.fields', 'Email From / SMS'),
380         'child_ids': fields.one2many('ir.actions.actions', 'parent_id', 'Others Actions'),
381         'usage': fields.char('Action Usage', size=32),
382         'type': fields.char('Report Type', size=32, required=True),
383         'srcmodel_id': fields.many2one('ir.model', 'Model'),
384         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Fields Mapping'),
385         'otype': fields.selection([
386             ('copy','Create in Same Model'),
387             ('new','Create in Other Model')
388         ], 'Create Model', required=True, size=32, change_default=True),
389     }
390     _defaults = {
391         'state': lambda *a: 'dummy',
392         'type': lambda *a: 'ir.actions.server',
393         'sequence': lambda *a: 0,
394         'code': lambda *a: """# You can use the following variables
395 #    - object
396 #    - object2
397 #    - time
398 #    - cr
399 #    - uid
400 #    - ids
401 # If you plan to return an action, assign: action = {...}
402 """
403     }
404     
405     def get_field_value(self, cr, uid, action, context):
406         obj_pool = self.pool.get(action.model_id.model)
407         id = context.get('active_id')
408         obj = obj_pool.browse(cr, uid, id)
409         
410         fields = None
411         
412         if '/' in action.address.complete_name:
413             fields = action.address.complete_name.split('/')
414         elif '.' in action.address.complete_name:
415             fields = action.address.complete_name.split('.')
416             
417         for field in fields:
418             try:
419                 obj = getattr(obj, field)
420             except Exception,e :
421                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (match.group()))
422         
423         return obj
424
425     def merge_message(self, cr, uid, keystr, action, context):
426         logger = netsvc.Logger()
427         def merge(match):
428             
429             obj_pool = self.pool.get(action.model_id.model)
430             id = context.get('active_id')
431             obj = obj_pool.browse(cr, uid, id)
432         
433             field = match.group()
434             field = field.replace('[','')
435             field = field.replace(']','')
436             field = field.strip()
437
438             fields = field.split('.')
439             for field in fields:
440                 try:
441                     obj = getattr(obj, field)
442                 except Exception,e :
443                     logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (match.group()))
444             
445             return str(obj)
446         
447         com = re.compile('\[\[(.+?)\]\]')
448         message = com.sub(merge, keystr)
449         return message
450     
451     #
452     # Context should contains:
453     #   ids : original ids
454     #   id  : current id of the object
455     # OUT:
456     #   False : Finnished correctly
457     #   ACTION_ID : Action to launch
458     def run(self, cr, uid, ids, context={}):
459         logger = netsvc.Logger()
460         for action in self.browse(cr, uid, ids, context):
461             if action.state=='python':
462                 localdict = {
463                     'self': self.pool.get(action.model_id.model),
464                     'context': context,
465                     'time': time,
466                     'ids': ids,
467                     'cr': cr,
468                     'uid': uid
469                 }
470                 exec action.code in localdict
471                 if 'action' in localdict:
472                     return localdict['action']
473                 
474             if action.state == 'email':
475                 user = config['email_from']
476                 subject = action.name
477                 
478                 address = self.get_field_value(cr, uid, str(action.message), action, context)
479                 body = self.merge_message(cr, uid, action, context)
480                 
481                 if tools.email_send_attach(user, address, subject, body, debug=False) == True:
482                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (address))
483                 else:
484                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (address))
485
486             if action.state == 'trigger':
487                 wf_service = netsvc.LocalService("workflow")
488                 res = str(action.trigger_obj_id).split(',')
489                 model = res[0]
490                 id = res[1]
491                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
492                 
493             if action.state == 'sms':
494                 #TODO: Apply mearge with the field
495                 if tools.sms_send(user, password, api_id, text, to) == True:
496                     logger.notifyChannel('sms', netsvc.LOG_INFO, 'SMS successfully send to : %s' % (action.address))
497                 else:
498                     logger.notifyChannel('sms', netsvc.LOG_ERROR, 'Failed to send SMS to : %s' % (action.address))
499                     
500             if action.state == 'other':
501                 localdict = {
502                     'self': self.pool.get(action.model_id.model),
503                     'context': context,
504                     'time': time,
505                     'ids': ids,
506                     'cr': cr,
507                     'uid': uid
508                 }
509                 
510                 for act in action.child_ids:
511                     code = """action = {'model':'%s','type':'%s', %s}""" % (action.model_id.model, act.type, act.usage)
512                     exec code in localdict
513                     if 'action' in localdict:
514                         return localdict['action']
515             if action.state == 'object_write':
516                 res = {}
517                 for exp in action.fields_lines:
518                     euq = exp.value
519                     if exp.type == 'equation':
520                         expr = self.merge_message(cr, uid, euq, action, context)
521                         expr = eval(expr)
522                     else:
523                         expr = exp.value
524                     res[exp.col1.name] = expr
525                 obj_pool = self.pool.get(action.model_id.model)
526                 obj_pool.write(cr, uid, [context.get('active_id')], res)
527                 
528             if action.state == 'object_create':
529                 res = {}
530                 for exp in action.fields_lines:
531                     euq = exp.value
532                     if exp.type == 'equation':
533                         expr = self.merge_message(cr, uid, euq, action, context)
534                         expr = eval(expr)
535                     else:
536                         expr = exp.value
537                     res[exp.col1.name] = expr
538                 obj_pool = self.pool.get(action.model_id.model)
539                 id = context.get('active_id')
540                 obj_pool.copy(cr, uid, id, res)
541                 
542         return False
543 actions_server()
544
545 class act_window_close(osv.osv):
546     _name = 'ir.actions.act_window_close'
547     _table = 'ir_actions'
548     _sequence = 'ir_actions_id_seq'
549     _columns = {
550         'name': fields.char('Action Name', size=64, translate=True),
551         'type': fields.char('Action Type', size=32, required=True),
552     }
553     _defaults = {
554         'type': lambda *a: 'ir.actions.act_window_close',
555     }
556 act_window_close()
557
558
559 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
560