7a07ca40ef88aa2919e5d266d8e5a59e623fe17e
[odoo/odoo.git] / bin / addons / base / ir / ir_actions.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 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 fields,osv
23 from tools.safe_eval import safe_eval as eval
24 import tools
25 import time
26 from tools.config import config
27 from tools.translate import _
28 import netsvc
29 import logging
30 import re
31 import copy
32 import os
33 from xml import dom
34 from report.report_sxw import report_sxw, report_rml
35
36 class actions(osv.osv):
37     _name = 'ir.actions.actions'
38     _table = 'ir_actions'
39     _order = 'name'
40     _columns = {
41         'name': fields.char('Action Name', required=True, size=64),
42         'type': fields.char('Action Type', required=True, size=32,readonly=True),
43         'usage': fields.char('Action Usage', size=32),
44     }
45     _defaults = {
46         'usage': lambda *a: False,
47     }
48 actions()
49
50
51 class report_xml(osv.osv):
52
53     def _report_content(self, cursor, user, ids, name, arg, context=None):
54         res = {}
55         for report in self.browse(cursor, user, ids, context=context):
56             data = report[name + '_data']
57             if not data and report[name[:-8]]:
58                 fp = None
59                 try:
60                     fp = tools.file_open(report[name[:-8]], mode='rb')
61                     data = fp.read()
62                 except:
63                     data = False
64                 finally:
65                     if fp:
66                         fp.close()
67             res[report.id] = data
68         return res
69
70     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
71         self.write(cursor, user, id, {name+'_data': value}, context=context)
72
73     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
74         res = {}
75         for report in self.browse(cursor, user, ids, context=context):
76             if report.report_rml:
77                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
78             else:
79                 res[report.id] = False
80         return res
81
82     def register_all(self, cr):
83         """Report registration handler that may be overridden by subclasses to
84            add their own kinds of report services.
85            Loads all reports with no manual loaders (auto==True) and
86            registers the appropriate services to implement them.
87         """
88         opj = os.path.join
89         cr.execute("SELECT * FROM ir_act_report_xml WHERE auto=%s ORDER BY id", (True,))
90         result = cr.dictfetchall()
91         svcs = netsvc.Service._services
92         for r in result:
93             if svcs.has_key('report.'+r['report_name']):
94                 continue
95             if r['report_rml'] or r['report_rml_content_data']:
96                 report_sxw('report.'+r['report_name'], r['model'],
97                         opj('addons',r['report_rml'] or '/'), header=r['header'])
98             if r['report_xsl']:
99                 report_rml('report.'+r['report_name'], r['model'],
100                         opj('addons',r['report_xml']),
101                         r['report_xsl'] and opj('addons',r['report_xsl']))
102
103     _name = 'ir.actions.report.xml'
104     _table = 'ir_act_report_xml'
105     _sequence = 'ir_actions_id_seq'
106     _order = 'name'
107     _columns = {
108         'name': fields.char('Name', size=64, required=True, translate=True),
109         'model': fields.char('Object', size=64, required=True),
110         'type': fields.char('Action Type', size=32, required=True),
111         'report_name': fields.char('Service Name', size=64, required=True),
112         'usage': fields.char('Action Usage', size=32),
113         'report_type': fields.char('Report Type', size=32, required=True, help="Report Type, e.g. pdf, html, raw, sxw, odt, html2html, mako2html, ..."),
114         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),
115         'multi': fields.boolean('On multiple doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view."),
116         'attachment': fields.char('Save As Attachment Prefix', size=128, help='This is the filename of the attachment used to store the printing result. Keep empty to not save the printed reports. You can use a python expression with the object and time variables.'),
117         'attachment_use': fields.boolean('Reload from Attachment', help='If you check this, then the second time the user prints with same attachment name, it returns the previous report.'),
118         'auto': fields.boolean('Custom python parser', required=True),
119
120         'header': fields.boolean('Add RML header', help="Add or not the coporate RML header"),
121
122         'report_xsl': fields.char('XSL path', size=256),
123         'report_xml': fields.char('XML path', size=256, help=''),
124
125         # Pending deprecation... to be replaced by report_file as this object will become the default report object (not so specific to RML anymore)
126         'report_rml': fields.char('Main report file path', size=256, help="The path to the main report file (depending on Report Type) or NULL if the content is in another data field"),
127         # temporary related field as report_rml is pending deprecation - this field will replace report_rml after v6.0
128         'report_file': fields.related('report_rml', type="char", size=256, required=False, readonly=False, string='Report file', help="The path to the main report file (depending on Report Type) or NULL if the content is in another field", store=True),
129
130         'report_sxw': fields.function(_report_sxw, method=True, type='char', string='SXW path'),
131         'report_sxw_content_data': fields.binary('SXW content'),
132         'report_rml_content_data': fields.binary('RML content'),
133         'report_sxw_content': fields.function(_report_content, fnct_inv=_report_content_inv, method=True, type='binary', string='SXW content',),
134         'report_rml_content': fields.function(_report_content, fnct_inv=_report_content_inv, method=True, type='binary', string='RML content'),
135
136     }
137     _defaults = {
138         'type': lambda *a: 'ir.actions.report.xml',
139         'multi': lambda *a: False,
140         'auto': lambda *a: True,
141         'header': lambda *a: True,
142         'report_sxw_content': lambda *a: False,
143         'report_type': lambda *a: 'pdf',
144         'attachment': lambda *a: False,
145     }
146
147 report_xml()
148
149 class act_window(osv.osv):
150     _name = 'ir.actions.act_window'
151     _table = 'ir_act_window'
152     _sequence = 'ir_actions_id_seq'
153     _order = 'name'
154
155     def _check_model(self, cr, uid, ids, context=None):
156         for action in self.browse(cr, uid, ids, context):
157             if not self.pool.get(action.res_model):
158                 return False
159             if action.src_model and not self.pool.get(action.src_model):
160                 return False
161         return True
162
163     def _invalid_model_msg(self, cr, uid, ids, context=None):
164         return _('Invalid model name in the action definition.')
165     
166     _constraints = [
167         (_check_model, _invalid_model_msg, ['res_model','src_model'])
168     ]
169
170     def _views_get_fnc(self, cr, uid, ids, name, arg, context=None):
171         res={}
172         for act in self.browse(cr, uid, ids):
173             res[act.id]=[(view.view_id.id, view.view_mode) for view in act.view_ids]
174             modes = act.view_mode.split(',')
175             if len(modes)>len(act.view_ids):
176                 find = False
177                 if act.view_id:
178                     res[act.id].append((act.view_id.id, act.view_id.type))
179                 for t in modes[len(act.view_ids):]:
180                     if act.view_id and (t == act.view_id.type) and not find:
181                         find = True
182                         continue
183                     res[act.id].append((False, t))
184         return res
185
186     def _search_view(self, cr, uid, ids, name, arg, context=None):
187         res = {}
188         def encode(s):
189             if isinstance(s, unicode):
190                 return s.encode('utf8')
191             return s
192         for act in self.browse(cr, uid, ids, context=context):
193             fields_from_fields_get = self.pool.get(act.res_model).fields_get(cr, uid, context=context)
194             search_view_id = False
195             if act.search_view_id:
196                 search_view_id = act.search_view_id.id
197             else:
198                 res_view = self.pool.get('ir.ui.view').search(cr, uid, 
199                         [('model','=',act.res_model),('type','=','search'),
200                         ('inherit_id','=',False)], context=context)
201                 if res_view:
202                     search_view_id = res_view[0]
203             if search_view_id:
204                 field_get = self.pool.get(act.res_model).fields_view_get(cr, uid, search_view_id,
205                             'search', context)
206                 fields_from_fields_get.update(field_get['fields'])
207                 field_get['fields'] = fields_from_fields_get
208                 res[act.id] = str(field_get)
209             else:
210                 def process_child(node, new_node, doc):
211                     for child in node.childNodes:
212                         if child.localName=='field' and child.hasAttribute('select') \
213                                 and child.getAttribute('select')=='1':
214                             if child.childNodes:
215                                 fld = doc.createElement('field')
216                                 for attr in child.attributes.keys():
217                                     fld.setAttribute(attr, child.getAttribute(attr))
218                                 new_node.appendChild(fld)
219                             else:
220                                 new_node.appendChild(child)
221                         elif child.localName in ('page','group','notebook'):
222                             process_child(child, new_node, doc)
223
224                 form_arch = self.pool.get(act.res_model).fields_view_get(cr, uid, False, 'form', context)
225                 dom_arc = dom.minidom.parseString(encode(form_arch['arch']))
226                 new_node = copy.deepcopy(dom_arc)
227                 for child_node in new_node.childNodes[0].childNodes:
228                     if child_node.nodeType == child_node.ELEMENT_NODE:
229                         new_node.childNodes[0].removeChild(child_node)
230                 process_child(dom_arc.childNodes[0],new_node.childNodes[0],dom_arc)
231
232                 form_arch['arch'] = new_node.toxml()
233                 form_arch['fields'].update(fields_from_fields_get)
234                 res[act.id] = str(form_arch)
235         return res
236
237     def _get_help_status(self, cr, uid, ids, name, arg, context=None):
238         activate_tips = self.pool.get('res.users').browse(cr, uid, uid).menu_tips
239         return dict([(id, activate_tips) for id in ids])
240
241     _columns = {
242         'name': fields.char('Action Name', size=64, translate=True),
243         'type': fields.char('Action Type', size=32, required=True),
244         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
245         'domain': fields.char('Domain Value', size=250,
246             help="Optional domain filtering of the destination data, as a Python expression"),
247         'context': fields.char('Context Value', size=250, required=True,
248             help="Context dictionary as Python expression, empty by default (Default: {})"),
249         'res_model': fields.char('Object', size=64, required=True,
250             help="Model name of the object to open in the view window"),
251         'src_model': fields.char('Source Object', size=64,
252             help="Optional model name of the objects on which this action should be visible"),
253         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
254         'view_type': fields.selection((('tree','Tree'),('form','Form')), string='View Type', required=True,
255             help="View type: set to 'tree' for a hierarchical tree view, or 'form' for other views"),
256         'view_mode': fields.char('View Mode', size=250, required=True,
257             help="Comma-separated list of allowed view modes, such as 'form', 'tree', 'calendar', etc. (Default: tree,form)"),
258         'usage': fields.char('Action Usage', size=32),
259         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
260         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
261         'limit': fields.integer('Limit', help='Default limit for the list view'),
262         'auto_refresh': fields.integer('Auto-Refresh',
263             help='Add an auto-refresh on the view'),
264         'groups_id': fields.many2many('res.groups', 'ir_act_window_group_rel',
265             'act_id', 'gid', 'Groups'),
266         'search_view_id': fields.many2one('ir.ui.view', 'Search View Ref.'),
267         'filter': fields.boolean('Filter'),
268         'auto_search':fields.boolean('Auto Search'),
269         'search_view' : fields.function(_search_view, type='text', method=True, string='Search View'),
270         'menus': fields.char('Menus', size=4096),
271         'help': fields.text('Action description',
272             help='Optional help text for the users with a description of the target view, such as its usage and purpose.',
273             translate=True),
274         'display_menu_tip':fields.function(_get_help_status, type='boolean', method=True, string='Display Menu Tips',
275             help='It gives the status if the tip has to be displayed or not when a user executes an action'),
276         'multi': fields.boolean('Action on Multiple Doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view"),
277     }
278
279     _defaults = {
280         'type': lambda *a: 'ir.actions.act_window',
281         'view_type': lambda *a: 'form',
282         'view_mode': lambda *a: 'tree,form',
283         'context': lambda *a: '{}',
284         'limit': lambda *a: 80,
285         'target': lambda *a: 'current',
286         'auto_refresh': lambda *a: 0,
287         'auto_search':lambda *a: True,
288         'multi': False,
289     }
290
291     def for_xml_id(self, cr, uid, module, xml_id, context=None):
292         """ Returns the act_window object created for the provided xml_id
293
294         :param module: the module the act_window originates in
295         :param xml_id: the namespace-less id of the action (the @id
296                        attribute from the XML file)
297         :return: A read() view of the ir.actions.act_window
298         """
299         dataobj = self.pool.get('ir.model.data')
300         data_id = dataobj._get_id (cr, 1, module, xml_id)
301         res_id = dataobj.browse(cr, uid, data_id, context).res_id
302         return self.read(cr, uid, res_id, [], context)
303
304 act_window()
305
306 class act_window_view(osv.osv):
307     _name = 'ir.actions.act_window.view'
308     _table = 'ir_act_window_view'
309     _rec_name = 'view_id'
310     _columns = {
311         'sequence': fields.integer('Sequence'),
312         'view_id': fields.many2one('ir.ui.view', 'View'),
313         'view_mode': fields.selection((
314             ('tree', 'Tree'),
315             ('form', 'Form'),
316             ('graph', 'Graph'),
317             ('calendar', 'Calendar'),
318             ('gantt', 'Gantt')), string='View Type', required=True),
319         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
320         'multi': fields.boolean('On Multiple Doc.',
321             help="If set to true, the action will not be displayed on the right toolbar of a form view."),
322     }
323     _defaults = {
324         'multi': lambda *a: False,
325     }
326     _order = 'sequence'
327 act_window_view()
328
329 class act_wizard(osv.osv):
330     _name = 'ir.actions.wizard'
331     _inherit = 'ir.actions.actions'
332     _table = 'ir_act_wizard'
333     _sequence = 'ir_actions_id_seq'
334     _order = 'name'
335     _columns = {
336         'name': fields.char('Wizard Info', size=64, required=True, translate=True),
337         'type': fields.char('Action Type', size=32, required=True),
338         'wiz_name': fields.char('Wizard Name', size=64, required=True),
339         '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 view."),
340         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups'),
341         'model': fields.char('Object', size=64),
342     }
343     _defaults = {
344         'type': lambda *a: 'ir.actions.wizard',
345         'multi': lambda *a: False,
346     }
347 act_wizard()
348
349 class act_url(osv.osv):
350     _name = 'ir.actions.url'
351     _table = 'ir_act_url'
352     _sequence = 'ir_actions_id_seq'
353     _order = 'name'
354     _columns = {
355         'name': fields.char('Action Name', size=64, translate=True),
356         'type': fields.char('Action Type', size=32, required=True),
357         'url': fields.text('Action URL',required=True),
358         'target': fields.selection((
359             ('new', 'New Window'),
360             ('self', 'This Window')),
361             'Action Target', required=True
362         )
363     }
364     _defaults = {
365         'type': lambda *a: 'ir.actions.act_url',
366         'target': lambda *a: 'new'
367     }
368 act_url()
369
370 def model_get(self, cr, uid, context=None):
371     wkf_pool = self.pool.get('workflow')
372     ids = wkf_pool.search(cr, uid, [])
373     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
374
375     res = []
376     mpool = self.pool.get('ir.model')
377     for osv in osvs:
378         model = osv.get('osv')
379         id = mpool.search(cr, uid, [('model','=',model)])
380         name = mpool.read(cr, uid, id)[0]['name']
381         res.append((model, name))
382
383     return res
384
385 class ir_model_fields(osv.osv):
386     _inherit = 'ir.model.fields'
387     _rec_name = 'field_description'
388     _columns = {
389         'complete_name': fields.char('Complete Name', size=64, select=1),
390     }
391 ir_model_fields()
392
393 class server_object_lines(osv.osv):
394     _name = 'ir.server.object.lines'
395     _sequence = 'ir_actions_id_seq'
396     _columns = {
397         'server_id': fields.many2one('ir.actions.server', 'Object Mapping'),
398         'col1': fields.many2one('ir.model.fields', 'Destination', required=True),
399         'value': fields.text('Value', required=True),
400         'type': fields.selection([
401             ('value','Value'),
402             ('equation','Formula')
403         ], 'Type', required=True, size=32, change_default=True),
404     }
405     _defaults = {
406         'type': lambda *a: 'equation',
407     }
408 server_object_lines()
409
410 ##
411 # Actions that are run on the server side
412 #
413 class actions_server(osv.osv):
414
415     def _select_signals(self, cr, uid, context=None):
416         cr.execute("SELECT distinct w.osv, t.signal FROM wkf w, wkf_activity a, wkf_transition t \
417         WHERE w.id = a.wkf_id  AND t.act_from = a.id OR t.act_to = a.id AND t.signal!='' \
418         AND t.signal NOT IN (null, NULL)")
419         result = cr.fetchall() or []
420         res = []
421         for rs in result:
422             if rs[0] is not None and rs[1] is not None:
423                 line = rs[0], "%s - (%s)" % (rs[1], rs[0])
424                 res.append(line)
425         return res
426
427     def _select_objects(self, cr, uid, context=None):
428         model_pool = self.pool.get('ir.model')
429         ids = model_pool.search(cr, uid, [('name','not ilike','.')])
430         res = model_pool.read(cr, uid, ids, ['model', 'name'])
431         return [(r['model'], r['name']) for r in res] +  [('','')]
432
433     def change_object(self, cr, uid, ids, copy_object, state, context=None):
434         if state == 'object_copy':
435             model_pool = self.pool.get('ir.model')
436             model = copy_object.split(',')[0]
437             mid = model_pool.search(cr, uid, [('model','=',model)])
438             return {
439                 'value':{'srcmodel_id':mid[0]},
440                 'context':context
441             }
442         else:
443             return {}
444
445     _name = 'ir.actions.server'
446     _table = 'ir_act_server'
447     _sequence = 'ir_actions_id_seq'
448     _order = 'sequence,name'
449     _columns = {
450         'name': fields.char('Action Name', required=True, size=64, help="Easy to Refer action by name e.g. One Sales Order -> Many Invoices", translate=True),
451         'condition' : fields.char('Condition', size=256, required=True, help="Condition that is to be tested before action is executed, e.g. object.list_price > object.cost_price"),
452         'state': fields.selection([
453             ('client_action','Client Action'),
454             ('dummy','Dummy'),
455             ('loop','Iteration'),
456             ('code','Python Code'),
457             ('trigger','Trigger'),
458             ('email','Email'),
459             ('sms','SMS'),
460             ('object_create','Create Object'),
461             ('object_copy','Copy Object'),
462             ('object_write','Write Object'),
463             ('other','Multi Actions'),
464         ], 'Action Type', required=True, size=32, help="Type of the Action that is to be executed"),
465         'code':fields.text('Python Code', help="Python code to be executed"),
466         'sequence': fields.integer('Sequence', help="Important when you deal with multiple actions, the execution order will be decided based on this, low number is higher priority."),
467         'model_id': fields.many2one('ir.model', 'Object', required=True, help="Select the object on which the action will work (read, write, create)."),
468         'action_id': fields.many2one('ir.actions.actions', 'Client Action', help="Select the Action Window, Report, Wizard to be executed."),
469         'trigger_name': fields.selection(_select_signals, string='Trigger Name', size=128, help="Select the Signal name that is to be used as the trigger."),
470         'wkf_model_id': fields.many2one('ir.model', 'Workflow On', help="Workflow to be executed on this model."),
471         'trigger_obj_id': fields.many2one('ir.model.fields','Trigger On', help="Select the object from the model on which the workflow will executed."),
472         'email': fields.char('Email Address', size=512, help="Provides the fields that will be used to fetch the email address, e.g. when you select the invoice, then `object.invoice_address_id.email` is the field which gives the correct address"),
473         'subject': fields.char('Subject', size=1024, translate=True, help="Specify the subject. You can use fields from the object, e.g. `Hello [[ object.partner_id.name ]]`"),
474         'message': fields.text('Message', translate=True, help="Specify the message. You can use the fields from the object. e.g. `Dear [[ object.partner_id.name ]]`"),
475         'mobile': fields.char('Mobile No', size=512, help="Provides fields that be used to fetch the mobile number, e.g. you select the invoice, then `object.invoice_address_id.mobile` is the field which gives the correct mobile number"),
476         'sms': fields.char('SMS', size=160, translate=True),
477         'child_ids': fields.many2many('ir.actions.server', 'rel_server_actions', 'server_id', 'action_id', 'Other Actions'),
478         'usage': fields.char('Action Usage', size=32),
479         'type': fields.char('Action Type', size=32, required=True),
480         'srcmodel_id': fields.many2one('ir.model', 'Model', help="Object in which you want to create / write the object. If it is empty then refer to the Object field."),
481         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Field Mappings.'),
482         'record_id':fields.many2one('ir.model.fields', 'Create Id', help="Provide the field name where the record id is stored after the create operations. If it is empty, you can not track the new record."),
483         'write_id':fields.char('Write Id', size=256, help="Provide the field name that the record id refers to for the write operation. If it is empty it will refer to the active id of the object."),
484         'loop_action':fields.many2one('ir.actions.server', 'Loop Action', help="Select the action that will be executed. Loop action will not be avaliable inside loop."),
485         'expression':fields.char('Loop Expression', size=512, help="Enter the field/expression that will return the list. E.g. select the sale order in Object, and you can have loop on the sales order line. Expression = `object.order_line`."),
486         'copy_object': fields.reference('Copy Of', selection=_select_objects, size=256),
487     }
488     _defaults = {
489         'state': lambda *a: 'dummy',
490         'condition': lambda *a: 'True',
491         'type': lambda *a: 'ir.actions.server',
492         'sequence': lambda *a: 5,
493         'code': lambda *a: """# You can use the following variables
494 #    - object or obj
495 #    - time
496 #    - cr
497 #    - uid
498 #    - ids
499 # If you plan to return an action, assign: action = {...}
500 """,
501     }
502
503     def get_email(self, cr, uid, action, context):
504         logger = logging.getLogger('Workflow')
505         obj_pool = self.pool.get(action.model_id.model)
506         id = context.get('active_id')
507         obj = obj_pool.browse(cr, uid, id)
508
509         fields = None
510
511         if '/' in action.email.complete_name:
512             fields = action.email.complete_name.split('/')
513         elif '.' in action.email.complete_name:
514             fields = action.email.complete_name.split('.')
515
516         for field in fields:
517             try:
518                 obj = getattr(obj, field)
519             except Exception:
520                 logger.exception('Failed to parse: %s', field)
521
522         return obj
523
524     def get_mobile(self, cr, uid, action, context):
525         logger = logging.getLogger('Workflow')
526         obj_pool = self.pool.get(action.model_id.model)
527         id = context.get('active_id')
528         obj = obj_pool.browse(cr, uid, id)
529
530         fields = None
531
532         if '/' in action.mobile.complete_name:
533             fields = action.mobile.complete_name.split('/')
534         elif '.' in action.mobile.complete_name:
535             fields = action.mobile.complete_name.split('.')
536
537         for field in fields:
538             try:
539                 obj = getattr(obj, field)
540             except Exception:
541                 logger.exception('Failed to parse: %s', field)
542
543         return obj
544
545     def merge_message(self, cr, uid, keystr, action, context=None):
546         if context is None:
547             context = {}
548         def merge(match):
549             obj_pool = self.pool.get(action.model_id.model)
550             id = context.get('active_id')
551             obj = obj_pool.browse(cr, uid, id)
552             exp = str(match.group()[2:-2]).strip()
553             result = eval(exp,
554                           {
555                             'object': obj,
556                             'context': dict(context), # copy context to prevent side-effects of eval
557                             'time': time,
558                           })
559             if result in (None, False):
560                 return str("--------")
561             return tools.ustr(result)
562
563         com = re.compile('(\[\[.+?\]\])')
564         message = com.sub(merge, keystr)
565
566         return message
567
568     # Context should contains:
569     #   ids : original ids
570     #   id  : current id of the object
571     # OUT:
572     #   False : Finnished correctly
573     #   ACTION_ID : Action to launch
574
575     # FIXME: refactor all the eval() calls in run()!
576     def run(self, cr, uid, ids, context=None):
577         logger = logging.getLogger(self._name)
578         if context is None:
579             context = {}
580         for action in self.browse(cr, uid, ids, context):
581             obj_pool = self.pool.get(action.model_id.model)
582             obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
583             cxt = {
584                 'context': dict(context), # copy context to prevent side-effects of eval
585                 'object': obj,
586                 'time':time,
587                 'cr': cr,
588                 'pool' : self.pool,
589                 'uid' : uid
590             }
591             expr = eval(str(action.condition), cxt)
592             if not expr:
593                 continue
594
595             if action.state=='client_action':
596                 if not action.action_id:
597                     raise osv.except_osv(_('Error'), _("Please specify an action to launch !"))
598                 return self.pool.get(action.action_id.type)\
599                     .read(cr, uid, action.action_id.id, context=context)
600
601             if action.state=='code':
602                 localdict = {
603                     'self': self.pool.get(action.model_id.model),
604                     'context': dict(context), # copy context to prevent side-effects of eval
605                     'time': time,
606                     'ids': ids,
607                     'cr': cr,
608                     'uid': uid,
609                     'object':obj,
610                     'obj': obj,
611                 }
612                 eval(action.code, localdict, mode="exec", nocopy=True) # nocopy allows to return 'action'
613                 if 'action' in localdict:
614                     return localdict['action']
615
616             if action.state == 'email':
617                 user = config['email_from']
618                 address = str(action.email)
619                 try:
620                     address =  eval(str(action.email), cxt)
621                 except:
622                     pass
623
624                 if not address:
625                     logger.info('Partner Email address not Specified!')
626                     continue
627                 if not user:
628                     logger.info('Email-From address not Specified at server!')
629                     raise osv.except_osv(_('Error'), _("Please specify server option --email-from !"))
630
631                 subject = self.merge_message(cr, uid, action.subject, action, context)
632                 body = self.merge_message(cr, uid, action.message, action, context)
633
634                 if tools.email_send(user, [address], subject, body, debug=False, subtype='html') == True:
635                     logger.info('Email successfully sent to: %s', address)
636                 else:
637                     logger.warning('Failed to send email to: %s', address)
638
639             if action.state == 'trigger':
640                 wf_service = netsvc.LocalService("workflow")
641                 model = action.wkf_model_id.model
642                 obj_pool = self.pool.get(action.model_id.model)
643                 res_id = self.pool.get(action.model_id.model).read(cr, uid, [context.get('active_id')], [action.trigger_obj_id.name])
644                 id = res_id [0][action.trigger_obj_id.name]
645                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
646
647             if action.state == 'sms':
648                 #TODO: set the user and password from the system
649                 # for the sms gateway user / password
650                 # USE smsclient module from extra-addons
651                 logger.warning('SMS Facility has not been implemented yet. Use smsclient module!')
652
653             if action.state == 'other':
654                 res = []
655                 for act in action.child_ids:
656                     context['active_id'] = context['active_ids'][0]
657                     result = self.run(cr, uid, [act.id], context)
658                     if result:
659                         res.append(result)
660
661                 return res
662
663             if action.state == 'loop':
664                 obj_pool = self.pool.get(action.model_id.model)
665                 obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
666                 cxt = {
667                     'context': dict(context), # copy context to prevent side-effects of eval
668                     'object': obj,
669                     'time': time,
670                     'cr': cr,
671                     'pool' : self.pool,
672                     'uid' : uid
673                 }
674                 expr = eval(str(action.expression), cxt)
675                 context['object'] = obj
676                 for i in expr:
677                     context['active_id'] = i.id
678                     result = self.run(cr, uid, [action.loop_action.id], context)
679
680             if action.state == 'object_write':
681                 res = {}
682                 for exp in action.fields_lines:
683                     euq = exp.value
684                     if exp.type == 'equation':
685                         obj_pool = self.pool.get(action.model_id.model)
686                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
687                         cxt = {
688                             'context': dict(context), # copy context to prevent side-effects of eval
689                             'object': obj,
690                             'time': time,
691                         }
692                         expr = eval(euq, cxt)
693                     else:
694                         expr = exp.value
695                     res[exp.col1.name] = expr
696
697                 if not action.write_id:
698                     if not action.srcmodel_id:
699                         obj_pool = self.pool.get(action.model_id.model)
700                         obj_pool.write(cr, uid, [context.get('active_id')], res)
701                     else:
702                         write_id = context.get('active_id')
703                         obj_pool = self.pool.get(action.srcmodel_id.model)
704                         obj_pool.write(cr, uid, [write_id], res)
705
706                 elif action.write_id:
707                     obj_pool = self.pool.get(action.srcmodel_id.model)
708                     rec = self.pool.get(action.model_id.model).browse(cr, uid, context.get('active_id'))
709                     id = eval(action.write_id, {'object': rec})
710                     try:
711                         id = int(id)
712                     except:
713                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
714
715                     if type(id) != type(1):
716                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
717                     write_id = id
718                     obj_pool.write(cr, uid, [write_id], res)
719
720             if action.state == 'object_create':
721                 res = {}
722                 for exp in action.fields_lines:
723                     euq = exp.value
724                     if exp.type == 'equation':
725                         obj_pool = self.pool.get(action.model_id.model)
726                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
727                         expr = eval(euq,
728                                     {
729                                         'context': dict(context), # copy context to prevent side-effects of eval
730                                         'object': obj,
731                                         'time': time,
732                                     })
733                     else:
734                         expr = exp.value
735                     res[exp.col1.name] = expr
736
737                 obj_pool = None
738                 res_id = False
739                 obj_pool = self.pool.get(action.srcmodel_id.model)
740                 res_id = obj_pool.create(cr, uid, res)
741                 if action.record_id:
742                     self.pool.get(action.model_id.model).write(cr, uid, [context.get('active_id')], {action.record_id.name:res_id})
743
744             if action.state == 'object_copy':
745                 res = {}
746                 for exp in action.fields_lines:
747                     euq = exp.value
748                     if exp.type == 'equation':
749                         obj_pool = self.pool.get(action.model_id.model)
750                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
751                         expr = eval(euq,
752                                     {
753                                         'context': dict(context), # copy context to prevent side-effects of eval
754                                         'object': obj,
755                                         'time': time,
756                                     })
757                     else:
758                         expr = exp.value
759                     res[exp.col1.name] = expr
760
761                 obj_pool = None
762                 res_id = False
763
764                 model = action.copy_object.split(',')[0]
765                 cid = action.copy_object.split(',')[1]
766                 obj_pool = self.pool.get(model)
767                 res_id = obj_pool.copy(cr, uid, int(cid), res)
768
769         return False
770
771 actions_server()
772
773 class act_window_close(osv.osv):
774     _name = 'ir.actions.act_window_close'
775     _inherit = 'ir.actions.actions'
776     _table = 'ir_actions'
777     _defaults = {
778         'type': lambda *a: 'ir.actions.act_window_close',
779     }
780 act_window_close()
781
782 # This model use to register action services.
783 TODO_STATES = [('open', 'To Do'),
784                ('done', 'Done'),
785                ('skip','Skipped'),
786                ('cancel','Cancelled')]
787
788 class ir_actions_todo(osv.osv):
789     _name = 'ir.actions.todo'
790     _columns={
791         'action_id': fields.many2one(
792             'ir.actions.act_window', 'Action', select=True, required=True,
793             ondelete='cascade'),
794         'sequence': fields.integer('Sequence'),
795         'state': fields.selection(TODO_STATES, string='State', required=True),
796         'name':fields.char('Name', size=64),
797         'restart': fields.selection([('onskip','On Skip'),('always','Always'),('never','Never')],'Restart',required=True),
798         'groups_id':fields.many2many('res.groups', 'res_groups_action_rel', 'uid', 'gid', 'Groups'),
799         'note':fields.text('Text', translate=True),
800     }
801     _defaults={
802         'state': 'open',
803         'sequence': 10,
804         'restart': 'onskip',
805     }
806     _order="sequence,name,id"
807
808     def action_launch(self, cr, uid, ids, context=None):
809         """ Launch Action of Wizard"""
810         if context is None:
811             context = {}
812         wizard_id = ids and ids[0] or False
813         wizard = self.browse(cr, uid, wizard_id, context=context)
814         res = self.pool.get('ir.actions.act_window').read(cr, uid, wizard.action_id.id, ['name', 'view_type', 'view_mode', 'res_model', 'context', 'views', 'type'], context=context)
815         res.update({'target':'new', 'nodestroy': True})
816         return res
817
818     def action_open(self, cr, uid, ids, context=None):
819         """ Sets configuration wizard in TODO state"""
820         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
821
822 ir_actions_todo()
823
824 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
825