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