fd591d322283a1b56a4071aa60c0da7a82afcc3d
[odoo/odoo.git] / bin / addons / base / ir / ir_actions.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution    
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import fields,osv
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
33 try:
34     from xml import dom, xpath
35 except ImportError:
36     sys.stderr.write("ERROR: Import xpath module\n")
37     sys.stderr.write("ERROR: Try to install the old python-xml package\n")
38     sys.exit(2)
39
40 class actions(osv.osv):
41     _name = 'ir.actions.actions'
42     _table = 'ir_actions'
43     _columns = {
44         'name': fields.char('Action Name', required=True, size=64),
45         'type': fields.char('Action Type', required=True, size=32),
46         'usage': fields.char('Action Usage', size=32),
47     }
48     _defaults = {
49         'usage': lambda *a: False,
50     }
51 actions()
52
53 class report_custom(osv.osv):
54     _name = 'ir.actions.report.custom'
55     _table = 'ir_act_report_custom'
56     _sequence = 'ir_actions_id_seq'
57     _columns = {
58         'name': fields.char('Report Name', size=64, required=True, translate=True),
59         'type': fields.char('Report Type', size=32, required=True),
60         'model':fields.char('Object', size=64, required=True),
61         'report_id': fields.integer('Report Ref.', required=True),
62         'usage': fields.char('Action Usage', size=32),
63         '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.")
64     }
65     _defaults = {
66         'multi': lambda *a: False,
67         'type': lambda *a: 'ir.actions.report.custom',
68     }
69 report_custom()
70
71 class report_xml(osv.osv):
72
73     def _report_content(self, cursor, user, ids, name, arg, context=None):
74         res = {}
75         for report in self.browse(cursor, user, ids, context=context):
76             data = report[name + '_data']
77             if not data and report[name[:-8]]:
78                 try:
79                     fp = tools.file_open(report[name[:-8]], mode='rb')
80                     data = fp.read()
81                 except:
82                     data = False
83             res[report.id] = data
84         return res
85
86     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
87         self.write(cursor, user, id, {name+'_data': value}, context=context)
88
89     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
90         res = {}
91         for report in self.browse(cursor, user, ids, context=context):
92             if report.report_rml:
93                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
94             else:
95                 res[report.id] = False
96         return res
97
98     _name = 'ir.actions.report.xml'
99     _table = 'ir_act_report_xml'
100     _sequence = 'ir_actions_id_seq'
101     _columns = {
102         'name': fields.char('Name', size=64, required=True, translate=True),
103         'type': fields.char('Report Type', size=32, required=True),
104         'model': fields.char('Object', size=64, required=True),
105         'report_name': fields.char('Internal Name', size=64, required=True),
106         'report_xsl': fields.char('XSL path', size=256),
107         'report_xml': fields.char('XML path', size=256),
108         'report_rml': fields.char('RML path', size=256,
109             help="The .rml path of the file or NULL if the content is in report_rml_content"),
110         'report_sxw': fields.function(_report_sxw, method=True, type='char',
111             string='SXW path'),
112         'report_sxw_content_data': fields.binary('SXW content'),
113         'report_rml_content_data': fields.binary('RML content'),
114         'report_sxw_content': fields.function(_report_content,
115             fnct_inv=_report_content_inv, method=True,
116             type='binary', string='SXW content',),
117         'report_rml_content': fields.function(_report_content,
118             fnct_inv=_report_content_inv, method=True,
119             type='binary', string='RML content'),
120         'auto': fields.boolean('Automatic XSL:RML', required=True),
121         'usage': fields.char('Action Usage', size=32),
122         'header': fields.boolean('Add RML header',
123             help="Add or not the coporate RML header"),
124         'multi': fields.boolean('On multiple doc.',
125             help="If set to true, the action will not be displayed on the right toolbar of a form view."),
126         'report_type': fields.selection([
127             ('pdf', 'pdf'),
128             ('html', 'html'),
129             ('raw', 'raw'),
130             ('sxw', 'sxw'),
131             ('odt', 'odt'),
132             ('html2html','Html from html'),
133             ], string='Type', required=True),
134         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),
135         '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.'),
136         '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.')
137     }
138     _defaults = {
139         'type': lambda *a: 'ir.actions.report.xml',
140         'multi': lambda *a: False,
141         'auto': lambda *a: True,
142         'header': lambda *a: True,
143         'report_sxw_content': lambda *a: False,
144         'report_type': lambda *a: 'pdf',
145         'attachment': lambda *a: False,
146     }
147
148 report_xml()
149
150 class act_window(osv.osv):
151     _name = 'ir.actions.act_window'
152     _table = 'ir_act_window'
153     _sequence = 'ir_actions_id_seq'
154     def _check_model(self, cr, uid, ids, context={}):
155         for action in self.browse(cr, uid, ids, context):
156             if not self.pool.get(action.res_model):
157                 return False
158             if action.src_model and not self.pool.get(action.src_model):
159                 return False
160         return True
161     _constraints = [
162         (_check_model, 'Invalid model name in the action definition.', ['res_model','src_model'])
163     ]
164
165     def get_filters(self, cr, uid, model):
166         cr.execute('select id from ir_act_window a where a.id not in (select act_id from ir_act_window_user_rel) and a.res_model=\''+model+'\' and a.filter=\'1\';')
167         all_ids = cr.fetchall()
168         filter_ids =  map(lambda x:x[0],all_ids)
169         act_ids = self.search(cr,uid,[('res_model','=',model),('filter','=',1),('default_user_ids','in',(','.join(map(str,[uid,])),))])
170         act_ids += filter_ids
171         act_ids = list(set(act_ids))
172         my_acts = self.read(cr, uid, act_ids, ['name', 'domain'])
173         return my_acts
174
175     def _views_get_fnc(self, cr, uid, ids, name, arg, context={}):
176         res={}
177         for act in self.browse(cr, uid, ids):
178             res[act.id]=[(view.view_id.id, view.view_mode) for view in act.view_ids]
179             modes = act.view_mode.split(',')
180             if len(modes)>len(act.view_ids):
181                 find = False
182                 if act.view_id:
183                     res[act.id].append((act.view_id.id, act.view_id.type))
184                 for t in modes[len(act.view_ids):]:
185                     if act.view_id and (t == act.view_id.type) and not find:
186                         find = True
187                         continue
188                     res[act.id].append((False, t))
189         return res
190
191     def _search_view(self, cr, uid, ids, name, arg, context={}):
192         res = {}
193         def encode(s):
194             if isinstance(s, unicode):
195                 return s.encode('utf8')
196             return s
197         for act in self.browse(cr, uid, ids):
198             fields_from_fields_get = self.pool.get(act.res_model).fields_get(cr, uid)
199             if act.search_view_id:
200                 field_get = self.pool.get(act.res_model).fields_view_get(cr, uid, act.search_view_id.id, 'search', context)
201                 fields_from_fields_get.update(field_get['fields'])
202                 field_get['fields'] = fields_from_fields_get
203                 res[act.id] = str(field_get)
204             else:
205                 def process_child(node, new_node, doc):
206                     for child in node.childNodes:
207                         if child.localName=='field' and child.hasAttribute('select') and child.getAttribute('select')=='1':
208                             if child.childNodes:
209                                 fld = doc.createElement('field')
210                                 for attr in child.attributes.keys():
211                                     fld.setAttribute(attr, child.getAttribute(attr))
212                                 new_node.appendChild(fld)
213                             else:
214                                 new_node.appendChild(child)
215                         elif child.localName in ('page','group','notebook'):
216                             process_child(child, new_node, doc)
217
218                 form_arch = self.pool.get(act.res_model).fields_view_get(cr, uid, False, 'form', context)
219                 dom_arc = dom.minidom.parseString(encode(form_arch['arch']))
220                 new_node = copy.deepcopy(dom_arc)
221                 for child_node in new_node.childNodes[0].childNodes:
222                     if child_node.nodeType == child_node.ELEMENT_NODE:
223                         new_node.childNodes[0].removeChild(child_node)
224                 process_child(dom_arc.childNodes[0],new_node.childNodes[0],dom_arc)
225
226                 form_arch['arch'] = new_node.toxml()
227                 form_arch['fields'].update(fields_from_fields_get)
228                 res[act.id] = str(form_arch)
229         return res
230
231     _columns = {
232         'name': fields.char('Action Name', size=64, translate=True),
233         'type': fields.char('Action Type', size=32, required=True),
234         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
235         'domain': fields.char('Domain Value', size=250),
236         'context': fields.char('Context Value', size=250),
237         'res_model': fields.char('Object', size=64),
238         'src_model': fields.char('Source Object', size=64),
239         'target': fields.selection([('current','Current Window'),('new','New Window')], 'Target Window'),
240         'view_type': fields.selection((('tree','Tree'),('form','Form')),string='View Type'),
241         'view_mode': fields.char('View Mode', size=250),
242         'usage': fields.char('Action Usage', size=32),
243         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
244         'views': fields.function(_views_get_fnc, method=True, type='binary', string='Views'),
245         'limit': fields.integer('Limit', help='Default limit for the list view'),
246         'auto_refresh': fields.integer('Auto-Refresh',
247             help='Add an auto-refresh on the view'),
248         'groups_id': fields.many2many('res.groups', 'ir_act_window_group_rel',
249             'act_id', 'gid', 'Groups'),
250         'search_view_id': fields.many2one('ir.ui.view', 'Search View Ref.'),
251         'filter': fields.boolean('Filter'),
252         'default_user_ids': fields.many2many('res.users', 'ir_act_window_user_rel', 'act_id', 'uid', 'Users'),
253         'search_view' : fields.function(_search_view, type='text', method=True, string='Search View'),
254         'menus': fields.char('Menus', size=4096)            
255     }
256     _defaults = {
257         'type': lambda *a: 'ir.actions.act_window',
258         'view_type': lambda *a: 'form',
259         'view_mode': lambda *a: 'tree,form',
260         'context': lambda *a: '{}',
261         'limit': lambda *a: 80,
262         'target': lambda *a: 'current',
263         'auto_refresh': lambda *a: 0,
264     }
265 act_window()
266
267 class act_window_view(osv.osv):
268     _name = 'ir.actions.act_window.view'
269     _table = 'ir_act_window_view'
270     _rec_name = 'view_id'
271     _columns = {
272         'sequence': fields.integer('Sequence'),
273         'view_id': fields.many2one('ir.ui.view', 'View'),
274         'view_mode': fields.selection((
275             ('tree', 'Tree'),
276             ('form', 'Form'),
277             ('graph', 'Graph'),
278             ('calendar', 'Calendar'),
279             ('gantt', 'Gantt')), string='View Type', required=True),
280         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
281         'multi': fields.boolean('On Multiple Doc.',
282             help="If set to true, the action will not be displayed on the right toolbar of a form view."),
283     }
284     _defaults = {
285         'multi': lambda *a: False,
286     }
287     _order = 'sequence'
288 act_window_view()
289
290 class act_wizard(osv.osv):
291     _name = 'ir.actions.wizard'
292     _inherit = 'ir.actions.actions'
293     _table = 'ir_act_wizard'
294     _sequence = 'ir_actions_id_seq'
295     _columns = {
296         'name': fields.char('Wizard Info', size=64, required=True, translate=True),
297         'type': fields.char('Action Type', size=32, required=True),
298         'wiz_name': fields.char('Wizard Name', size=64, required=True),
299         '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."),
300         'groups_id': fields.many2many('res.groups', 'res_groups_wizard_rel', 'uid', 'gid', 'Groups'),
301         'model': fields.char('Object', size=64),
302     }
303     _defaults = {
304         'type': lambda *a: 'ir.actions.wizard',
305         'multi': lambda *a: False,
306     }
307 act_wizard()
308
309 class act_url(osv.osv):
310     _name = 'ir.actions.url'
311     _table = 'ir_act_url'
312     _sequence = 'ir_actions_id_seq'
313     _columns = {
314         'name': fields.char('Action Name', size=64, translate=True),
315         'type': fields.char('Action Type', size=32, required=True),
316         'url': fields.text('Action URL',required=True),
317         'target': fields.selection((
318             ('new', 'New Window'),
319             ('self', 'This Window')),
320             'Action Target', required=True
321         )
322     }
323     _defaults = {
324         'type': lambda *a: 'ir.actions.act_url',
325         'target': lambda *a: 'new'
326     }
327 act_url()
328
329 def model_get(self, cr, uid, context={}):
330     wkf_pool = self.pool.get('workflow')
331     ids = wkf_pool.search(cr, uid, [])
332     osvs = wkf_pool.read(cr, uid, ids, ['osv'])
333
334     res = []
335     mpool = self.pool.get('ir.model')
336     for osv in osvs:
337         model = osv.get('osv')
338         id = mpool.search(cr, uid, [('model','=',model)])
339         name = mpool.read(cr, uid, id)[0]['name']
340         res.append((model, name))
341
342     return res
343
344 class ir_model_fields(osv.osv):
345     _inherit = 'ir.model.fields'
346     _rec_name = 'field_description'
347     _columns = {
348         'complete_name': fields.char('Complete Name', size=64, select=1),
349     }
350
351     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=800):
352         def get_fields(cr, uid, field, rel):
353             result = []
354             mobj = self.pool.get('ir.model')
355             id = mobj.search(cr, uid, [('model','=',rel)])
356
357             obj = self.pool.get('ir.model.fields')
358             ids = obj.search(cr, uid, [('model_id','in',id)])
359             records = obj.read(cr, uid, ids)
360             for record in records:
361                 id = record['id']
362                 fld = field + '/' + record['name']
363
364                 result.append((id, fld))
365             return result
366
367         if not args:
368             args=[]
369         if not context:
370             context={}
371             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
372
373         if context.get('key') != 'server_action':
374             return super(ir_model_fields, self).name_search(cr, uid, name, args, operator, context, limit)
375
376         result = []
377         obj = self.pool.get('ir.model.fields')
378         ids = obj.search(cr, uid, args)
379         records = obj.read(cr, uid, ids)
380         for record in records:
381             id = record['id']
382             field = record['name']
383
384             if record['ttype'] == 'many2one':
385                 rel = record['relation']
386                 res = get_fields(cr, uid, field, record['relation'])
387                 for rs in res:
388                     result.append(rs)
389
390             result.append((id, field))
391
392         for rs in result:
393             obj.write(cr, uid, [rs[0]], {'complete_name':rs[1]})
394
395         iids = []
396         for rs in result:
397             iids.append(rs[0])
398
399         result = super(ir_model_fields, self).name_search(cr, uid, name, [('complete_name','ilike',name), ('id','in',iids)], operator, context, limit)
400
401         return result
402
403 ir_model_fields()
404
405 class server_object_lines(osv.osv):
406     _name = 'ir.server.object.lines'
407     _sequence = 'ir_actions_id_seq'
408     _columns = {
409         'server_id': fields.many2one('ir.actions.server', 'Object Mapping'),
410         'col1': fields.many2one('ir.model.fields', 'Destination', required=True),
411         'value': fields.text('Value', required=True),
412         'type': fields.selection([
413             ('value','Value'),
414             ('equation','Formula')
415         ], 'Type', required=True, size=32, change_default=True),
416     }
417     _defaults = {
418         'type': lambda *a: 'equation',
419     }
420 server_object_lines()
421
422 ##
423 # Actions that are run on the server side
424 #
425 class actions_server(osv.osv):
426
427     def _select_signals(self, cr, uid, context={}):
428         cr.execute("select distinct t.signal as key, t.signal || ' - [ ' || w.osv || ' ] ' as val from wkf w, wkf_activity a, wkf_transition t "\
429                         " where w.id = a.wkf_id " \
430                         " and t.act_from = a.wkf_id " \
431                         " or t.act_to = a.wkf_id and t.signal not in (null, NULL)")
432         result = cr.fetchall() or []
433         res = []
434         for rs in result:
435             if not rs[0] == None and not rs[1] == None:
436                 res.append(rs)
437         return res
438
439     _name = 'ir.actions.server'
440     _table = 'ir_act_server'
441     _sequence = 'ir_actions_id_seq'
442     _order = 'sequence'
443     _columns = {
444         '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),
445         '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"),
446         'state': fields.selection([
447             ('client_action','Client Action'),
448             ('dummy','Dummy'),
449             ('loop','Iteration'),
450             ('code','Python Code'),
451             ('trigger','Trigger'),
452             ('email','Email'),
453             ('sms','SMS'),
454             ('object_create','Create Object'),
455             ('object_write','Write Object'),
456             ('other','Multi Actions'),
457         ], 'Action Type', required=True, size=32, help="Type of the Action that is to be executed"),
458         'code':fields.text('Python Code', help="Python code to be executed"),
459         '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."),
460         'model_id': fields.many2one('ir.model', 'Object', required=True, help="Select the object on which the action will work (read, write, create)."),
461         'action_id': fields.many2one('ir.actions.actions', 'Client Action', help="Select the Action Window, Report, Wizard to be executed."),
462         'trigger_name': fields.selection(_select_signals, string='Trigger Name', size=128, help="Select the Signal name that is to be used as the trigger."),
463         'wkf_model_id': fields.many2one('ir.model', 'Workflow On', help="Workflow to be executed on this model."),
464         'trigger_obj_id': fields.many2one('ir.model.fields','Trigger On', help="Select the object from the model on which the workflow will executed."),
465         '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"),
466         '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 ]]`"),
467         '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 ]]`"),
468         '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"),
469         'sms': fields.char('SMS', size=160, translate=True),
470         'child_ids': fields.many2many('ir.actions.server', 'rel_server_actions', 'server_id', 'action_id', 'Other Actions'),
471         'usage': fields.char('Action Usage', size=32),
472         'type': fields.char('Action Type', size=32, required=True),
473         '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."),
474         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Field Mappings.'),
475         '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."),
476         '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."),
477         '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."),
478         '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`."),
479     }
480     _defaults = {
481         'state': lambda *a: 'dummy',
482         'condition': lambda *a: 'True',
483         'type': lambda *a: 'ir.actions.server',
484         'sequence': lambda *a: 5,
485         'code': lambda *a: """# You can use the following variables
486 #    - object
487 #    - object2
488 #    - time
489 #    - cr
490 #    - uid
491 #    - ids
492 # If you plan to return an action, assign: action = {...}
493 """,
494     }
495
496     def get_email(self, cr, uid, action, context):
497         logger = netsvc.Logger()
498         obj_pool = self.pool.get(action.model_id.model)
499         id = context.get('active_id')
500         obj = obj_pool.browse(cr, uid, id)
501
502         fields = None
503
504         if '/' in action.email.complete_name:
505             fields = action.email.complete_name.split('/')
506         elif '.' in action.email.complete_name:
507             fields = action.email.complete_name.split('.')
508
509         for field in fields:
510             try:
511                 obj = getattr(obj, field)
512             except Exception,e :
513                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (field))
514
515         return obj
516
517     def get_mobile(self, cr, uid, action, context):
518         logger = netsvc.Logger()
519         obj_pool = self.pool.get(action.model_id.model)
520         id = context.get('active_id')
521         obj = obj_pool.browse(cr, uid, id)
522
523         fields = None
524
525         if '/' in action.mobile.complete_name:
526             fields = action.mobile.complete_name.split('/')
527         elif '.' in action.mobile.complete_name:
528             fields = action.mobile.complete_name.split('.')
529
530         for field in fields:
531             try:
532                 obj = getattr(obj, field)
533             except Exception,e :
534                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (field))
535
536         return obj
537
538     def merge_message(self, cr, uid, keystr, action, context):
539         logger = netsvc.Logger()
540         def merge(match):
541             obj_pool = self.pool.get(action.model_id.model)
542             id = context.get('active_id')
543             obj = obj_pool.browse(cr, uid, id)
544             exp = str(match.group()[2:-2]).strip()
545             result = eval(exp, {'object':obj, 'context': context,'time':time})
546             if result in (None, False):
547                 return str("--------")
548             return str(result)
549         
550         com = re.compile('(\[\[.+?\]\])')
551         message = com.sub(merge, keystr)
552         
553         return message
554
555     # Context should contains:
556     #   ids : original ids
557     #   id  : current id of the object
558     # OUT:
559     #   False : Finnished correctly
560     #   ACTION_ID : Action to launch
561     
562     def run(self, cr, uid, ids, context={}):
563         logger = netsvc.Logger()
564         
565         for action in self.browse(cr, uid, ids, context):
566             obj_pool = self.pool.get(action.model_id.model)
567             obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
568             cxt = {
569                 'context':context, 
570                 'object': obj, 
571                 'time':time,
572                 'cr': cr,
573                 'pool' : self.pool,
574                 'uid' : uid
575             }
576             expr = eval(str(action.condition), cxt)
577             if not expr:
578                 continue
579             
580             if action.state=='client_action':
581                 if not action.action_id:
582                     raise osv.except_osv(_('Error'), _("Please specify an action to launch !")) 
583                 result = self.pool.get(action.action_id.type).read(cr, uid, action.action_id.id, context=context)
584                 return result
585
586             if action.state == 'code':
587                 localdict = {
588                     'self': self.pool.get(action.model_id.model),
589                     'context': context,
590                     'time': time,
591                     'ids': ids,
592                     'cr': cr,
593                     'uid': uid,
594                     'obj':obj
595                 }
596                 exec action.code in localdict
597                 if 'action' in localdict:
598                     return localdict['action']
599
600             if action.state == 'email':
601                 user = config['email_from']
602                 address = str(action.email)
603                 try:
604                     address =  eval(str(action.email), cxt)
605                 except:
606                     pass
607                 
608                 if not address:
609                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Partner Email address not Specified!')
610                     continue
611                 if not user:
612                     raise osv.except_osv(_('Error'), _("Please specify server option --smtp-from !"))
613                 
614                 subject = self.merge_message(cr, uid, str(action.subject), action, context)
615                 body = self.merge_message(cr, uid, str(action.message), action, context)
616                 
617                 if tools.email_send(user, [address], subject, body, debug=False, subtype='html') == True:
618                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (address))
619                 else:
620                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (address))
621
622             if action.state == 'trigger':
623                 wf_service = netsvc.LocalService("workflow")
624                 model = action.wkf_model_id.model
625                 obj_pool = self.pool.get(action.model_id.model)
626                 res_id = self.pool.get(action.model_id.model).read(cr, uid, [context.get('active_id')], [action.trigger_obj_id.name])
627                 id = res_id [0][action.trigger_obj_id.name]
628                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
629
630             if action.state == 'sms':
631                 #TODO: set the user and password from the system
632                 # for the sms gateway user / password
633                 api_id = ''
634                 text = action.sms
635                 to = self.get_mobile(cr, uid, action, context)
636                 #TODO: Apply message mearge with the field
637                 if tools.sms_send(user, password, api_id, text, to) == True:
638                     logger.notifyChannel('sms', netsvc.LOG_INFO, 'SMS successfully send to : %s' % (action.address))
639                 else:
640                     logger.notifyChannel('sms', netsvc.LOG_ERROR, 'Failed to send SMS to : %s' % (action.address))
641             
642             if action.state == 'other':
643                 res = []
644                 for act in action.child_ids:
645                     context['active_id'] = context['active_ids'][0]
646                     result = self.run(cr, uid, [act.id], context)
647                     if result:
648                         res.append(result)
649                     
650                 return res
651             
652             if action.state == 'loop':
653                 obj_pool = self.pool.get(action.model_id.model)
654                 obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
655                 cxt = {
656                     'context':context, 
657                     'object': obj, 
658                     'time':time,
659                     'cr': cr,
660                     'pool' : self.pool,
661                     'uid' : uid
662                 }
663                 expr = eval(str(action.expression), cxt)
664                 context['object'] = obj
665                 for i in expr:
666                     context['active_id'] = i.id
667                     result = self.run(cr, uid, [action.loop_action.id], context)
668             
669             if action.state == 'object_write':
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                         cxt = {'context':context, 'object': obj, 'time':time}
677                         expr = eval(euq, cxt)
678                     else:
679                         expr = exp.value
680                     res[exp.col1.name] = expr
681
682                 if not action.write_id:
683                     if not action.srcmodel_id:
684                         obj_pool = self.pool.get(action.model_id.model)
685                         obj_pool.write(cr, uid, [context.get('active_id')], res)
686                     else:
687                         write_id = context.get('active_id')
688                         obj_pool = self.pool.get(action.srcmodel_id.model)
689                         obj_pool.write(cr, uid, [write_id], res)
690                         
691                 elif action.write_id:
692                     obj_pool = self.pool.get(action.srcmodel_id.model)
693                     rec = self.pool.get(action.model_id.model).browse(cr, uid, context.get('active_id'))
694                     id = eval(action.write_id, {'object': rec})
695                     try:
696                         id = int(id)
697                     except:
698                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
699                     
700                     if type(id) != type(1):
701                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
702                     write_id = id
703                     obj_pool.write(cr, uid, [write_id], res)
704
705             if action.state == 'object_create':
706                 res = {}
707                 for exp in action.fields_lines:
708                     euq = exp.value
709                     if exp.type == 'equation':
710                         obj_pool = self.pool.get(action.model_id.model)
711                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
712                         expr = eval(euq, {'context':context, 'object': obj, 'time':time})
713                     else:
714                         expr = exp.value
715                     res[exp.col1.name] = expr
716
717                 obj_pool = None
718                 res_id = False
719                 obj_pool = self.pool.get(action.srcmodel_id.model)
720                 res_id = obj_pool.create(cr, uid, res)
721                 cr.commit()
722                 if action.record_id:
723                     self.pool.get(action.model_id.model).write(cr, uid, [context.get('active_id')], {action.record_id.name:res_id})
724
725         return False
726
727 actions_server()
728
729 class act_window_close(osv.osv):
730     _name = 'ir.actions.act_window_close'
731     _inherit = 'ir.actions.actions'
732     _table = 'ir_actions'
733     _defaults = {
734         'type': lambda *a: 'ir.actions.act_window_close',
735     }
736 act_window_close()
737
738 # This model use to register action services.
739 # if action type is 'configure', it will be start on configuration wizard.
740 # if action type is 'service',
741 #                - if start_type= 'at once', it will be start at one time on start date
742 #                - if start_type='auto', it will be start on auto starting from start date, and stop on stop date
743 #                - if start_type="manual", it will start and stop on manually 
744 class ir_actions_todo(osv.osv):
745     _name = 'ir.actions.todo'    
746     _columns={
747         'name':fields.char('Name',size=64,required=True, select=True),
748         'note':fields.text('Text', translate=True),
749         'start_date': fields.datetime('Start Date'),
750         'end_date': fields.datetime('End Date'),
751         'action_id':fields.many2one('ir.actions.act_window', 'Action', select=True,required=True, ondelete='cascade'),
752         'sequence':fields.integer('Sequence'),
753         'active': fields.boolean('Active'),
754         'type':fields.selection([('configure', 'Configure'),('service', 'Service'),('other','Other')], string='Type', required=True),
755         'start_on':fields.selection([('at_once', 'At Once'),('auto', 'Auto'),('manual','Manual')], string='Start On'),
756         'groups_id': fields.many2many('res.groups', 'res_groups_act_todo_rel', 'act_todo_id', 'group_id', 'Groups'),
757         'users_id': fields.many2many('res.users', 'res_users_act_todo_rel', 'act_todo_id', 'user_id', 'Users'),
758         'state':fields.selection([('open', 'Not Started'),('done', 'Done'),('skip','Skipped'),('cancel','Cancel')], string='State', required=True)
759     }
760     _defaults={
761         'state': lambda *a: 'open',
762         'sequence': lambda *a: 10,
763         'active':lambda *a:True,
764         'type':lambda *a:'configure'
765     }
766     _order="sequence"
767 ir_actions_todo()
768
769 # This model to use run all configuration actions
770 class ir_actions_configuration_wizard(osv.osv_memory):
771     _name='ir.actions.configuration.wizard'
772     def next_configuration_action(self,cr,uid,context={}):
773         item_obj = self.pool.get('ir.actions.todo')
774         item_ids = item_obj.search(cr, uid, [('type','=','configure'),('state', '=', 'open'),('active','=',True)], limit=1, context=context)
775         if item_ids and len(item_ids):
776             item = item_obj.browse(cr, uid, item_ids[0], context=context)
777             return item
778         return False
779     def _get_action_name(self, cr, uid, context={}):
780         next_action=self.next_configuration_action(cr,uid,context=context)        
781         if next_action:
782             return next_action.note
783         else:
784             return "Your database is now fully configured.\n\nClick 'Continue' and enjoy your OpenERP experience..."
785         return False
786
787     def _get_action(self, cr, uid, context={}):
788         next_action=self.next_configuration_action(cr,uid,context=context)
789         if next_action:
790             return next_action.id
791         return False
792
793     def _progress_get(self,cr,uid, context={}):
794         total = self.pool.get('ir.actions.todo').search_count(cr, uid, [], context)
795         todo = self.pool.get('ir.actions.todo').search_count(cr, uid, [('type','=','configure'),('active','=',True),('state','<>','open')], context)
796         if total > 0.0:
797             return max(5.0,round(todo*100/total))
798         else:
799             return 100.0
800
801     _columns = {
802         'name': fields.text('Next Wizard',readonly=True),
803         'progress': fields.float('Configuration Progress', readonly=True),
804         'item_id':fields.many2one('ir.actions.todo', 'Next Configuration Wizard',invisible=True, readonly=True),
805     }
806     _defaults={
807         'progress': _progress_get,
808         'item_id':_get_action,
809         'name':_get_action_name,
810     }
811     def button_next(self,cr,uid,ids,context=None):
812         user_action=self.pool.get('res.users').browse(cr,uid,uid)
813         act_obj=self.pool.get(user_action.menu_id.type)
814         action_ids=act_obj.search(cr,uid,[('name','=',user_action.menu_id.name)])
815         action_open=act_obj.browse(cr,uid,action_ids)[0]
816         if context.get('menu',False):
817             return{
818                 'view_type': action_open.view_type,
819                 'view_id':action_open.view_id and [action_open.view_id.id] or False,
820                 'res_model': action_open.res_model,
821                 'type': action_open.type,
822                 'domain':action_open.domain
823             }
824         return {'type':'ir.actions.act_window_close'}
825
826     def button_skip(self,cr,uid,ids,context=None):
827         item_obj = self.pool.get('ir.actions.todo')
828         item_id=self.read(cr,uid,ids)[0]['item_id']
829         if item_id:
830             item = item_obj.browse(cr, uid, item_id, context=context)
831             item_obj.write(cr, uid, item.id, {
832                 'state': 'skip',
833                 }, context=context)
834             return{
835                 'view_type': 'form',
836                 "view_mode": 'form',
837                 'res_model': 'ir.actions.configuration.wizard',
838                 'type': 'ir.actions.act_window',
839                 'target':'new',
840             }
841         return self.button_next(cr, uid, ids, context)
842
843     def button_continue(self, cr, uid, ids, context=None):
844         item_obj = self.pool.get('ir.actions.todo')
845         item_id=self.read(cr,uid,ids)[0]['item_id']
846         if item_id:
847             item = item_obj.browse(cr, uid, item_id, context=context)
848             item_obj.write(cr, uid, item.id, {
849                 'state': 'done',
850                 }, context=context)
851             return{
852                   'view_mode': item.action_id.view_mode,
853                   'view_type': item.action_id.view_type,
854                   'view_id':item.action_id.view_id and [item.action_id.view_id.id] or False,
855                   'res_model': item.action_id.res_model,
856                   'type': item.action_id.type,
857                   'target':item.action_id.target,
858             }
859         return self.button_next(cr, uid, ids, context)
860 ir_actions_configuration_wizard()
861
862 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
863