Change the type for the sms/emailtext fields
[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         'attachment': fields.char('Save As Attachment Prefix', size=32, help='This is the prefix of the file name the print will be saved as attachement. Keep empty to not save the printed reports')
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         'attachment': lambda *a: False,
142     }
143
144 report_xml()
145
146 class act_window(osv.osv):
147     _name = 'ir.actions.act_window'
148     _table = 'ir_act_window'
149     _sequence = 'ir_actions_id_seq'
150
151     def _views_get_fnc(self, cr, uid, ids, name, arg, context={}):
152         res={}
153         for act in self.browse(cr, uid, ids):
154             res[act.id]=[(view.view_id.id, view.view_mode) for view in act.view_ids]
155             if (not act.view_ids):
156                 modes = act.view_mode.split(',')
157                 find = False
158                 if act.view_id:
159                     res[act.id].append((act.view_id.id, act.view_id.type))
160                 for t in modes:
161                     if act.view_id and (t == act.view_id.type) and not find:
162                         find = True
163                         continue
164                     res[act.id].append((False, t))
165
166                 if 'calendar' not in modes:
167                     mobj = self.pool.get(act.res_model)
168                     if mobj._date_name in mobj._columns:
169                         res[act.id].append((False, 'calendar'))
170         return res
171
172     _columns = {
173         'name': fields.char('Action Name', size=64, translate=True),
174         'type': fields.char('Action Type', size=32, required=True),
175         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
176         'domain': fields.char('Domain Value', size=250),
177         'context': fields.char('Context Value', size=250),
178         'res_model': fields.char('Object', size=64),
179         'src_model': fields.char('Source Object', size=64),
180         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
181         'view_type': fields.selection((('tree','Tree'),('form','Form')),string='Type of view'),
182         'view_mode': fields.char('Mode of view', size=250),
183         'usage': fields.char('Action Usage', size=32),
184         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
185         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
186         'limit': fields.integer('Limit', help='Default limit for the list view'),
187         'auto_refresh': fields.integer('Auto-Refresh',
188             help='Add an auto-refresh on the view'),
189     }
190     _defaults = {
191         'type': lambda *a: 'ir.actions.act_window',
192         'view_type': lambda *a: 'form',
193         'view_mode': lambda *a: 'tree,form',
194         'context': lambda *a: '{}',
195         'limit': lambda *a: 80,
196         'target': lambda *a: 'current',
197         'auto_refresh': lambda *a: 0,
198     }
199 act_window()
200
201 class act_window_view(osv.osv):
202     _name = 'ir.actions.act_window.view'
203     _table = 'ir_act_window_view'
204     _rec_name = 'view_id'
205     _columns = {
206         'sequence': fields.integer('Sequence'),
207         'view_id': fields.many2one('ir.ui.view', 'View'),
208         'view_mode': fields.selection((
209             ('tree', 'Tree'),
210             ('form', 'Form'),
211             ('graph', 'Graph'),
212             ('calendar', 'Calendar')), string='Type of view', required=True),
213         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
214         'multi': fields.boolean('On multiple doc.',
215             help="If set to true, the action will not be displayed on the right toolbar of a form views."),
216     }
217     _defaults = {
218         'multi': lambda *a: False,
219     }
220     _order = 'sequence'
221 act_window_view()
222
223 class act_wizard(osv.osv):
224     _name = 'ir.actions.wizard'
225     _table = 'ir_act_wizard'
226     _sequence = 'ir_actions_id_seq'
227     _columns = {
228         'name': fields.char('Wizard info', size=64, required=True, translate=True),
229         'type': fields.char('Action type', size=32, required=True),
230         'wiz_name': fields.char('Wizard name', size=64, required=True),
231         '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."),
232         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups')
233     }
234     _defaults = {
235         'type': lambda *a: 'ir.actions.wizard',
236         'multi': lambda *a: False,
237     }
238 act_wizard()
239
240 class act_url(osv.osv):
241     _name = 'ir.actions.url'
242     _table = 'ir_act_url'
243     _sequence = 'ir_actions_id_seq'
244     _columns = {
245         'name': fields.char('Action Name', size=64, translate=True),
246         'type': fields.char('Action Type', size=32, required=True),
247         'url': fields.text('Action Url',required=True),
248         'target': fields.selection((
249             ('new', 'New Window'),
250             ('self', 'This Window')),
251             'Action Target', required=True
252         )
253     }
254     _defaults = {
255         'type': lambda *a: 'ir.actions.act_url',
256         'target': lambda *a: 'new'
257     }
258 act_url()
259
260 def model_get(self, cr, uid, context={}):
261     wkf_pool = self.pool.get('workflow')
262     ids = wkf_pool.search(cr, uid, [])
263     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
264     
265     res = []
266     mpool = self.pool.get('ir.model')
267     for osv in osvs:
268         model = osv.get('osv')
269         id = mpool.search(cr, uid, [('model','=',model)])
270         name = mpool.read(cr, uid, id)[0]['name']
271         res.append((model, name))
272         
273     return res
274
275 class ir_model_fields(osv.osv):
276     _inherit = 'ir.model.fields'
277     _rec_name = 'complete_name'
278     _columns = {
279         'complete_name': fields.char('Complete Name', required=True, size=64, select=1),
280     }
281
282     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80):
283
284         def get_fields(cr, uid, field, rel):
285             result = []
286             mobj = self.pool.get('ir.model')
287             id = mobj.search(cr, uid, [('model','=',rel)])
288             
289             obj = self.pool.get('ir.model.fields')
290             ids = obj.search(cr, uid, [('model_id','in',id)])
291             records = obj.read(cr, uid, ids)
292             for record in records:
293                 id = record['id']
294                 fld = field + '/' + record['name']
295                 
296                 result.append((id, fld))
297             return result
298         
299         if not args:
300             args=[]
301         if not context:
302             context={}
303             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
304         
305         if context.get('key') != 'server_action':
306             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
307         
308         result = []
309         obj = self.pool.get('ir.model.fields')
310         ids = obj.search(cr, uid, args)
311         records = obj.read(cr, uid, ids)
312         for record in records:
313             id = record['id']
314             field = record['name']
315             
316             if record['ttype'] == 'many2one':
317                 rel = record['relation']
318                 res = get_fields(cr, uid, field, record['relation'])
319                 for rs in res:
320                     result.append(rs)
321
322             result.append((id, field))
323         
324         for rs in result:
325             obj.write(cr, uid, [rs[0]], {'complete_name':rs[1]})
326         
327         iids = []
328         for rs in result:
329             iids.append(rs[0])
330             
331         result = super(ir_model_fields, self).name_search(cr, uid, name, [('complete_name','ilike',name), ('id','in',iids)], operator, context, limit)
332         
333         return result
334
335 ir_model_fields()
336
337 class server_object_lines(osv.osv):
338     _name = 'ir.server.object.lines'
339     _sequence = 'ir_actions_id_seq'
340     _columns = {
341         'server_id': fields.many2one('ir.actions.server', 'Object Mapping'),
342         'col1': fields.many2one('ir.model.fields', 'Destination', required=True),
343         'value': fields.text('Value', required=True),
344         'type': fields.selection([
345             ('value','Value'),
346             ('equation','Formula')
347         ], 'Type', required=True, size=32, change_default=True),
348     }
349     _defaults = {
350         'type': lambda *a: 'equation',
351     }
352 server_object_lines()
353
354 ##
355 # Actions that are run on the server side
356 #
357 class actions_server(osv.osv):
358     _name = 'ir.actions.server'
359     _table = 'ir_act_server'
360     _sequence = 'ir_actions_id_seq'
361     _columns = {
362         'name': fields.char('Action Name', required=True, size=64),
363         'state': fields.selection([
364             ('python','Python Code'),
365             ('dummy','Dummy'),
366             ('trigger','Trigger'),
367             ('email','Email'),
368             ('sms','SMS'),
369             ('object_create','Create Object'),
370             ('object_write','Write Object'),
371             ('client_action','Client Action'),
372             ('other','Others Actions'),
373         ], 'Action State', required=True, size=32, change_default=True),
374         'code': fields.text('Python Code'),
375         'sequence': fields.integer('Sequence'),
376         'model_id': fields.many2one('ir.model', 'Object', required=True),
377         'trigger_name': fields.char('Trigger Name', size=128),
378         'trigger_obj_id': fields.reference('Trigger On', selection=model_get, size=128),
379         'message': fields.text('Message', translate=True),
380         'address': fields.many2one('ir.model.fields', 'Email / Mobile'),
381         'sms': fields.char('SMS', size=160, translate=True),
382         'child_ids': fields.one2many('ir.actions.actions', 'parent_id', 'Others Actions'),
383         'usage': fields.char('Action Usage', size=32),
384         'type': fields.char('Report Type', size=32, required=True),
385         'srcmodel_id': fields.many2one('ir.model', 'Model'),
386         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Fields Mapping'),
387         'otype': fields.selection([
388             ('copy','Create in Same Model'),
389             ('new','Create in Other Model')
390         ], 'Create Model', size=32, change_default=True),
391     }
392     _defaults = {
393         'state': lambda *a: 'dummy',
394         'type': lambda *a: 'ir.actions.server',
395         'sequence': lambda *a: 0,
396         'code': lambda *a: """# You can use the following variables
397 #    - object
398 #    - object2
399 #    - time
400 #    - cr
401 #    - uid
402 #    - ids
403 # If you plan to return an action, assign: action = {...}
404 """,
405         'otype': lambda *a: 'copy',
406     }
407     
408     def get_field_value(self, cr, uid, action, context):
409         obj_pool = self.pool.get(action.model_id.model)
410         id = context.get('active_id')
411         obj = obj_pool.browse(cr, uid, id)
412         
413         fields = None
414         
415         if '/' in action.address.complete_name:
416             fields = action.address.complete_name.split('/')
417         elif '.' in action.address.complete_name:
418             fields = action.address.complete_name.split('.')
419             
420         for field in fields:
421             try:
422                 obj = getattr(obj, field)
423             except Exception,e :
424                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (match.group()))
425         
426         return obj
427
428     def merge_message(self, cr, uid, keystr, action, context):
429         logger = netsvc.Logger()
430         def merge(match):
431             
432             obj_pool = self.pool.get(action.model_id.model)
433             id = context.get('active_id')
434             obj = obj_pool.browse(cr, uid, id)
435         
436             field = match.group()
437             field = field.replace('[','')
438             field = field.replace(']','')
439             field = field.strip()
440
441             fields = field.split('.')
442             for field in fields:
443                 try:
444                     obj = getattr(obj, field)
445                 except Exception,e :
446                     logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (match.group()))
447             
448             return str(obj)
449         
450         com = re.compile('\[\[(.+?)\]\]')
451         message = com.sub(merge, keystr)
452         return message
453     
454     #
455     # Context should contains:
456     #   ids : original ids
457     #   id  : current id of the object
458     # OUT:
459     #   False : Finnished correctly
460     #   ACTION_ID : Action to launch
461     def run(self, cr, uid, ids, context={}):
462         logger = netsvc.Logger()
463         for action in self.browse(cr, uid, ids, context):
464             if action.state=='python':
465                 localdict = {
466                     'self': self.pool.get(action.model_id.model),
467                     'context': context,
468                     'time': time,
469                     'ids': ids,
470                     'cr': cr,
471                     'uid': uid
472                 }
473                 exec action.code in localdict
474                 if 'action' in localdict:
475                     return localdict['action']
476                 
477             if action.state == 'email':
478                 user = config['email_from']
479                 subject = action.name
480                 
481                 address = self.get_field_value(cr, uid, str(action.message), action, context)
482                 body = self.merge_message(cr, uid, action, context)
483                 
484                 if tools.email_send_attach(user, address, subject, body, debug=False) == True:
485                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (address))
486                 else:
487                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (address))
488
489             if action.state == 'trigger':
490                 wf_service = netsvc.LocalService("workflow")
491                 res = str(action.trigger_obj_id).split(',')
492                 model = res[0]
493                 id = res[1]
494                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
495                 
496             if action.state == 'sms':
497                 #TODO: set the user and password from the system
498                 # for the sms gateway user / password
499                 api_id = ''
500                 text = action.sms
501                 to = self.get_field_value(cr, uid, str(action.message), action, context)
502                 #TODO: Apply message mearge with the field
503                 if tools.sms_send(user, password, api_id, text, to) == True:
504                     logger.notifyChannel('sms', netsvc.LOG_INFO, 'SMS successfully send to : %s' % (action.address))
505                 else:
506                     logger.notifyChannel('sms', netsvc.LOG_ERROR, 'Failed to send SMS to : %s' % (action.address))
507             if action.state == 'other':
508                 localdict = {
509                     'self': self.pool.get(action.model_id.model),
510                     'context': context,
511                     'time': time,
512                     'ids': ids,
513                     'cr': cr,
514                     'uid': uid
515                 }
516                 
517                 for act in action.child_ids:
518                     code = """action = {'model':'%s','type':'%s', %s}""" % (action.model_id.model, act.type, act.usage)
519                     exec code in localdict
520                     if 'action' in localdict:
521                         return localdict['action']
522             if action.state == 'object_write':
523                 res = {}
524                 for exp in action.fields_lines:
525                     euq = exp.value
526                     if exp.type == 'equation':
527                         expr = self.merge_message(cr, uid, euq, action, context)
528                         expr = eval(expr)
529                     else:
530                         expr = exp.value
531                     res[exp.col1.name] = expr
532                 obj_pool = self.pool.get(action.model_id.model)
533                 obj_pool.write(cr, uid, [context.get('active_id')], res)
534                 
535             if action.state == 'object_create':
536                 res = {}
537                 for exp in action.fields_lines:
538                     euq = exp.value
539                     if exp.type == 'equation':
540                         expr = self.merge_message(cr, uid, euq, action, context)
541                         expr = eval(expr)
542                     else:
543                         expr = exp.value
544                     res[exp.col1.name] = expr
545                 
546                 obj_pool = None
547                 if action.state == 'object_create' and action.otype == 'new':
548                     obj_pool = self.pool.get(action.srcmodel_id.model)
549                     obj_pool.create(cr, uid, res)
550                 else:
551                     obj_pool = self.pool.get(action.model_id.model)
552                     id = context.get('active_id')
553                     obj_pool.copy(cr, uid, id, res)
554                 
555         return False
556 actions_server()
557
558 class act_window_close(osv.osv):
559     _name = 'ir.actions.act_window_close'
560     _table = 'ir_actions'
561     _sequence = 'ir_actions_id_seq'
562     _columns = {
563         'name': fields.char('Action Name', size=64, translate=True),
564         'type': fields.char('Action Type', size=32, required=True),
565     }
566     _defaults = {
567         'type': lambda *a: 'ir.actions.act_window_close',
568     }
569 act_window_close()