[IMP] Update the copyright to 2009
[odoo/odoo.git] / bin / addons / base / ir / ir_actions.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution    
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import fields,osv
24 import tools
25 import time
26 from tools.config import config
27 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             ('odt', 'odt'),
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=800):
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 and t.signal not in (null, NULL)")
374         result = cr.fetchall() or []
375         res = []
376         for rs in result:
377             if not rs[0] == None and not rs[1] == None:
378                 res.append(rs)
379         return res
380
381     _name = 'ir.actions.server'
382     _table = 'ir_act_server'
383     _sequence = 'ir_actions_id_seq'
384     _order = 'sequence'
385     _columns = {
386         'name': fields.char('Action Name', required=True, size=64, help="Easy to Refer action by name i.e. One Sales Order -> Many Invoice"),
387         'condition' : fields.char('Condition', size=256, required=True, help="Condition that is to be test before execute action,  i.e : object.list_price > object.cost_price"),
388         'state': fields.selection([
389             ('client_action','Client Action'),
390             ('dummy','Dummy'),
391             ('loop','Iteration'),
392             ('code','Python Code'),
393             ('trigger','Trigger'),
394             ('email','Email'),
395             ('sms','SMS'),
396             ('object_create','Create Object'),
397             ('object_write','Write Object'),
398             ('other','Multi Actions'),
399         ], 'Action Type', required=True, size=32, help="Type of the Action that is to be execute"),
400         'code':fields.text('Python Code', help="python code to be execute"),
401         'sequence': fields.integer('Sequence', help="Important when you deal with the multi action, the execution order will be decided based on this, low number higher priority"),
402         'model_id': fields.many2one('ir.model', 'Object', required=True, help="select the obect on which the action will work (read, write, create)"),
403         'action_id': fields.many2one('ir.actions.actions', 'Client Action', help="Select the Ation Window, Report, Wizard to be execute"),
404         'trigger_name': fields.selection(_select_signals, string='Trigger Name', size=128, help="Select the Signal name that is to be "),
405         'wkf_model_id': fields.many2one('ir.model', 'Workflow on', help="Workflow to be execute on which model"),
406         'trigger_obj_id': fields.many2one('ir.model.fields','Trigger On', help="select the object from the model on which the workflow will execute"),
407         'email': fields.char('Email Address', size=512, help="provides the fiels that will refer to the tiny to fetch the email address, i.e. you select the invoice, then `object.invoice_address_id.email` is the field which give the correct address"),
408         'subject': fields.char('Subject', size=1024, translate=True, help="Specify the subject, you can use the fields from the object. like `Hello [[ object.partner_id.name ]]`"),
409         'message': fields.text('Message', translate=True, help="Specify the Message, you can use the fields from the object. like `Dear [[ object.partner_id.name ]]`"),
410         'mobile': fields.char('Mobile No', size=512, help="provides the fiels that will refer to the tiny to fetch the mobile number, i.e. you select the invoice, then `object.invoice_address_id.mobile` is the field which give the correct mobile number"),
411         'sms': fields.char('SMS', size=160, translate=True),
412         'child_ids': fields.many2many('ir.actions.server', 'rel_server_actions', 'server_id', 'action_id', 'Others Actions'),
413         'usage': fields.char('Action Usage', size=32),
414         'type': fields.char('Action Type', size=32, required=True),
415         '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"),
416         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id', 'Fields Mapping'),
417         'record_id':fields.many2one('ir.model.fields', 'Create Id', help="Provide the field name from where the record id stores after the create operations, if its empty, you can not track the new record"),
418         'write_id':fields.char('Write Id', size=256, help="Provide the field name from where the record id refer for the write operation, if its empty it will refer to the active id of the object"),
419         'loop_action':fields.many2one('ir.actions.server', 'Loop Action', help="select the action, which will be executes. Loop action will not be avaliable inside loop"),
420         'expression':fields.char('Loop Expression', size=512, help="enter the field/expression that will return the list, i.e. select the sale order in Object, and we can have loop on sales order line. Expression = `object.order_line`"),
421     }
422     _defaults = {
423         'state': lambda *a: 'dummy',
424         'condition': lambda *a: 'True',
425         'type': lambda *a: 'ir.actions.server',
426         'sequence': lambda *a: 5,
427         'code': lambda *a: """# You can use the following variables
428 #    - object
429 #    - object2
430 #    - time
431 #    - cr
432 #    - uid
433 #    - ids
434 # If you plan to return an action, assign: action = {...}
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     def get_mobile(self, cr, uid, action, context):
460         logger = netsvc.Logger()
461         obj_pool = self.pool.get(action.model_id.model)
462         id = context.get('active_id')
463         obj = obj_pool.browse(cr, uid, id)
464
465         fields = None
466
467         if '/' in action.mobile.complete_name:
468             fields = action.mobile.complete_name.split('/')
469         elif '.' in action.mobile.complete_name:
470             fields = action.mobile.complete_name.split('.')
471
472         for field in fields:
473             try:
474                 obj = getattr(obj, field)
475             except Exception,e :
476                 logger.notifyChannel('Workflow', netsvc.LOG_ERROR, 'Failed to parse : %s' % (field))
477
478         return obj
479
480     def merge_message(self, cr, uid, keystr, action, context):
481         logger = netsvc.Logger()
482         def merge(match):
483             obj_pool = self.pool.get(action.model_id.model)
484             id = context.get('active_id')
485             obj = obj_pool.browse(cr, uid, id)
486             exp = str(match.group()[2:-2]).strip()
487             result = eval(exp, {'object':obj, 'context': context,'time':time})
488             if result in (None, False):
489                 return str("--------")
490             return str(result)
491         
492         com = re.compile('(\[\[.+?\]\])')
493         message = com.sub(merge, keystr)
494         
495         return message
496
497     # Context should contains:
498     #   ids : original ids
499     #   id  : current id of the object
500     # OUT:
501     #   False : Finnished correctly
502     #   ACTION_ID : Action to launch
503     
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 = str(action.email)
544                 try:
545                     address =  eval(str(action.email), cxt)
546                 except:
547                     pass
548                 
549                 if not address:
550                     raise osv.except_osv(_('Error'), _("Please specify the Partner Email address !"))
551                 if not user:
552                     raise osv.except_osv(_('Error'), _("Please specify server option --smtp-from !"))
553                 
554                 subject = self.merge_message(cr, uid, str(action.subject), action, context)
555                 body = self.merge_message(cr, uid, str(action.message), action, context)
556                 
557                 if tools.email_send(user, [address], subject, body, debug=False, subtype='html') == True:
558                     logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (address))
559                 else:
560                     logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (address))
561
562             if action.state == 'trigger':
563                 wf_service = netsvc.LocalService("workflow")
564                 model = action.wkf_model_id.model
565                 obj_pool = self.pool.get(action.model_id.model)
566                 res_id = self.pool.get(action.model_id.model).read(cr, uid, [context.get('active_id')], [action.trigger_obj_id.name])
567                 id = res_id [0][action.trigger_obj_id.name]
568                 wf_service.trg_validate(uid, model, int(id), action.trigger_name, cr)
569
570             if action.state == 'sms':
571                 #TODO: set the user and password from the system
572                 # for the sms gateway user / password
573                 api_id = ''
574                 text = action.sms
575                 to = self.get_mobile(cr, uid, action, context)
576                 #TODO: Apply message mearge with the field
577                 if tools.sms_send(user, password, api_id, text, to) == True:
578                     logger.notifyChannel('sms', netsvc.LOG_INFO, 'SMS successfully send to : %s' % (action.address))
579                 else:
580                     logger.notifyChannel('sms', netsvc.LOG_ERROR, 'Failed to send SMS to : %s' % (action.address))
581             
582             if action.state == 'other':
583                 res = []
584                 for act in action.child_ids:
585                     context['active_id'] = context['active_ids'][0]
586                     result = self.run(cr, uid, [act.id], context)
587                     if result:
588                         res.append(result)
589                     
590                 return res
591             
592             if action.state == 'loop':
593                 obj_pool = self.pool.get(action.model_id.model)
594                 obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
595                 cxt = {
596                     'context':context, 
597                     'object': obj, 
598                     'time':time,
599                     'cr': cr,
600                     'pool' : self.pool,
601                     'uid' : uid
602                 }
603                 expr = eval(str(action.expression), cxt)
604                 context['object'] = obj
605                 for i in expr:
606                     context['active_id'] = i.id
607                     result = self.run(cr, uid, [action.loop_action.id], context)
608             
609             if action.state == 'object_write':
610                 res = {}
611                 for exp in action.fields_lines:
612                     euq = exp.value
613                     if exp.type == 'equation':
614                         obj_pool = self.pool.get(action.model_id.model)
615                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
616                         cxt = {'context':context, 'object': obj, 'time':time}
617                         expr = eval(euq, cxt)
618                     else:
619                         expr = exp.value
620                     res[exp.col1.name] = expr
621
622                 if not action.write_id:
623                     if not action.srcmodel_id:
624                         obj_pool = self.pool.get(action.model_id.model)
625                         obj_pool.write(cr, uid, [context.get('active_id')], res)
626                     else:
627                         write_id = context.get('active_id')
628                         obj_pool = self.pool.get(action.srcmodel_id.model)
629                         obj_pool.write(cr, uid, [write_id], res)
630                         
631                 elif action.write_id:
632                     obj_pool = self.pool.get(action.srcmodel_id.model)
633                     rec = self.pool.get(action.model_id.model).browse(cr, uid, context.get('active_id'))
634                     id = eval(action.write_id, {'object': rec})
635                     try:
636                         id = int(id)
637                     except:
638                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
639                     
640                     if type(id) != type(1):
641                         raise osv.except_osv(_('Error'), _("Problem in configuration `Record Id` in Server Action!"))
642                     write_id = id
643                     obj_pool.write(cr, uid, [write_id], res)
644
645             if action.state == 'object_create':
646                 res = {}
647                 for exp in action.fields_lines:
648                     euq = exp.value
649                     if exp.type == 'equation':
650                         obj_pool = self.pool.get(action.model_id.model)
651                         obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
652                         expr = eval(euq, {'context':context, 'object': obj, 'time':time})
653                     else:
654                         expr = exp.value
655                     res[exp.col1.name] = expr
656
657                 obj_pool = None
658                 res_id = False
659                 obj_pool = self.pool.get(action.srcmodel_id.model)
660                 res_id = obj_pool.create(cr, uid, res)
661                 cr.commit()
662                 if action.record_id:
663                     self.pool.get(action.model_id.model).write(cr, uid, [context.get('active_id')], {action.record_id.name:res_id})
664
665         return False
666
667 actions_server()
668
669 class act_window_close(osv.osv):
670     _name = 'ir.actions.act_window_close'
671     _table = 'ir_actions'
672     _sequence = 'ir_actions_id_seq'
673     _columns = {
674         'name': fields.char('Action Name', size=64, translate=True),
675         'type': fields.char('Action Type', size=32, required=True),
676     }
677     _defaults = {
678         'type': lambda *a: 'ir.actions.act_window_close',
679     }
680 act_window_close()
681
682 # This model use to register action services.
683 # if action type is 'configure', it will be start on configuration wizard.
684 # if action type is 'service',
685 #                - if start_type= 'at once', it will be start at one time on start date
686 #                - if start_type='auto', it will be start on auto starting from start date, and stop on stop date
687 #                - if start_type="manual", it will start and stop on manually 
688 class ir_actions_todo(osv.osv):
689     _name = 'ir.actions.todo'    
690     _columns={
691         'name':fields.char('Name',size=64,required=True, select=True),
692         'note':fields.text('Text', translate=True),
693         'start_date': fields.datetime('Start Date'),
694         'end_date': fields.datetime('End Date'),
695         'action_id':fields.many2one('ir.actions.act_window', 'Action', select=True,required=True, ondelete='cascade'),
696         'sequence':fields.integer('Sequence'),
697         'active': fields.boolean('Active'),
698         'type':fields.selection([('configure', 'Configure'),('service', 'Service'),('other','Other')], string='Type', required=True),
699         'start_on':fields.selection([('at_once', 'At Once'),('auto', 'Auto'),('manual','Manual')], string='Start On'),
700         'groups_id': fields.many2many('res.groups', 'res_groups_act_todo_rel', 'act_todo_id', 'group_id', 'Groups'),
701         'users_id': fields.many2many('res.users', 'res_users_act_todo_rel', 'act_todo_id', 'user_id', 'Users'),
702         'state':fields.selection([('open', 'Not Started'),('done', 'Done'),('skip','Skipped'),('cancel','Cancel')], string='State', required=True)
703     }
704     _defaults={
705         'state': lambda *a: 'open',
706         'sequence': lambda *a: 10,
707         'active':lambda *a:True,
708         'type':lambda *a:'configure'
709     }
710     _order="sequence"
711 ir_actions_todo()
712
713 # This model to use run all configuration actions
714 class ir_actions_configuration_wizard(osv.osv_memory):
715     _name='ir.actions.configuration.wizard'
716     def next_configuration_action(self,cr,uid,context={}):
717         item_obj = self.pool.get('ir.actions.todo')
718         item_ids = item_obj.search(cr, uid, [('type','=','configure'),('state', '=', 'open'),('active','=',True)], limit=1, context=context)
719         if item_ids and len(item_ids):
720             item = item_obj.browse(cr, uid, item_ids[0], context=context)
721             return item
722         return False
723     def _get_action_name(self, cr, uid, context={}):
724         next_action=self.next_configuration_action(cr,uid,context=context)        
725         if next_action:
726             return next_action.note
727         else:
728             return "Your database is now fully configured.\n\nClick 'Continue' and enjoy your OpenERP experience..."
729         return False
730
731     def _get_action(self, cr, uid, context={}):
732         next_action=self.next_configuration_action(cr,uid,context=context)
733         if next_action:           
734             return next_action.id
735         return False
736
737     def _progress_get(self,cr,uid, context={}):
738         total = self.pool.get('ir.actions.todo').search_count(cr, uid, [], context)
739         todo = self.pool.get('ir.actions.todo').search_count(cr, uid, [('type','=','configure'),('active','=',True),('state','<>','open')], context)
740         return max(5.0,round(todo*100/total))
741
742     _columns = {
743         'name': fields.text('Next Wizard',readonly=True),
744         'progress': fields.float('Configuration Progress', readonly=True),
745         'item_id':fields.many2one('ir.actions.todo', 'Next Configuration Wizard',invisible=True, readonly=True),
746     }
747     _defaults={
748         'progress': _progress_get,
749         'item_id':_get_action,
750         'name':_get_action_name,
751     }
752     def button_next(self,cr,uid,ids,context=None):
753         user_action=self.pool.get('res.users').browse(cr,uid,uid)
754         act_obj=self.pool.get(user_action.menu_id.type)
755         action_ids=act_obj.search(cr,uid,[('name','=',user_action.menu_id.name)])
756         action_open=act_obj.browse(cr,uid,action_ids)[0]
757         if context.get('menu',False):
758             return{
759                 'view_type': action_open.view_type,
760                 'view_id':action_open.view_id and [action_open.view_id.id] or False,
761                 'res_model': action_open.res_model,
762                 'type': action_open.type,
763                 'domain':action_open.domain
764             }
765         return {'type':'ir.actions.act_window_close'}
766
767     def button_skip(self,cr,uid,ids,context=None):
768         item_obj = self.pool.get('ir.actions.todo')
769         item_id=self.read(cr,uid,ids)[0]['item_id']
770         if item_id:
771             item = item_obj.browse(cr, uid, item_id, context=context)
772             item_obj.write(cr, uid, item.id, {
773                 'state': 'skip',
774                 }, context=context)
775             return{
776                 'view_type': 'form',
777                 "view_mode": 'form',
778                 'res_model': 'ir.actions.configuration.wizard',
779                 'type': 'ir.actions.act_window',
780                 'target':'new',
781             }
782         return self.button_next(cr, uid, ids, context)
783
784     def button_continue(self, cr, uid, ids, context=None):
785         item_obj = self.pool.get('ir.actions.todo')
786         item_id=self.read(cr,uid,ids)[0]['item_id']
787         if item_id:
788             item = item_obj.browse(cr, uid, item_id, context=context)
789             item_obj.write(cr, uid, item.id, {
790                 'state': 'done',
791                 }, context=context)
792             return{
793                   'view_mode': item.action_id.view_mode,
794                   'view_type': item.action_id.view_type,
795                   'view_id':item.action_id.view_id and [item.action_id.view_id.id] or False,
796                   'res_model': item.action_id.res_model,
797                   'type': item.action_id.type,
798                   'target':item.action_id.target,
799             }
800         return self.button_next(cr, uid, ids, context)
801 ir_actions_configuration_wizard()
802
803 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
804