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