[REV]
[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 re
30 import copy
31 import sys
32 from xml import dom
33
34 class actions(osv.osv):
35     _name = 'ir.actions.actions'
36     _table = 'ir_actions'
37     _columns = {
38         'name': fields.char('Action Name', required=True, size=64),
39         'type': fields.char('Action Type', required=True, size=32),
40         'usage': fields.char('Action Usage', size=32),
41     }
42     _defaults = {
43         'usage': lambda *a: False,
44     }
45 actions()
46
47 class report_custom(osv.osv):
48     _name = 'ir.actions.report.custom'
49     _table = 'ir_act_report_custom'
50     _sequence = 'ir_actions_id_seq'
51     _columns = {
52         'name': fields.char('Report Name', size=64, required=True, translate=True),
53         'type': fields.char('Report Type', size=32, required=True),
54         'model':fields.char('Object', size=64, required=True),
55         'report_id': fields.integer('Report Ref.', required=True),
56         'usage': fields.char('Action Usage', size=32),
57         '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.")
58     }
59     _defaults = {
60         'multi': lambda *a: False,
61         'type': lambda *a: 'ir.actions.report.custom',
62     }
63 report_custom()
64
65 class report_xml(osv.osv):
66
67     def _report_content(self, cursor, user, ids, name, arg, context=None):
68         res = {}
69         for report in self.browse(cursor, user, ids, context=context):
70             data = report[name + '_data']
71             if not data and report[name[:-8]]:
72                 try:
73                     fp = tools.file_open(report[name[:-8]], mode='rb')
74                     data = fp.read()
75                 except:
76                     data = False
77             res[report.id] = data
78         return res
79
80     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
81         self.write(cursor, user, id, {name+'_data': value}, context=context)
82
83     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
84         res = {}
85         for report in self.browse(cursor, user, ids, context=context):
86             if report.report_rml:
87                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
88             else:
89                 res[report.id] = False
90         return res
91
92     _name = 'ir.actions.report.xml'
93     _table = 'ir_act_report_xml'
94     _sequence = 'ir_actions_id_seq'
95     _columns = {
96         'name': fields.char('Name', size=64, required=True, translate=True),
97         'model': fields.char('Object', size=64, required=True),
98         'type': fields.char('Action Type', size=32, required=True),
99         'report_name': fields.char('Service Name', size=64, required=True),
100         'usage': fields.char('Action Usage', size=32),
101         'report_type': fields.selection([ ('pdf','pdf'), ('html','html'), ('raw','raw'), ('sxw','sxw'), ('txt','txt'), ('odt','odt'), ('html2html','HTML from HTML'), ('mako2html','HTML from Mako'), ], string='Report Type', required=True),
102         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),
103         '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."),
104         '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.'),
105         '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.'),
106         'auto': fields.boolean('Custom python parser', required=True),
107
108         'header': fields.boolean('Add RML header', help="Add or not the coporate RML header"),
109
110         'report_xsl': fields.char('XSL path', size=256),
111         'report_xml': fields.char('XML path', size=256, help=''),
112         'report_rml': fields.char('RML path', size=256, help="The .rml path of the file or NULL if the content is in report_rml_content"),
113         'report_sxw': fields.function(_report_sxw, method=True, type='char', string='SXW path'),
114
115         'report_sxw_content_data': fields.binary('SXW content'),
116         'report_rml_content_data': fields.binary('RML content'),
117         'report_sxw_content': fields.function(_report_content, fnct_inv=_report_content_inv, method=True, type='binary', string='SXW content',),
118         'report_rml_content': fields.function(_report_content, fnct_inv=_report_content_inv, method=True, type='binary', string='RML content'),
119
120     }
121     _defaults = {
122         'type': lambda *a: 'ir.actions.report.xml',
123         'multi': lambda *a: False,
124         'auto': lambda *a: True,
125         'header': lambda *a: True,
126         'report_sxw_content': lambda *a: False,
127         'report_type': lambda *a: 'pdf',
128         'attachment': lambda *a: False,
129     }
130
131 report_xml()
132
133 class act_window(osv.osv):
134     _name = 'ir.actions.act_window'
135     _table = 'ir_act_window'
136     _sequence = 'ir_actions_id_seq'
137
138     def _check_model(self, cr, uid, ids, context={}):
139         for action in self.browse(cr, uid, ids, context):
140             if not self.pool.get(action.res_model):
141                 return False
142             if action.src_model and not self.pool.get(action.src_model):
143                 return False
144         return True
145     _constraints = [
146         (_check_model, 'Invalid model name in the action definition.', ['res_model','src_model'])
147     ]
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             modes = act.view_mode.split(',')
154             if len(modes)>len(act.view_ids):
155                 find = False
156                 if act.view_id:
157                     res[act.id].append((act.view_id.id, act.view_id.type))
158                 for t in modes[len(act.view_ids):]:
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         return res
164
165     def _search_view(self, cr, uid, ids, name, arg, context={}):
166         res = {}
167         def encode(s):
168             if isinstance(s, unicode):
169                 return s.encode('utf8')
170             return s
171         for act in self.browse(cr, uid, ids):
172             fields_from_fields_get = self.pool.get(act.res_model).fields_get(cr, uid, context=context)
173             search_view_id = False
174             if act.search_view_id:
175                 search_view_id = act.search_view_id.id
176             else:
177                 res_view = self.pool.get('ir.ui.view').search(cr, uid, [('model','=',act.res_model),('type','=','search'),('inherit_id','=',False)])
178                 if res_view:
179                     search_view_id = res_view[0]
180             if search_view_id:
181                 field_get = self.pool.get(act.res_model).fields_view_get(cr, uid, search_view_id, 'search', context)
182                 fields_from_fields_get.update(field_get['fields'])
183                 field_get['fields'] = fields_from_fields_get
184                 res[act.id] = str(field_get)
185             else:
186                 def process_child(node, new_node, doc):
187                     for child in node.childNodes:
188                         if child.localName=='field' and child.hasAttribute('select') and child.getAttribute('select')=='1':
189                             if child.childNodes:
190                                 fld = doc.createElement('field')
191                                 for attr in child.attributes.keys():
192                                     fld.setAttribute(attr, child.getAttribute(attr))
193                                 new_node.appendChild(fld)
194                             else:
195                                 new_node.appendChild(child)
196                         elif child.localName in ('page','group','notebook'):
197                             process_child(child, new_node, doc)
198
199                 form_arch = self.pool.get(act.res_model).fields_view_get(cr, uid, False, 'form', context)
200                 dom_arc = dom.minidom.parseString(encode(form_arch['arch']))
201                 new_node = copy.deepcopy(dom_arc)
202                 for child_node in new_node.childNodes[0].childNodes:
203                     if child_node.nodeType == child_node.ELEMENT_NODE:
204                         new_node.childNodes[0].removeChild(child_node)
205                 process_child(dom_arc.childNodes[0],new_node.childNodes[0],dom_arc)
206
207                 form_arch['arch'] = new_node.toxml()
208                 form_arch['fields'].update(fields_from_fields_get)
209                 res[act.id] = str(form_arch)
210         return res
211
212     def _get_help_status(self, cr, uid, ids, name, arg, context={}):
213         cr.execute(""" SELECT action.id,
214                      CASE WHEN r.uid IS NULL THEN True ELSE False END
215                      AS help_status FROM ir_act_window action
216                      LEFT JOIN ir_act_window_user_rel r ON
217                      (action.id = r.act_id AND (r.uid IS NULL or r.uid= %s)) WHERE action.id = ANY(%s)""",(uid,ids,))
218         return dict(cr.fetchall())
219
220     _columns = {
221         'name': fields.char('Action Name', size=64, translate=True),
222         'type': fields.char('Action Type', size=32, required=True),
223         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
224         'domain': fields.char('Domain Value', size=250,
225             help="Optional domain filtering of the destination data, as a Python expression"),
226         'context': fields.char('Context Value', size=250, required=True,
227             help="Context dictionary as Python expression, empty by default (Default: {})"),
228         'res_model': fields.char('Object', size=64, required=True,
229             help="Model name of the object to open in the view window"),
230         'src_model': fields.char('Source Object', size=64,
231             help="Optional model name of the objects on which this action should be visible"),
232         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
233         'view_type': fields.selection((('tree','Tree'),('form','Form')), string='View Type', required=True,
234             help="View type: set to 'tree' for a hierarchical tree view, or 'form' for other views"),
235         'view_mode': fields.char('View Mode', size=250, required=True,
236             help="Comma-separated list of allowed view modes, such as 'form', 'tree', 'calendar', etc. (Default: tree,form)"),
237         'usage': fields.char('Action Usage', size=32),
238         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
239         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
240         'limit': fields.integer('Limit', help='Default limit for the list view'),
241         'auto_refresh': fields.integer('Auto-Refresh',
242             help='Add an auto-refresh on the view'),
243         'groups_id': fields.many2many('res.groups', 'ir_act_window_group_rel',
244             'act_id', 'gid', 'Groups'),
245         'search_view_id': fields.many2one('ir.ui.view', 'Search View Ref.'),
246         'filter': fields.boolean('Filter'),
247         'auto_search':fields.boolean('Auto Search'),
248         'default_user_ids': fields.many2many('res.users', 'ir_act_window_user_rel', 'act_id', 'uid', 'Users'),
249         'search_view' : fields.function(_search_view, type='text', method=True, string='Search View'),
250         'menus': fields.char('Menus', size=4096),
251         'help': fields.text('Action description',
252             help='Optional help text for the users with a description of the target view, such as its usage and purpose.'),
253         'display_help':fields.function(_get_help_status, type='boolean', method=True, string='Display Help',
254             help='It gives the status if the help message has to be displayed or not when a user performs an action')
255
256     }
257     _defaults = {
258         'type': lambda *a: 'ir.actions.act_window',
259         'view_type': lambda *a: 'form',
260         'view_mode': lambda *a: 'tree,form',
261         'context': lambda *a: '{}',
262         'limit': lambda *a: 80,
263         'target': lambda *a: 'current',
264         'auto_refresh': lambda *a: 0,
265         'auto_search':lambda *a: True
266     }
267     def _auto_init(self, cr, context={}):
268         super(act_window, self)._auto_init(cr, context)
269         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'act_window_action_uid_index\'')
270         if not cr.fetchone():
271             cr.execute('CREATE INDEX act_window_action_uid_index ON ir_act_window_user_rel (act_id, uid)')
272             cr.commit()
273 act_window()
274
275 class act_window_view(osv.osv):
276     _name = 'ir.actions.act_window.view'
277     _table = 'ir_act_window_view'
278     _rec_name = 'view_id'
279     _columns = {
280         'sequence': fields.integer('Sequence'),
281         'view_id': fields.many2one('ir.ui.view', 'View'),
282         'view_mode': fields.selection((
283             ('tree', 'Tree'),
284             ('form', 'Form'),
285             ('graph', 'Graph'),
286             ('calendar', 'Calendar'),
287             ('gantt', 'Gantt')), string='View Type', required=True),
288         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
289         'multi': fields.boolean('On Multiple Doc.',
290             help="If set to true, the action will not be displayed on the right toolbar of a form view."),
291     }
292     _defaults = {
293         'multi': lambda *a: False,
294     }
295     _order = 'sequence'
296 act_window_view()
297
298 class act_wizard(osv.osv):
299     _name = 'ir.actions.wizard'
300     _inherit = 'ir.actions.actions'
301     _table = 'ir_act_wizard'
302     _sequence = 'ir_actions_id_seq'
303     _columns = {
304         'name': fields.char('Wizard Info', size=64, required=True, translate=True),
305         'type': fields.char('Action Type', size=32, required=True),
306         'wiz_name': fields.char('Wizard Name', size=64, required=True),
307         '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."),
308         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups'),
309         'model': fields.char('Object', size=64),
310     }
311     _defaults = {
312         'type': lambda *a: 'ir.actions.wizard',
313         'multi': lambda *a: False,
314     }
315 act_wizard()
316
317 class act_url(osv.osv):
318     _name = 'ir.actions.url'
319     _table = 'ir_act_url'
320     _sequence = 'ir_actions_id_seq'
321     _columns = {
322         'name': fields.char('Action Name', size=64, translate=True),
323         'type': fields.char('Action Type', size=32, required=True),
324         'url': fields.text('Action URL',required=True),
325         'target': fields.selection((
326             ('new', 'New Window'),
327             ('self', 'This Window')),
328             'Action Target', required=True
329         )
330     }
331     _defaults = {
332         'type': lambda *a: 'ir.actions.act_url',
333         'target': lambda *a: 'new'
334     }
335 act_url()
336
337 def model_get(self, cr, uid, context={}):
338     wkf_pool = self.pool.get('workflow')
339     ids = wkf_pool.search(cr, uid, [])
340     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
341
342     res = []
343     mpool = self.pool.get('ir.model')
344     for osv in osvs:
345         model = osv.get('osv')
346         id = mpool.search(cr, uid, [('model','=',model)])
347         name = mpool.read(cr, uid, id)[0]['name']
348         res.append((model, name))
349
350     return res
351
352 class ir_model_fields(osv.osv):
353     _inherit = 'ir.model.fields'
354     _rec_name = 'field_description'
355     _columns = {
356         'complete_name': fields.char('Complete Name', size=64, select=1),
357     }
358 ir_model_fields()
359
360 class server_object_lines(osv.osv):
361     _name = 'ir.server.object.lines'
362     _sequence = 'ir_actions_id_seq'
363     _columns = {
364         'server_id': fields.many2one('ir.actions.server', 'Object Mapping'),
365         'col1': fields.many2one('ir.model.fields', 'Destination', required=True),
366         'value': fields.text('Value', required=True),
367         'type': fields.selection([
368             ('value','Value'),
369             ('equation','Formula')
370         ], 'Type', required=True, size=32, change_default=True),
371     }
372     _defaults = {
373         'type': lambda *a: 'equation',
374     }
375 server_object_lines()
376
377 ##
378 # Actions that are run on the server side
379 #
380 class actions_server(osv.osv):
381
382     def _select_signals(self, cr, uid, context={}):
383         cr.execute("SELECT distinct w.osv, t.signal FROM wkf w, wkf_activity a, wkf_transition t \
384         WHERE w.id = a.wkf_id  AND t.act_from = a.id OR t.act_to = a.id AND t.signal!='' \
385         AND t.signal NOT IN (null, NULL)")
386         result = cr.fetchall() or []
387         res = []
388         for rs in result:
389             if rs[0] is not None and rs[1] is not None:
390                 line = rs[0], "%s - (%s)" % (rs[1], rs[0])
391                 res.append(line)
392         return res
393
394     def _select_objects(self, cr, uid, context={}):
395         model_pool = self.pool.get('ir.model')
396         ids = model_pool.search(cr, uid, [('name','not ilike','.')])
397         res = model_pool.read(cr, uid, ids, ['model', 'name'])
398         return [(r['model'], r['name']) for r in res] +  [('','')]
399
400     def change_object(self, cr, uid, ids, copy_object, state, context={}):
401         if state == 'object_copy':
402             model_pool = self.pool.get('ir.model')
403             model = copy_object.split(',')[0]
404             mid = model_pool.search(cr, uid, [('model','=',model)])
405             return {
406                 'value':{'srcmodel_id':mid[0]},
407                 'context':context
408             }
409         else:
410             return {}
411
412     _name = 'ir.actions.server'
413     _table = 'ir_act_server'
414     _sequence = 'ir_actions_id_seq'
415     _order = 'sequence'
416     _columns = {
417         '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),
418         '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"),
419         'state': fields.selection([
420             ('client_action','Client Action'),
421             ('dummy','Dummy'),
422             ('loop','Iteration'),
423             ('code','Python Code'),
424             ('trigger','Trigger'),
425             ('email','Email'),
426             ('sms','SMS'),
427             ('object_create','Create Object'),
428             ('object_copy','Copy Object'),
429             ('object_write','Write Object'),
430             ('other','Multi Actions'),
431         ], 'Action Type', required=True, size=32, help="Type of the Action that is to be executed"),
432         'code':fields.text('Python Code', help="Python code to be executed"),
433         '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."),
434         'model_id': fields.many2one('ir.model', 'Object', required=True, help="Select the object on which the action will work (read, write, create)."),
435         'action_id': fields.many2one('ir.actions.actions', 'Client Action', help="Select the Action Window, Report, Wizard to be executed."),
436         'trigger_name': fields.selection(_select_signals, string='Trigger Name', size=128, help="Select the Signal name that is to be used as the trigger."),
437         'wkf_model_id': fields.many2one('ir.model', 'Workflow On', help="Workflow to be executed on this model."),
438         'trigger_obj_id': fields.many2one('ir.model.fields','Trigger On', help="Select the object from the model on which the workflow will executed."),
439         '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"),
440         '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 ]]`"),
441         '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 ]]`"),
442         '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"),
443         'sms': fields.char('SMS', size=160, translate=True),
444         'child_ids': fields.many2many('ir.actions.server', 'rel_server_actions', 'server_id', 'action_id', 'Other Actions'),
445         'usage': fields.char('Action Usage', size=32),
446         'type': fields.char('Action Type', size=32, required=True),
447         '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."),
448         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Field Mappings.'),
449         '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."),
450         '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."),
451         '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."),
452         '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`."),
453         'copy_object': fields.reference('Copy Of', selection=_select_objects, size=256),
454     }
455     _defaults = {
456         'state': lambda *a: 'dummy',
457         'condition': lambda *a: 'True',
458         'type': lambda *a: 'ir.actions.server',
459         'sequence': lambda *a: 5,
460         'code': lambda *a: """# You can use the following variables
461 #    - object or obj
462 #    - time
463 #    - cr
464 #    - uid
465 #    - ids
466 # If you plan to return an action, assign: action = {...}
467 """,
468     }
469
470     def get_email(self, cr, uid, action, context):
471         logger = netsvc.Logger()
472         obj_pool = self.pool.get(action.model_id.model)
473         id = context.get('active_id')
474         obj = obj_pool.browse(cr, uid, id)
475
476         fields = None
477
478         if '/' in action.email.complete_name:
479             fields = action.email.complete_name.split('/')
480         elif '.' in action.email.complete_name:
481             fields = action.email.complete_name.split('.')
482
483         for field in fields:
484             try:
485                 obj = getattr(obj, field)
486             except Exception,e :
487                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (field))
488
489         return obj
490
491     def get_mobile(self, cr, uid, action, context):
492         logger = netsvc.Logger()
493         obj_pool = self.pool.get(action.model_id.model)
494         id = context.get('active_id')
495         obj = obj_pool.browse(cr, uid, id)
496
497         fields = None
498
499         if '/' in action.mobile.complete_name:
500             fields = action.mobile.complete_name.split('/')
501         elif '.' in action.mobile.complete_name:
502             fields = action.mobile.complete_name.split('.')
503
504         for field in fields:
505             try:
506                 obj = getattr(obj, field)
507             except Exception,e :
508                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (field))
509
510         return obj
511
512     def merge_message(self, cr, uid, keystr, action, context):
513         logger = netsvc.Logger()
514         def merge(match):
515             obj_pool = self.pool.get(action.model_id.model)
516             id = context.get('active_id')
517             obj = obj_pool.browse(cr, uid, id)
518             exp = str(match.group()[2:-2]).strip()
519             result = eval(exp, {'object':obj, 'context': context,'time':time})
520             if result in (None, False):
521                 return str("--------")
522             return tools.ustr(result)
523
524         com = re.compile('(\[\[.+?\]\])')
525         message = com.sub(merge, keystr)
526
527         return message
528
529     # Context should contains:
530     #   ids : original ids
531     #   id  : current id of the object
532     # OUT:
533     #   False : Finnished correctly
534     #   ACTION_ID : Action to launch
535
536     def run(self, cr, uid, ids, context={}):
537         logger = netsvc.Logger()
538         for action in self.browse(cr, uid, ids, context):
539             obj_pool = self.pool.get(action.model_id.model)
540             obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
541             cxt = {
542                 'context':context,
543                 'object': obj,
544                 'time':time,
545                 'cr': cr,
546                 'pool' : self.pool,
547                 'uid' : uid
548             }
549             expr = eval(str(action.condition), cxt)
550             if not expr:
551                 continue
552
553             if action.state=='client_action':
554                 if not action.action_id:
555                     raise osv.except_osv(_('Error'), _("Please specify an action to launch !"))
556                 return self.pool.get(action.action_id.type)\
557                     .read(cr, uid, action.action_id.id, context=context)
558
559             if action.state=='code':
560                 if config['server_actions_allow_code']:
561                     localdict = {
562                         'self': self.pool.get(action.model_id.model),
563                         'context': context,
564                         'time': time,
565                         'ids': ids,
566                         'cr': cr,
567                         'uid': uid,
568                         'object':obj,
569                         'obj': obj,
570                         }
571                     eval(action.code, localdict, mode="exec")
572                     if 'action' in localdict:
573                         return localdict['action']
574                 else:
575                     netsvc.Logger().notifyChannel(
576                         self._name, netsvc.LOG_ERROR,
577                         "%s is a `code` server action, but "
578                         "it isn't allowed in this configuration.\n\n"
579                         "See server options to enable it"%action)
580
581             if action.state == 'email':
582                 user = config['email_from']
583                 address = str(action.email)
584                 try:
585                     address =  eval(str(action.email), cxt)
586                 except:
587                     pass
588
589                 if not address:
590                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Partner Email address not Specified!')
591                     continue
592                 if not user:
593                     raise osv.except_osv(_('Error'), _("Please specify server option --email-from !"))
594
595                 subject = self.merge_message(cr, uid, action.subject, action, context)
596                 body = self.merge_message(cr, uid, action.message, action, context)
597
598                 if tools.email_send(user, [address], subject, body, debug=False, subtype='html') == True:
599                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (address))
600                 else:
601                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (address))
602
603             if action.state == 'trigger':
604                 wf_service = netsvc.LocalService("workflow")
605                 model = action.wkf_model_id.model
606                 obj_pool = self.pool.get(action.model_id.model)
607                 res_id = self.pool.get(action.model_id.model).read(cr, uid, [context.get('active_id')], [action.trigger_obj_id.name])
608                 id = res_id [0][action.trigger_obj_id.name]
609                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
610
611             if action.state == 'sms':
612                 #TODO: set the user and password from the system
613                 # for the sms gateway user / password
614                 # USE smsclient module from extra-addons
615                 logger.notifyChannel('sms', netsvc.LOG_ERROR, 'SMS Facility has not been implemented yet. Use smsclient module!')
616
617             if action.state == 'other':
618                 res = []
619                 for act in action.child_ids:
620                     context['active_id'] = context['active_ids'][0]
621                     result = self.run(cr, uid, [act.id], context)
622                     if result:
623                         res.append(result)
624
625                 return res
626
627             if action.state == 'loop':
628                 obj_pool = self.pool.get(action.model_id.model)
629                 obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
630                 cxt = {
631                     'context':context,
632                     'object': obj,
633                     'time':time,
634                     'cr': cr,
635                     'pool' : self.pool,
636                     'uid' : uid
637                 }
638                 expr = eval(str(action.expression), cxt)
639                 context['object'] = obj
640                 for i in expr:
641                     context['active_id'] = i.id
642                     result = self.run(cr, uid, [action.loop_action.id], context)
643
644             if action.state == 'object_write':
645                 res = {}
646                 for exp in action.fields_lines:
647                     euq = exp.value
648                     if exp.type == 'equation':
649                         obj_pool = self.pool.get(action.model_id.model)
650                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
651                         cxt = {'context':context, 'object': obj, 'time':time}
652                         expr = eval(euq, cxt)
653                     else:
654                         expr = exp.value
655                     res[exp.col1.name] = expr
656
657                 if not action.write_id:
658                     if not action.srcmodel_id:
659                         obj_pool = self.pool.get(action.model_id.model)
660                         obj_pool.write(cr, uid, [context.get('active_id')], res)
661                     else:
662                         write_id = context.get('active_id')
663                         obj_pool = self.pool.get(action.srcmodel_id.model)
664                         obj_pool.write(cr, uid, [write_id], res)
665
666                 elif action.write_id:
667                     obj_pool = self.pool.get(action.srcmodel_id.model)
668                     rec = self.pool.get(action.model_id.model).browse(cr, uid, context.get('active_id'))
669                     id = eval(action.write_id, {'object': rec})
670                     try:
671                         id = int(id)
672                     except:
673                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
674
675                     if type(id) != type(1):
676                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
677                     write_id = id
678                     obj_pool.write(cr, uid, [write_id], res)
679
680             if action.state == 'object_create':
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                         expr = eval(euq, {'context':context, 'object': obj, 'time':time})
688                     else:
689                         expr = exp.value
690                     res[exp.col1.name] = expr
691
692                 obj_pool = None
693                 res_id = False
694                 obj_pool = self.pool.get(action.srcmodel_id.model)
695                 res_id = obj_pool.create(cr, uid, res)
696                 if action.record_id:
697                     self.pool.get(action.model_id.model).write(cr, uid, [context.get('active_id')], {action.record_id.name:res_id})
698
699             if action.state == 'object_copy':
700                 res = {}
701                 for exp in action.fields_lines:
702                     euq = exp.value
703                     if exp.type == 'equation':
704                         obj_pool = self.pool.get(action.model_id.model)
705                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
706                         expr = eval(euq, {'context':context, 'object': obj, 'time':time})
707                     else:
708                         expr = exp.value
709                     res[exp.col1.name] = expr
710
711                 obj_pool = None
712                 res_id = False
713
714                 model = action.copy_object.split(',')[0]
715                 cid = action.copy_object.split(',')[1]
716                 obj_pool = self.pool.get(model)
717                 res_id = obj_pool.copy(cr, uid, int(cid), res)
718
719         return False
720
721 actions_server()
722
723 class act_window_close(osv.osv):
724     _name = 'ir.actions.act_window_close'
725     _inherit = 'ir.actions.actions'
726     _table = 'ir_actions'
727     _defaults = {
728         'type': lambda *a: 'ir.actions.act_window_close',
729     }
730 act_window_close()
731
732 # This model use to register action services.
733 TODO_STATES = [('open', 'To Do'),
734                ('done', 'Done'),
735                ('skip','Skipped'),
736                ('cancel','Cancel')]
737
738 class ir_actions_todo(osv.osv):
739     _name = 'ir.actions.todo'
740     _columns={
741         'action_id': fields.many2one(
742             'ir.actions.act_window', 'Action', select=True, required=True,
743             ondelete='cascade'),
744         'sequence': fields.integer('Sequence'),
745         'state': fields.selection(TODO_STATES, string='State', required=True),
746         'name':fields.char('Name', size=64),
747         'restart': fields.selection([('onskip','On Skip'),('always','Always'),('never','Never')],'Restart',required=True),
748         'groups_id':fields.many2many('res.groups', 'res_groups_action_rel', 'uid', 'gid', 'Groups'),
749         'note':fields.text('Text', translate=True),
750     }
751     _defaults={
752         'state': lambda *a: 'open',
753         'sequence': lambda *a: 10,
754         'restart': lambda *a: 'always',
755     }
756     _order="sequence,id"
757 ir_actions_todo()
758
759 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
760