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