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