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