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