* change view for the server action
[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
37 class actions(osv.osv):
38     _name = 'ir.actions.actions'
39     _table = 'ir_actions'
40     _columns = {
41         'name': fields.char('Action Name', required=True, size=64),
42         'type': fields.char('Action Type', required=True, size=32),
43         'usage': fields.char('Action Usage', size=32),
44         'parent_id': fields.many2one('ir.actions.server', 'Parent Action'),
45     }
46     _defaults = {
47         'usage': lambda *a: False,
48     }
49 actions()
50
51 class report_custom(osv.osv):
52     _name = 'ir.actions.report.custom'
53     _table = 'ir_act_report_custom'
54     _sequence = 'ir_actions_id_seq'
55     _columns = {
56         'name': fields.char('Report Name', size=64, required=True, translate=True),
57         'type': fields.char('Report Type', size=32, required=True),
58         'model':fields.char('Model', size=64, required=True),
59         'report_id': fields.integer('Report Ref.', required=True),
60         'usage': fields.char('Action Usage', size=32),
61         '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.")
62     }
63     _defaults = {
64         'multi': lambda *a: False,
65         'type': lambda *a: 'ir.actions.report.custom',
66     }
67 report_custom()
68
69 class report_xml(osv.osv):
70
71     def _report_content(self, cursor, user, ids, name, arg, context=None):
72         res = {}
73         for report in self.browse(cursor, user, ids, context=context):
74             data = report[name + '_data']
75             if not data and report[name[:-8]]:
76                 try:
77                     fp = tools.file_open(report[name[:-8]], mode='rb')
78                     data = fp.read()
79                 except:
80                     data = False
81             res[report.id] = data
82         return res
83
84     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
85         self.write(cursor, user, id, {name+'_data': value}, context=context)
86
87     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
88         res = {}
89         for report in self.browse(cursor, user, ids, context=context):
90             if report.report_rml:
91                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
92             else:
93                 res[report.id] = False
94         return res
95
96     _name = 'ir.actions.report.xml'
97     _table = 'ir_act_report_xml'
98     _sequence = 'ir_actions_id_seq'
99     _columns = {
100         'name': fields.char('Name', size=64, required=True, translate=True),
101         'type': fields.char('Report Type', size=32, required=True),
102         'model': fields.char('Model', size=64, required=True),
103         'report_name': fields.char('Internal Name', size=64, required=True),
104         'report_xsl': fields.char('XSL path', size=256),
105         'report_xml': fields.char('XML path', size=256),
106         'report_rml': fields.char('RML path', size=256,
107             help="The .rml path of the file or NULL if the content is in report_rml_content"),
108         'report_sxw': fields.function(_report_sxw, method=True, type='char',
109             string='SXW path'),
110         'report_sxw_content_data': fields.binary('SXW content'),
111         'report_rml_content_data': fields.binary('RML content'),
112         'report_sxw_content': fields.function(_report_content,
113             fnct_inv=_report_content_inv, method=True,
114             type='binary', string='SXW content',),
115         'report_rml_content': fields.function(_report_content,
116             fnct_inv=_report_content_inv, method=True,
117             type='binary', string='RML content'),
118         'auto': fields.boolean('Automatic XSL:RML', required=True),
119         'usage': fields.char('Action Usage', size=32),
120         'header': fields.boolean('Add RML header',
121             help="Add or not the coporate RML header"),
122         'multi': fields.boolean('On multiple doc.',
123             help="If set to true, the action will not be displayed on the right toolbar of a form views."),
124         'report_type': fields.selection([
125             ('pdf', 'pdf'),
126             ('html', 'html'),
127             ('raw', 'raw'),
128             ('sxw', 'sxw'),
129             ], string='Type', required=True),
130         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups')
131         
132     }
133     _defaults = {
134         'type': lambda *a: 'ir.actions.report.xml',
135         'multi': lambda *a: False,
136         'auto': lambda *a: True,
137         'header': lambda *a: True,
138         'report_sxw_content': lambda *a: False,
139         'report_type': lambda *a: 'pdf',
140     }
141
142 report_xml()
143
144 class act_window(osv.osv):
145     _name = 'ir.actions.act_window'
146     _table = 'ir_act_window'
147     _sequence = 'ir_actions_id_seq'
148
149     def _views_get_fnc(self, cr, uid, ids, name, arg, context={}):
150         res={}
151         for act in self.browse(cr, uid, ids):
152             res[act.id]=[(view.view_id.id, view.view_mode) for view in act.view_ids]
153             if (not act.view_ids):
154                 modes = act.view_mode.split(',')
155                 find = False
156                 if act.view_id.id:
157                     res[act.id].append((act.view_id.id, act.view_id.type))
158                 for t in modes:
159                     if act.view_id and (t == act.view_id.type) and not find:
160                         find = True
161                         continue
162                     res[act.id].append((False, t))
163
164                 if 'calendar' not in modes:
165                     mobj = self.pool.get(act.res_model)
166                     if mobj._date_name in mobj._columns:
167                         res[act.id].append((False, 'calendar'))
168         return res
169
170     _columns = {
171         'name': fields.char('Action Name', size=64, translate=True),
172         'type': fields.char('Action Type', size=32, required=True),
173         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
174         'domain': fields.char('Domain Value', size=250),
175         'context': fields.char('Context Value', size=250),
176         'res_model': fields.char('Model', size=64),
177         'src_model': fields.char('Source model', size=64),
178         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
179         'view_type': fields.selection((('tree','Tree'),('form','Form')),string='Type of view'),
180         'view_mode': fields.char('Mode of view', size=250),
181         'usage': fields.char('Action Usage', size=32),
182         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
183         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
184         'limit': fields.integer('Limit', help='Default limit for the list view'),
185         'auto_refresh': fields.integer('Auto-Refresh',
186             help='Add an auto-refresh on the view'),
187     }
188     _defaults = {
189         'type': lambda *a: 'ir.actions.act_window',
190         'view_type': lambda *a: 'form',
191         'view_mode': lambda *a: 'tree,form',
192         'context': lambda *a: '{}',
193         'limit': lambda *a: 80,
194         'target': lambda *a: 'current',
195         'auto_refresh': lambda *a: 0,
196     }
197 act_window()
198
199 class act_window_view(osv.osv):
200     _name = 'ir.actions.act_window.view'
201     _table = 'ir_act_window_view'
202     _rec_name = 'view_id'
203     _columns = {
204         'sequence': fields.integer('Sequence'),
205         'view_id': fields.many2one('ir.ui.view', 'View'),
206         'view_mode': fields.selection((
207             ('tree', 'Tree'),
208             ('form', 'Form'),
209             ('graph', 'Graph'),
210             ('calendar', 'Calendar')), string='Type of view', required=True),
211         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
212         'multi': fields.boolean('On multiple doc.',
213             help="If set to true, the action will not be displayed on the right toolbar of a form views."),
214     }
215     _defaults = {
216         'multi': lambda *a: False,
217     }
218     _order = 'sequence'
219 act_window_view()
220
221 class act_wizard(osv.osv):
222     _name = 'ir.actions.wizard'
223     _table = 'ir_act_wizard'
224     _sequence = 'ir_actions_id_seq'
225     _columns = {
226         'name': fields.char('Wizard info', size=64, required=True, translate=True),
227         'type': fields.char('Action type', size=32, required=True),
228         'wiz_name': fields.char('Wizard name', size=64, required=True),
229         '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."),
230         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups')
231     }
232     _defaults = {
233         'type': lambda *a: 'ir.actions.wizard',
234         'multi': lambda *a: False,
235     }
236 act_wizard()
237
238 class act_url(osv.osv):
239     _name = 'ir.actions.url'
240     _table = 'ir_act_url'
241     _sequence = 'ir_actions_id_seq'
242     _columns = {
243         'name': fields.char('Action Name', size=64, translate=True),
244         'type': fields.char('Action Type', size=32, required=True),
245         'url': fields.text('Action Url',required=True),
246         'target': fields.selection((
247             ('new', 'New Window'),
248             ('self', 'This Window')),
249             'Action Target', required=True
250         )
251     }
252     _defaults = {
253         'type': lambda *a: 'ir.actions.act_url',
254         'target': lambda *a: 'new'
255     }
256 act_url()
257
258 def model_get(self, cr, uid, context={}):
259     wkf_pool = self.pool.get('workflow')
260     ids = wkf_pool.search(cr, uid, [])
261     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
262     
263     res = []
264     mpool = self.pool.get('ir.model')
265     for osv in osvs:
266         model = osv.get('osv')
267         id = mpool.search(cr, uid, [('model','=',model)])
268         name = mpool.read(cr, uid, id)[0]['name']
269         res.append((model, name))
270         
271     return res
272
273 class ir_model_fields(osv.osv):
274     _inherit = 'ir.model.fields'
275     _rec_name = 'complete_name'
276     _columns = {
277         'complete_name': fields.char('Complete Name', required=True, size=64, select=1),
278     }
279
280     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80):
281         
282         print name, args, operator, context
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         result = []
306         obj = self.pool.get('ir.model.fields')
307         ids = obj.search(cr, uid, args)
308         records = obj.read(cr, uid, ids)
309         for record in records:
310             id = record['id']
311             field = record['name']
312             
313             if record['ttype'] == 'many2one':
314                 rel = record['relation']
315                 res = get_fields(cr, uid, field, record['relation'])
316                 for rs in res:
317                     result.append(rs)
318
319             result.append((id, field))
320         
321         for rs in result:
322             obj.write(cr, uid, [rs[0]], {'complete_name':rs[1]})
323         
324         #result = super(ir_model_fields, self).name_search(cr, uid, name, [['complete_name','ilike',name]], operator, context, limit)
325         return result
326
327 ir_model_fields()
328 #
329 # Actions that are run on the server side
330 #
331 class actions_server(osv.osv):
332     _name = 'ir.actions.server'
333     _table = 'ir_act_server'
334     _sequence = 'ir_actions_id_seq'
335     _columns = {
336         'name': fields.char('Action Name', required=True, size=64),
337         'state': fields.selection([
338             ('python','Python Code'),
339             ('dummy','Dummy'),
340             ('trigger','Trigger'),
341             ('email','Email'),
342             ('sms','SMS'),
343             ('object_create','Create Object'),
344             ('object_write','Write Object'),
345             ('client_action','Client Action'),
346             ('other','Others Actions'),
347         ], 'Action State', required=True, size=32, change_default=True),
348         'code': fields.text('Python Code'),
349         'sequence': fields.integer('Sequence'),
350         'model_id': fields.many2one('ir.model', 'Model', required=True),
351         'trigger_name': fields.char('Trigger Name', size=128),
352         'trigger_obj_id': fields.reference('Trigger On', selection=model_get, size=128),
353         #'trigger_object': fields.char('Trigger Object', size=128),
354         #'trigger_object_id': fields.char('Trigger Object ID', size=128),
355         'message': fields.text('Message', translate=True),
356         'address': fields.many2one('ir.model.fields', 'Email From / SMS'),
357         #selection(_get_fields ,'Email / SMS', size=128),
358         'child_ids': fields.one2many('ir.actions.actions', 'parent_id', 'Others Actions'),
359         'usage': fields.char('Action Usage', size=32),
360         'type': fields.char('Report Type', size=32, required=True),
361     }
362     _defaults = {
363         'state': lambda *a: 'dummy',
364         'type': lambda *a: 'ir.actions.server',
365         'sequence': lambda *a: 0,
366         'code': lambda *a: """# You can use the following variables
367 #    - object
368 #    - object2
369 #    - time
370 #    - cr
371 #    - uid
372 #    - ids
373 # If you plan to return an action, assign: action = {...}
374 """
375     }
376
377 #    def on_change_model(self, cr, uid, ids, model_id):
378 #        print '**************** : method called'
379 #        res = {'value' : {'address': [('key1','Email Value One')]} }
380 #        return res
381
382     #
383     # Context should contains:
384     #   ids : original ids
385     #   id  : current id of the object
386     # OUT:
387     #   False : Finnished correctly
388     #   ACTION_ID : Action to launch
389     def run(self, cr, uid, ids, context={}):
390         logger = netsvc.Logger()
391         for action in self.browse(cr, uid, ids, context):
392             if action.state=='python':
393                 localdict = {
394                     'self': self.pool.get(action.model_id.model),
395                     'context': context,
396                     'time': time,
397                     'ids': ids,
398                     'cr': cr,
399                     'uid': uid
400                 }
401                 exec action.code in localdict
402                 if 'action' in localdict:
403                     return localdict['action']
404                 
405             if action.state == 'email':
406                 user = config['email_from']
407                 subject = action.name
408                 
409                 #TODO : Apply Mail merge in to the Content of the Email
410                 print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ',context
411                 
412                 body = action.message
413                 if tools.email_send_attach(user, action.address, subject, body, debug=False) == True:
414                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (action.address))
415                 else:
416                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (action.address))
417
418             if action.state == 'trigger':
419                 wf_service = netsvc.LocalService("workflow")
420                 res = str(action.trigger_obj_id).split(',')
421                 model = res[0]
422                 id = res[1]
423                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
424                 
425             if action.state == 'sms':
426                 #TODO: Apply mearge with the field
427                 if tools.sms_send(user, password, api_id, text, to) == True:
428                     logger.notifyChannel('sms', netsvc.LOG_INFO, 'SMS successfully send to : %s' % (action.address))
429                 else:
430                     logger.notifyChannel('sms', netsvc.LOG_ERROR, 'Failed to send SMS to : %s' % (action.address))
431                     
432             if action.state == 'other':
433                 localdict = {
434                     'self': self.pool.get(action.model_id.model),
435                     'context': context,
436                     'time': time,
437                     'ids': ids,
438                     'cr': cr,
439                     'uid': uid
440                 }
441                 
442                 for act in action.child_ids:
443                     code = """action = {'model':'%s','type':'%s', %s}""" % (action.model_id.model, act.type, act.usage)
444                     exec code in localdict
445                     if 'action' in localdict:
446                         return localdict['action']
447
448         return False
449 actions_server()
450
451 class act_window_close(osv.osv):
452     _name = 'ir.actions.act_window_close'
453     _table = 'ir_actions'
454     _sequence = 'ir_actions_id_seq'
455     _columns = {
456         'name': fields.char('Action Name', size=64, translate=True),
457         'type': fields.char('Action Type', size=32, required=True),
458     }
459     _defaults = {
460         'type': lambda *a: 'ir.actions.act_window_close',
461     }
462 act_window_close()
463
464
465 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
466