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