[MERGE]with lp:openobject-server
[odoo/odoo.git] / openerp / addons / base / ir / ir_actions.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2013 OpenERP S.A. <http://www.openerp.com>
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from functools import partial
23 import logging
24 import operator
25 import os
26 import time
27
28 import openerp
29 from openerp import SUPERUSER_ID
30 from openerp import tools
31 from openerp import workflow
32 from openerp.osv import fields, osv
33 from openerp.osv.orm import browse_record
34 import openerp.report.interface
35 from openerp.report.report_sxw import report_sxw, report_rml
36 from openerp.tools.safe_eval import safe_eval as eval
37 from openerp.tools.translate import _
38 import openerp.workflow
39
40 _logger = logging.getLogger(__name__)
41
42 class actions(osv.osv):
43     _name = 'ir.actions.actions'
44     _table = 'ir_actions'
45     _order = 'name'
46     _columns = {
47         'name': fields.char('Name', size=64, required=True),
48         'type': fields.char('Action Type', required=True, size=32),
49         'usage': fields.char('Action Usage', size=32),
50         'help': fields.text('Action description',
51             help='Optional help text for the users with a description of the target view, such as its usage and purpose.',
52             translate=True),
53     }
54     _defaults = {
55         'usage': lambda *a: False,
56     }
57
58
59 class ir_actions_report_xml(osv.osv):
60
61     def _report_content(self, cursor, user, ids, name, arg, context=None):
62         res = {}
63         for report in self.browse(cursor, user, ids, context=context):
64             data = report[name + '_data']
65             if not data and report[name[:-8]]:
66                 fp = None
67                 try:
68                     fp = tools.file_open(report[name[:-8]], mode='rb')
69                     data = fp.read()
70                 except:
71                     data = False
72                 finally:
73                     if fp:
74                         fp.close()
75             res[report.id] = data
76         return res
77
78     def _report_content_inv(self, cursor, user, id, name, value, arg, context=None):
79         self.write(cursor, user, id, {name+'_data': value}, context=context)
80
81     def _report_sxw(self, cursor, user, ids, name, arg, context=None):
82         res = {}
83         for report in self.browse(cursor, user, ids, context=context):
84             if report.report_rml:
85                 res[report.id] = report.report_rml.replace('.rml', '.sxw')
86             else:
87                 res[report.id] = False
88         return res
89
90     def _lookup_report(self, cr, name):
91         """
92         Look up a report definition.
93         """
94         opj = os.path.join
95
96         # First lookup in the deprecated place, because if the report definition
97         # has not been updated, it is more likely the correct definition is there.
98         # Only reports with custom parser sepcified in Python are still there.
99         if 'report.' + name in openerp.report.interface.report_int._reports:
100             new_report = openerp.report.interface.report_int._reports['report.' + name]
101         else:
102             cr.execute("SELECT * FROM ir_act_report_xml WHERE report_name=%s", (name,))
103             r = cr.dictfetchone()
104             if r:
105                 if r['report_rml'] or r['report_rml_content_data']:
106                     if r['parser']:
107                         kwargs = { 'parser': operator.attrgetter(r['parser'])(openerp.addons) }
108                     else:
109                         kwargs = {}
110                     new_report = report_sxw('report.'+r['report_name'], r['model'],
111                             opj('addons',r['report_rml'] or '/'), header=r['header'], register=False, **kwargs)
112                 elif r['report_xsl'] and r['report_xml']:
113                     new_report = report_rml('report.'+r['report_name'], r['model'],
114                             opj('addons',r['report_xml']),
115                             r['report_xsl'] and opj('addons',r['report_xsl']), register=False)
116                 else:
117                     raise Exception, "Unhandled report type: %s" % r
118             else:
119                 raise Exception, "Required report does not exist: %s" % r
120
121         return new_report
122
123     def render_report(self, cr, uid, res_ids, name, data, context=None):
124         """
125         Look up a report definition and render the report for the provided IDs.
126         """
127         new_report = self._lookup_report(cr, name)
128         return new_report.create(cr, uid, res_ids, data, context)
129
130     _name = 'ir.actions.report.xml'
131     _inherit = 'ir.actions.actions'
132     _table = 'ir_act_report_xml'
133     _sequence = 'ir_actions_id_seq'
134     _order = 'name'
135     _columns = {
136         'name': fields.char('Name', size=64, required=True, translate=True),
137         'model': fields.char('Object', size=64, required=True),
138         'type': fields.char('Action Type', size=32, required=True),
139         'report_name': fields.char('Service Name', size=64, required=True),
140         'usage': fields.char('Action Usage', size=32),
141         'report_type': fields.char('Report Type', size=32, required=True, help="Report Type, e.g. pdf, html, raw, sxw, odt, html2html, mako2html, ..."),
142         'groups_id': fields.many2many('res.groups', 'res_groups_report_rel', 'uid', 'gid', 'Groups'),
143         '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."),
144         '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.'),
145         '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.'),
146         'auto': fields.boolean('Custom Python Parser'),
147
148         'header': fields.boolean('Add RML Header', help="Add or not the corporate RML header"),
149
150         'report_xsl': fields.char('XSL Path', size=256),
151         'report_xml': fields.char('XML Path', size=256, help=''),
152
153         # Pending deprecation... to be replaced by report_file as this object will become the default report object (not so specific to RML anymore)
154         'report_rml': fields.char('Main Report File Path', size=256, help="The path to the main report file (depending on Report Type) or NULL if the content is in another data field"),
155         # temporary related field as report_rml is pending deprecation - this field will replace report_rml after v6.0
156         'report_file': fields.related('report_rml', type="char", size=256, required=False, readonly=False, string='Report File', help="The path to the main report file (depending on Report Type) or NULL if the content is in another field", store=True),
157
158         'report_sxw': fields.function(_report_sxw, type='char', string='SXW Path'),
159         'report_sxw_content_data': fields.binary('SXW Content'),
160         'report_rml_content_data': fields.binary('RML Content'),
161         'report_sxw_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='SXW Content',),
162         'report_rml_content': fields.function(_report_content, fnct_inv=_report_content_inv, type='binary', string='RML Content'),
163
164         'parser': fields.char('Parser Class'),
165     }
166     _defaults = {
167         'type': 'ir.actions.report.xml',
168         'multi': False,
169         'auto': True,
170         'header': True,
171         'report_sxw_content': False,
172         'report_type': 'pdf',
173         'attachment': False,
174     }
175
176
177 class ir_actions_act_window(osv.osv):
178     _name = 'ir.actions.act_window'
179     _table = 'ir_act_window'
180     _inherit = 'ir.actions.actions'
181     _sequence = 'ir_actions_id_seq'
182     _order = 'name'
183
184     def _check_model(self, cr, uid, ids, context=None):
185         for action in self.browse(cr, uid, ids, context):
186             if action.res_model not in self.pool:
187                 return False
188             if action.src_model and action.src_model not in self.pool:
189                 return False
190         return True
191
192     def _invalid_model_msg(self, cr, uid, ids, context=None):
193         return _('Invalid model name in the action definition.')
194
195     _constraints = [
196         (_check_model, _invalid_model_msg, ['res_model','src_model'])
197     ]
198
199     def _views_get_fnc(self, cr, uid, ids, name, arg, context=None):
200         """Returns an ordered list of the specific view modes that should be
201            enabled when displaying the result of this action, along with the
202            ID of the specific view to use for each mode, if any were required.
203
204            This function hides the logic of determining the precedence between
205            the view_modes string, the view_ids o2m, and the view_id m2o that can
206            be set on the action.
207
208            :rtype: dict in the form { action_id: list of pairs (tuples) }
209            :return: { action_id: [(view_id, view_mode), ...], ... }, where view_mode
210                     is one of the possible values for ir.ui.view.type and view_id
211                     is the ID of a specific view to use for this mode, or False for
212                     the default one.
213         """
214         res = {}
215         for act in self.browse(cr, uid, ids):
216             res[act.id] = [(view.view_id.id, view.view_mode) for view in act.view_ids]
217             view_ids_modes = [view.view_mode for view in act.view_ids]
218             modes = act.view_mode.split(',')
219             missing_modes = [mode for mode in modes if mode not in view_ids_modes]
220             if missing_modes:
221                 if act.view_id and act.view_id.type in missing_modes:
222                     # reorder missing modes to put view_id first if present
223                     missing_modes.remove(act.view_id.type)
224                     res[act.id].append((act.view_id.id, act.view_id.type))
225                 res[act.id].extend([(False, mode) for mode in missing_modes])
226         return res
227
228     def _search_view(self, cr, uid, ids, name, arg, context=None):
229         res = {}
230         for act in self.browse(cr, uid, ids, context=context):
231             field_get = self.pool[act.res_model].fields_view_get(cr, uid,
232                 act.search_view_id and act.search_view_id.id or False,
233                 'search', context=context)
234             res[act.id] = str(field_get)
235         return res
236
237     _columns = {
238         'name': fields.char('Action Name', size=64, translate=True),
239         'type': fields.char('Action Type', size=32, required=True),
240         'view_id': fields.many2one('ir.ui.view', 'View Ref.', ondelete='cascade'),
241         'domain': fields.char('Domain Value',
242             help="Optional domain filtering of the destination data, as a Python expression"),
243         'context': fields.char('Context Value', required=True,
244             help="Context dictionary as Python expression, empty by default (Default: {})"),
245         'res_id': fields.integer('Record ID', help="Database ID of record to open in form view, when ``view_mode`` is set to 'form' only"),
246         'res_model': fields.char('Destination Model', size=64, required=True,
247             help="Model name of the object to open in the view window"),
248         'src_model': fields.char('Source Model', size=64,
249             help="Optional model name of the objects on which this action should be visible"),
250         'target': fields.selection([('current','Current Window'),('new','New Window'),('inline','Inline Edit'),('inlineview','Inline View')], 'Target Window'),
251         'view_mode': fields.char('View Mode', size=250, required=True,
252             help="Comma-separated list of allowed view modes, such as 'form', 'tree', 'calendar', etc. (Default: tree,form)"),
253         'view_type': fields.selection((('tree','Tree'),('form','Form')), string='View Type', required=True,
254             help="View type: Tree type to use for the tree view, set to 'tree' for a hierarchical tree view, or 'form' for a regular list view"),
255         'usage': fields.char('Action Usage', size=32,
256             help="Used to filter menu and home actions from the user form."),
257         'view_ids': fields.one2many('ir.actions.act_window.view', 'act_window_id', 'Views'),
258         'views': fields.function(_views_get_fnc, type='binary', string='Views',
259                help="This function field computes the ordered list of views that should be enabled " \
260                     "when displaying the result of an action, federating view mode, views and " \
261                     "reference view. The result is returned as an ordered list of pairs (view_id,view_mode)."),
262         'limit': fields.integer('Limit', help='Default limit for the list view'),
263         'auto_refresh': fields.integer('Auto-Refresh',
264             help='Add an auto-refresh on the view'),
265         'groups_id': fields.many2many('res.groups', 'ir_act_window_group_rel',
266             'act_id', 'gid', 'Groups'),
267         'search_view_id': fields.many2one('ir.ui.view', 'Search View Ref.'),
268         'filter': fields.boolean('Filter'),
269         'auto_search':fields.boolean('Auto Search'),
270         'search_view' : fields.function(_search_view, type='text', string='Search View'),
271         'multi': fields.boolean('Action on Multiple Doc.', help="If set to true, the action will not be displayed on the right toolbar of a form view"),
272     }
273
274     _defaults = {
275         'type': 'ir.actions.act_window',
276         'view_type': 'form',
277         'view_mode': 'tree,form',
278         'context': '{}',
279         'limit': 80,
280         'target': 'current',
281         'auto_refresh': 0,
282         'auto_search':True,
283         'multi': False,
284     }
285
286     def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
287         """ call the method get_empty_list_help of the model and set the window action help message
288         """
289         ids_int = isinstance(ids, (int, long))
290         if ids_int:
291             ids = [ids]
292         results = super(ir_actions_act_window, self).read(cr, uid, ids, fields=fields, context=context, load=load)
293
294         if not fields or 'help' in fields:
295             context = dict(context or {})
296             eval_dict = {
297                 'active_model': context.get('active_model'),
298                 'active_id': context.get('active_id'),
299                 'active_ids': context.get('active_ids'),
300                 'uid': uid,
301             }
302             for res in results:
303                 model = res.get('res_model')
304                 if model and self.pool.get(model):
305                     try:
306                         with tools.mute_logger("openerp.tools.safe_eval"):
307                             eval_context = eval(res['context'] or "{}", eval_dict) or {}
308                     except Exception:
309                         continue
310                     custom_context = dict(context, **eval_context)
311                     res['help'] = self.pool.get(model).get_empty_list_help(cr, uid, res.get('help', ""), context=custom_context)
312         if ids_int:
313             return results[0]
314         return results
315
316     def for_xml_id(self, cr, uid, module, xml_id, context=None):
317         """ Returns the act_window object created for the provided xml_id
318
319         :param module: the module the act_window originates in
320         :param xml_id: the namespace-less id of the action (the @id
321                        attribute from the XML file)
322         :return: A read() view of the ir.actions.act_window
323         """
324         dataobj = self.pool.get('ir.model.data')
325         data_id = dataobj._get_id (cr, SUPERUSER_ID, module, xml_id)
326         res_id = dataobj.browse(cr, uid, data_id, context).res_id
327         return self.read(cr, uid, res_id, [], context)
328
329 VIEW_TYPES = [
330     ('tree', 'Tree'),
331     ('form', 'Form'),
332     ('graph', 'Graph'),
333     ('calendar', 'Calendar'),
334     ('gantt', 'Gantt'),
335     ('kanban', 'Kanban')]
336 class ir_actions_act_window_view(osv.osv):
337     _name = 'ir.actions.act_window.view'
338     _table = 'ir_act_window_view'
339     _rec_name = 'view_id'
340     _order = 'sequence'
341     _columns = {
342         'sequence': fields.integer('Sequence'),
343         'view_id': fields.many2one('ir.ui.view', 'View'),
344         'view_mode': fields.selection(VIEW_TYPES, string='View Type', required=True),
345         'act_window_id': fields.many2one('ir.actions.act_window', 'Action', ondelete='cascade'),
346         'multi': fields.boolean('On Multiple Doc.',
347             help="If set to true, the action will not be displayed on the right toolbar of a form view."),
348     }
349     _defaults = {
350         'multi': False,
351     }
352     def _auto_init(self, cr, context=None):
353         super(ir_actions_act_window_view, self)._auto_init(cr, context)
354         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'act_window_view_unique_mode_per_action\'')
355         if not cr.fetchone():
356             cr.execute('CREATE UNIQUE INDEX act_window_view_unique_mode_per_action ON ir_act_window_view (act_window_id, view_mode)')
357
358
359 class ir_actions_act_window_close(osv.osv):
360     _name = 'ir.actions.act_window_close'
361     _inherit = 'ir.actions.actions'
362     _table = 'ir_actions'
363     _defaults = {
364         'type': 'ir.actions.act_window_close',
365     }
366
367
368 class ir_actions_act_url(osv.osv):
369     _name = 'ir.actions.act_url'
370     _table = 'ir_act_url'
371     _inherit = 'ir.actions.actions'
372     _sequence = 'ir_actions_id_seq'
373     _order = 'name'
374     _columns = {
375         'name': fields.char('Action Name', size=64, translate=True),
376         'type': fields.char('Action Type', size=32, required=True),
377         'url': fields.text('Action URL',required=True),
378         'target': fields.selection((
379             ('new', 'New Window'),
380             ('self', 'This Window')),
381             'Action Target', required=True
382         )
383     }
384     _defaults = {
385         'type': 'ir.actions.act_url',
386         'target': 'new'
387     }
388
389
390 class ir_actions_server(osv.osv):
391     """ Server actions model. Server action work on a base model and offer various
392     type of actions that can be executed automatically, for example using base
393     action rules, of manually, by adding the action in the 'More' contextual
394     menu.
395
396     Since OpenERP 8.0 a button 'Create Menu Action' button is available on the
397     action form view. It creates an entry in the More menu of the base model.
398     This allows to create server actions and run them in mass mode easily through
399     the interface.
400
401     The available actions are :
402
403     - 'Execute Python Code': a block of python code that will be executed
404     - 'Trigger a Workflow Signal': send a signal to a workflow
405     - 'Run a Client Action': choose a client action to launch
406     - 'Create or Copy a new Record': create a new record with new values, or
407       copy an existing record in your database
408     - 'Write on a Record': update the values of a record
409     - 'Execute several actions': define an action that triggers several other
410       server actions
411     """
412     _name = 'ir.actions.server'
413     _table = 'ir_act_server'
414     _inherit = 'ir.actions.actions'
415     _sequence = 'ir_actions_id_seq'
416     _order = 'sequence,name'
417
418     def _select_objects(self, cr, uid, context=None):
419         model_pool = self.pool.get('ir.model')
420         ids = model_pool.search(cr, uid, [('name', 'not ilike', '.')])
421         res = model_pool.read(cr, uid, ids, ['model', 'name'])
422         return [(r['model'], r['name']) for r in res] + [('', '')]
423
424     def _get_states(self, cr, uid, context=None):
425         """ Override me in order to add new states in the server action. Please
426         note that the added key length should not be higher than already-existing
427         ones. """
428         return [('code', 'Execute Python Code'),
429                 ('trigger', 'Trigger a Workflow Signal'),
430                 ('client_action', 'Run a Client Action'),
431                 ('object_create', 'Create or Copy a new Record'),
432                 ('object_write', 'Write on a Record'),
433                 ('multi', 'Execute several actions')]
434
435     def _get_states_wrapper(self, cr, uid, context=None):
436         return self._get_states(cr, uid, context)
437
438     _columns = {
439         'name': fields.char('Action Name', required=True, size=64, translate=True),
440         'condition': fields.char('Condition',
441                                  help="Condition verified before executing the server action. If it "
442                                  "is not verified, the action will not be executed. The condition is "
443                                  "a Python expression, like 'object.list_price > 5000'. A void "
444                                  "condition is considered as always True. Help about python expression "
445                                  "is given in the help tab."),
446         'state': fields.selection(_get_states_wrapper, 'Action To Do', required=True,
447                                   help="Type of server action. The following values are available:\n"
448                                   "- 'Execute Python Code': a block of python code that will be executed\n"
449                                   "- 'Trigger a Workflow Signal': send a signal to a workflow\n"
450                                   "- 'Run a Client Action': choose a client action to launch\n"
451                                   "- 'Create or Copy a new Record': create a new record with new values, or copy an existing record in your database\n"
452                                   "- 'Write on a Record': update the values of a record\n"
453                                   "- 'Execute several actions': define an action that triggers several other server actions\n"
454                                   "- 'Send Email': automatically send an email (available in email_template)"),
455         'usage': fields.char('Action Usage', size=32),
456         'type': fields.char('Action Type', size=32, required=True),
457         # Generic
458         'sequence': fields.integer('Sequence',
459                                    help="When dealing with multiple actions, the execution order is "
460                                    "based on the sequence. Low number means high priority."),
461         'model_id': fields.many2one('ir.model', 'Base Model', required=True, ondelete='cascade',
462                                     help="Base model on which the server action runs."),
463         'menu_ir_values_id': fields.many2one('ir.values', 'More Menu entry', readonly=True,
464                                              help='More menu entry.'),
465         # Client Action
466         'action_id': fields.many2one('ir.actions.actions', 'Client Action',
467                                      help="Select the client action that has to be executed."),
468         # Python code
469         'code': fields.text('Python Code',
470                             help="Write Python code that the action will execute. Some variables are "
471                             "available for use; help about pyhon expression is given in the help tab."),
472         # Workflow signal
473         'use_relational_model': fields.selection([('base', 'Use the base model of the action'),
474                                                   ('relational', 'Use a relation field on the base model')],
475                                                  string='Target Model', required=True),
476         'wkf_transition_id': fields.many2one('workflow.transition', string='Signal to Trigger',
477                                              help="Select the workflow signal to trigger."),
478         'wkf_model_id': fields.many2one('ir.model', 'Target Model',
479                                         help="The model that will receive the workflow signal. Note that it should have a workflow associated with it."),
480         'wkf_model_name': fields.related('wkf_model_id', 'model', type='char', string='Target Model Name', store=True, readonly=True),
481         'wkf_field_id': fields.many2one('ir.model.fields', string='Relation Field',
482                                         oldname='trigger_obj_id',
483                                         help="The field on the current object that links to the target object record (must be a many2one, or an integer field with the record ID)"),
484         # Multi
485         'child_ids': fields.many2many('ir.actions.server', 'rel_server_actions',
486                                       'server_id', 'action_id',
487                                       string='Child Actions',
488                                       help='Child server actions that will be executed. Note that the last return returned action value will be used as global return value.'),
489         # Create/Copy/Write
490         'use_create': fields.selection([('new', 'Create a new record in the Base Model'),
491                                         ('new_other', 'Create a new record in another model'),
492                                         ('copy_current', 'Copy the current record'),
493                                         ('copy_other', 'Choose and copy a record in the database')],
494                                        string="Creation Policy", required=True,
495                                        help=""),
496         'crud_model_id': fields.many2one('ir.model', 'Target Model',
497                                          oldname='srcmodel_id',
498                                          help="Model for record creation / update. Set this field only to specify a different model than the base model."),
499         'crud_model_name': fields.related('crud_model_id', 'model', type='char',
500                                           string='Create/Write Target Model Name',
501                                           store=True, readonly=True),
502         'ref_object': fields.reference('Reference record', selection=_select_objects, size=128,
503                                        oldname='copy_object'),
504         'link_new_record': fields.boolean('Attach the new record',
505                                           help="Check this if you want to link the newly-created record "
506                                           "to the current record on which the server action runs."),
507         'link_field_id': fields.many2one('ir.model.fields', 'Link using field',
508                                          oldname='record_id',
509                                          help="Provide the field where the record id is stored after the operations."),
510         'use_write': fields.selection([('current', 'Update the current record'),
511                                        ('expression', 'Update a record linked to the current record using python'),
512                                        ('other', 'Choose and Update a record in the database')],
513                                       string='Update Policy', required=True,
514                                       help=""),
515         'write_expression': fields.char('Expression',
516                                         oldname='write_id',
517                                         help="Provide an expression that, applied on the current record, gives the field to update."),
518         'fields_lines': fields.one2many('ir.server.object.lines', 'server_id',
519                                         string='Value Mapping',
520                                         help=""),
521
522         # Fake fields used to implement the placeholder assistant
523         'model_object_field': fields.many2one('ir.model.fields', string="Field",
524                                               help="Select target field from the related document model.\n"
525                                                    "If it is a relationship field you will be able to select "
526                                                    "a target field at the destination of the relationship."),
527         'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
528                                       help="When a relationship field is selected as first field, "
529                                            "this field shows the document model the relationship goes to."),
530         'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
531                                                   help="When a relationship field is selected as first field, "
532                                                        "this field lets you select the target field within the "
533                                                        "destination document model (sub-model)."),
534         'copyvalue': fields.char('Placeholder Expression', help="Final placeholder expression, to be copy-pasted in the desired template field."),
535         # Fake fields used to implement the ID finding assistant
536         'id_object': fields.reference('Record', selection=_select_objects, size=128),
537         'id_value': fields.char('Record ID'),
538     }
539
540     _defaults = {
541         'state': 'code',
542         'condition': 'True',
543         'type': 'ir.actions.server',
544         'sequence': 5,
545         'code': """# You can use the following variables:
546 #  - self: ORM model of the record on which the action is triggered
547 #  - object: browse_record of the record on which the action is triggered if there is one, otherwise None
548 #  - pool: ORM model pool (i.e. self.pool)
549 #  - cr: database cursor
550 #  - uid: current user id
551 #  - context: current context
552 #  - time: Python time module
553 # If you plan to return an action, assign: action = {...}""",
554         'use_relational_model': 'base',
555         'use_create': 'new',
556         'use_write': 'current',
557     }
558
559     def _check_expression(self, cr, uid, expression, model_id, context):
560         """ Check python expression (condition, write_expression). Each step of
561         the path must be a valid many2one field, or an integer field for the last
562         step.
563
564         :param str expression: a python expression, beginning by 'obj' or 'object'
565         :param int model_id: the base model of the server action
566         :returns tuple: (is_valid, target_model_name, error_msg)
567         """
568         if not model_id:
569             return (False, None, 'Your expression cannot be validated because the Base Model is not set.')
570         # fetch current model
571         current_model_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
572         # transform expression into a path that should look like 'object.many2onefield.many2onefield'
573         path = expression.split('.')
574         initial = path.pop(0)
575         if initial not in ['obj', 'object']:
576             return (False, None, 'Your expression should begin with obj or object.\nAn expression builder is available in the help tab.')
577         # analyze path
578         while path:
579             step = path.pop(0)
580             column_info = self.pool[current_model_name]._all_columns.get(step)
581             if not column_info:
582                 return (False, None, 'Part of the expression (%s) is not recognized as a column in the model %s.' % (step, current_model_name))
583             column_type = column_info.column._type
584             if column_type not in ['many2one', 'int']:
585                 return (False, None, 'Part of the expression (%s) is not a valid column type (is %s, should be a many2one or an int)' % (step, column_type))
586             if column_type == 'int' and path:
587                 return (False, None, 'Part of the expression (%s) is an integer field that is only allowed at the end of an expression' % (step))
588             if column_type == 'many2one':
589                 current_model_name = column_info.column._obj
590         return (True, current_model_name, None)
591
592     def _check_write_expression(self, cr, uid, ids, context=None):
593         for record in self.browse(cr, uid, ids, context=context):
594             if record.write_expression and record.model_id:
595                 correct, model_name, message = self._check_expression(cr, uid, record.write_expression, record.model_id.id, context=context)
596                 if not correct:
597                     _logger.warning('Invalid expression: %s' % message)
598                     return False
599         return True
600
601     _constraints = [
602         (_check_write_expression,
603             'Incorrect Write Record Expression',
604             ['write_expression']),
605         (partial(osv.Model._check_m2m_recursion, field_name='child_ids'),
606             'Recursion found in child server actions',
607             ['child_ids']),
608     ]
609
610     def on_change_model_id(self, cr, uid, ids, model_id, wkf_model_id, crud_model_id, context=None):
611         """ When changing the action base model, reset workflow and crud config
612         to ease value coherence. """
613         values = {
614             'use_create': 'new',
615             'use_write': 'current',
616             'use_relational_model': 'base',
617             'wkf_model_id': model_id,
618             'wkf_field_id': False,
619             'crud_model_id': model_id,
620         }
621         return {'value': values}
622
623     def on_change_wkf_wonfig(self, cr, uid, ids, use_relational_model, wkf_field_id, wkf_model_id, model_id, context=None):
624         """ Update workflow type configuration
625
626          - update the workflow model (for base (model_id) /relational (field.relation))
627          - update wkf_transition_id to False if workflow model changes, to force
628            the user to choose a new one
629         """
630         values = {}
631         if use_relational_model == 'relational' and wkf_field_id:
632             field = self.pool['ir.model.fields'].browse(cr, uid, wkf_field_id, context=context)
633             new_wkf_model_id = self.pool.get('ir.model').search(cr, uid, [('model', '=', field.relation)], context=context)[0]
634             values['wkf_model_id'] = new_wkf_model_id
635         else:
636             values['wkf_model_id'] = model_id
637         return {'value': values}
638
639     def on_change_wkf_model_id(self, cr, uid, ids, wkf_model_id, context=None):
640         """ When changing the workflow model, update its stored name also """
641         wkf_model_name = False
642         if wkf_model_id:
643             wkf_model_name = self.pool.get('ir.model').browse(cr, uid, wkf_model_id, context).model
644         values = {'wkf_transition_id': False, 'wkf_model_name': wkf_model_name}
645         return {'value': values}
646
647     def on_change_crud_config(self, cr, uid, ids, state, use_create, use_write, ref_object, crud_model_id, model_id, context=None):
648         """ Wrapper on CRUD-type (create or write) on_change """
649         if state == 'object_create':
650             return self.on_change_create_config(cr, uid, ids, use_create, ref_object, crud_model_id, model_id, context=context)
651         elif state == 'object_write':
652             return self.on_change_write_config(cr, uid, ids, use_write, ref_object, crud_model_id, model_id, context=context)
653         else:
654             return {}
655
656     def on_change_create_config(self, cr, uid, ids, use_create, ref_object, crud_model_id, model_id, context=None):
657         """ When changing the object_create type configuration:
658
659          - `new` and `copy_current`: crud_model_id is the same as base model
660          - `new_other`: user choose crud_model_id
661          - `copy_other`: disassemble the reference object to have its model
662          - if the target model has changed, then reset the link field that is
663            probably not correct anymore
664         """
665         values = {}
666         if use_create == 'new':
667             values['crud_model_id'] = model_id
668         elif use_create == 'new_other':
669             pass
670         elif use_create == 'copy_current':
671             values['crud_model_id'] = model_id
672         elif use_create == 'copy_other' and ref_object:
673             ref_model, ref_id = ref_object.split(',')
674             ref_model_id = self.pool['ir.model'].search(cr, uid, [('model', '=', ref_model)], context=context)[0]
675             values['crud_model_id'] = ref_model_id
676
677         if values.get('crud_model_id') != crud_model_id:
678             values['link_field_id'] = False
679         return {'value': values}
680
681     def on_change_write_config(self, cr, uid, ids, use_write, ref_object, crud_model_id, model_id, context=None):
682         """ When changing the object_write type configuration:
683
684          - `current`: crud_model_id is the same as base model
685          - `other`: disassemble the reference object to have its model
686          - `expression`: has its own on_change, nothing special here
687         """
688         values = {}
689         if use_write == 'current':
690             values['crud_model_id'] = model_id
691         elif use_write == 'other' and ref_object:
692             ref_model, ref_id = ref_object.split(',')
693             ref_model_id = self.pool['ir.model'].search(cr, uid, [('model', '=', ref_model)], context=context)[0]
694             values['crud_model_id'] = ref_model_id
695         elif use_write == 'expression':
696             pass
697
698         if values.get('crud_model_id') != crud_model_id:
699             values['link_field_id'] = False
700         return {'value': values}
701
702     def on_change_write_expression(self, cr, uid, ids, write_expression, model_id, context=None):
703         """ Check the write_expression and update crud_model_id accordingly """
704         values = {}
705         valid, model_name, message = self._check_expression(cr, uid, write_expression, model_id, context=context)
706         if valid:
707             ref_model_id = self.pool['ir.model'].search(cr, uid, [('model', '=', model_name)], context=context)[0]
708             values['crud_model_id'] = ref_model_id
709             return {'value': values}
710         if not message:
711             message = 'Invalid expression'
712         return {
713             'warning': {
714                 'title': 'Incorrect expression',
715                 'message': message,
716             }
717         }
718
719     def on_change_crud_model_id(self, cr, uid, ids, crud_model_id, context=None):
720         """ When changing the CRUD model, update its stored name also """
721         crud_model_name = False
722         if crud_model_id:
723             crud_model_name = self.pool.get('ir.model').browse(cr, uid, crud_model_id, context).model
724         values = {'link_field_id': False, 'crud_model_name': crud_model_name}
725         return {'value': values}
726
727     def _build_expression(self, field_name, sub_field_name):
728         """ Returns a placeholder expression for use in a template field,
729         based on the values provided in the placeholder assistant.
730
731         :param field_name: main field name
732         :param sub_field_name: sub field name (M2O)
733         :return: final placeholder expression
734         """
735         expression = ''
736         if field_name:
737             expression = "object." + field_name
738             if sub_field_name:
739                 expression += "." + sub_field_name
740         return expression
741
742     def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, context=None):
743         result = {
744             'sub_object': False,
745             'copyvalue': False,
746             'sub_model_object_field': False,
747         }
748         if model_object_field:
749             fields_obj = self.pool.get('ir.model.fields')
750             field_value = fields_obj.browse(cr, uid, model_object_field, context)
751             if field_value.ttype in ['many2one', 'one2many', 'many2many']:
752                 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
753                 sub_field_value = False
754                 if sub_model_object_field:
755                     sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
756                 if res_ids:
757                     result.update({
758                         'sub_object': res_ids[0],
759                         'copyvalue': self._build_expression(field_value.name, sub_field_value and sub_field_value.name or False),
760                         'sub_model_object_field': sub_model_object_field or False,
761                     })
762             else:
763                 result.update({
764                     'copyvalue': self._build_expression(field_value.name, False),
765                 })
766         return {'value': result}
767
768     def onchange_id_object(self, cr, uid, ids, id_object, context=None):
769         if id_object:
770             ref_model, ref_id = id_object.split(',')
771             return {'value': {'id_value': ref_id}}
772         return {'value': {'id_value': False}}
773
774     def create_action(self, cr, uid, ids, context=None):
775         """ Create a contextual action for each of the server actions. """
776         for action in self.browse(cr, uid, ids, context=context):
777             ir_values_id = self.pool.get('ir.values').create(cr, SUPERUSER_ID, {
778                 'name': _('Run %s') % action.name,
779                 'model': action.model_id.model,
780                 'key2': 'client_action_multi',
781                 'value': "ir.actions.server,%s" % action.id,
782             }, context)
783             action.write({
784                 'menu_ir_values_id': ir_values_id,
785             })
786
787         return True
788
789     def unlink_action(self, cr, uid, ids, context=None):
790         """ Remove the contextual actions created for the server actions. """
791         for action in self.browse(cr, uid, ids, context=context):
792             if action.menu_ir_values_id:
793                 try:
794                     self.pool.get('ir.values').unlink(cr, SUPERUSER_ID, action.menu_ir_values_id.id, context)
795                 except Exception:
796                     raise osv.except_osv(_('Warning'), _('Deletion of the action record failed.'))
797         return True
798
799     def run_action_client_action(self, cr, uid, action, eval_context=None, context=None):
800         if not action.action_id:
801             raise osv.except_osv(_('Error'), _("Please specify an action to launch!"))
802         return self.pool[action.action_id.type].read(cr, uid, action.action_id.id, context=context)
803
804     def run_action_code_multi(self, cr, uid, action, eval_context=None, context=None):
805         eval(action.code.strip(), eval_context, mode="exec", nocopy=True)  # nocopy allows to return 'action'
806         if 'action' in eval_context:
807             return eval_context['action']
808
809     def run_action_trigger(self, cr, uid, action, eval_context=None, context=None):
810         """ Trigger a workflow signal, depending on the use_relational_model:
811
812          - `base`: base_model_pool.signal_<TRIGGER_NAME>(cr, uid, context.get('active_id'))
813          - `relational`: find the related model and object, using the relational
814            field, then target_model_pool.signal_<TRIGGER_NAME>(cr, uid, target_id)
815         """
816         obj_pool = self.pool[action.model_id.model]
817         if action.use_relational_model == 'base':
818             target_id = context.get('active_id')
819             target_pool = obj_pool
820         else:
821             value = getattr(obj_pool.browse(cr, uid, context.get('active_id'), context=context), action.wkf_field_id.name)
822             if action.wkf_field_id.ttype == 'many2one':
823                 target_id = value.id
824             else:
825                 target_id = value
826             target_pool = self.pool[action.wkf_model_id.model]
827
828         trigger_name = action.wkf_transition_id.signal
829
830         workflow.trg_validate(uid, target_pool._name, target_id, trigger_name, cr)
831
832     def run_action_multi(self, cr, uid, action, eval_context=None, context=None):
833         res = []
834         for act in action.child_ids:
835             result = self.run(cr, uid, [act.id], context)
836             if result:
837                 res.append(result)
838         return res and res[0] or False
839
840     def run_action_object_write(self, cr, uid, action, eval_context=None, context=None):
841         """ Write server action.
842
843          - 1. evaluate the value mapping
844          - 2. depending on the write configuration:
845
846           - `current`: id = active_id
847           - `other`: id = from reference object
848           - `expression`: id = from expression evaluation
849         """
850         res = {}
851         for exp in action.fields_lines:
852             if exp.type == 'equation':
853                 expr = eval(exp.value, eval_context)
854             else:
855                 expr = exp.value
856             res[exp.col1.name] = expr
857
858         if action.use_write == 'current':
859             model = action.model_id.model
860             ref_id = context.get('active_id')
861         elif action.use_write == 'other':
862             model = action.crud_model_id.model
863             ref_id = action.ref_object.id
864         elif action.use_write == 'expression':
865             model = action.crud_model_id.model
866             ref = eval(action.write_expression, eval_context)
867             if isinstance(ref, browse_record):
868                 ref_id = getattr(ref, 'id')
869             else:
870                 ref_id = int(ref)
871
872         obj_pool = self.pool[model]
873         obj_pool.write(cr, uid, [ref_id], res, context=context)
874
875     def run_action_object_create(self, cr, uid, action, eval_context=None, context=None):
876         """ Create and Copy server action.
877
878          - 1. evaluate the value mapping
879          - 2. depending on the write configuration:
880
881           - `new`: new record in the base model
882           - `copy_current`: copy the current record (id = active_id) + gives custom values
883           - `new_other`: new record in target model
884           - `copy_other`: copy the current record (id from reference object)
885             + gives custom values
886         """
887         res = {}
888         for exp in action.fields_lines:
889             if exp.type == 'equation':
890                 expr = eval(exp.value, eval_context)
891             else:
892                 expr = exp.value
893             res[exp.col1.name] = expr
894
895         if action.use_create in ['new', 'copy_current']:
896             model = action.model_id.model
897         elif action.use_create in ['new_other', 'copy_other']:
898             model = action.crud_model_id.model
899
900         obj_pool = self.pool[model]
901         if action.use_create == 'copy_current':
902             ref_id = context.get('active_id')
903             res_id = obj_pool.copy(cr, uid, ref_id, res, context=context)
904         elif action.use_create == 'copy_other':
905             ref_id = action.ref_object.id
906             res_id = obj_pool.copy(cr, uid, ref_id, res, context=context)
907         else:
908             res_id = obj_pool.create(cr, uid, res, context=context)
909
910         if action.link_new_record and action.link_field_id:
911             self.pool[action.model_id.model].write(cr, uid, [context.get('active_id')], {action.link_field_id.name: res_id})
912
913     def run(self, cr, uid, ids, context=None):
914         """ Run the server action. For each server action, the condition is
915         checked. Note that A void (aka False) condition is considered as always
916         valid. If it is verified, the run_action_<STATE> method is called. This
917         allows easy inheritance of the server actions.
918
919         :param dict context: context should contain following keys
920
921                              - active_id: id of the current object (single mode)
922                              - active_model: current model that should equal the action's model
923
924                              The following keys are optional:
925
926                              - active_ids: ids of the current records (mass mode). If active_ids
927                                and active_id are present, active_ids is given precedence.
928
929         :return: an action_id to be executed, or False is finished correctly without
930                  return action
931         """
932         if context is None:
933             context = {}
934         res = False
935         user = self.pool.get('res.users').browse(cr, uid, uid)
936         active_ids = context.get('active_ids', [context.get('active_id')])
937         for action in self.browse(cr, uid, ids, context):
938             obj_pool = self.pool[action.model_id.model]
939             obj = None
940             if context.get('active_model') == action.model_id.model and context.get('active_id'):
941                 obj = obj_pool.browse(cr, uid, context['active_id'], context=context)
942
943             # evaluation context for python strings to evaluate
944             eval_context = {
945                 'self': obj_pool,
946                 'object': obj,
947                 'obj': obj,
948                 'pool': self.pool,
949                 'time': time,
950                 'cr': cr,
951                 'uid': uid,
952                 'user': user,
953             }
954             condition = action.condition
955             if condition is False:
956                 # Void (aka False) conditions are considered as True
957                 condition = True
958             if hasattr(self, 'run_action_%s_multi' % action.state):
959                 # set active_ids in context only needed if one active_id
960                 run_context = dict(context, active_ids=active_ids)
961                 eval_context["context"] = run_context
962                 expr = eval(str(condition), eval_context)
963                 if not expr:
964                     continue
965                 # call the multi method
966                 func = getattr(self, 'run_action_%s_multi' % action.state)
967                 res = func(cr, uid, action, eval_context=eval_context, context=run_context)
968
969             elif hasattr(self, 'run_action_%s' % action.state):
970                 func = getattr(self, 'run_action_%s' % action.state)
971                 for active_id in active_ids:
972                     # run context dedicated to a particular active_id
973                     run_context = dict(context, active_ids=[active_id], active_id=active_id)
974                     eval_context["context"] = run_context
975                     expr = eval(str(condition), eval_context)
976                     if not expr:
977                         continue
978                     # call the single method related to the action: run_action_<STATE>
979                     res = func(cr, uid, action, eval_context=eval_context, context=run_context)
980         return res
981
982
983 class ir_server_object_lines(osv.osv):
984     _name = 'ir.server.object.lines'
985     _sequence = 'ir_actions_id_seq'
986     _columns = {
987         'server_id': fields.many2one('ir.actions.server', 'Related Server Action'),
988         'col1': fields.many2one('ir.model.fields', 'Field', required=True),
989         'value': fields.text('Value', required=True, help="Expression containing a value specification. \n"
990                                                           "When Formula type is selected, this field may be a Python expression "
991                                                           " that can use the same values as for the condition field on the server action.\n"
992                                                           "If Value type is selected, the value will be used directly without evaluation."),
993         'type': fields.selection([
994             ('value', 'Value'),
995             ('equation', 'Python expression')
996         ], 'Evaluation Type', required=True, change_default=True),
997     }
998     _defaults = {
999         'type': 'value',
1000     }
1001
1002
1003 TODO_STATES = [('open', 'To Do'),
1004                ('done', 'Done')]
1005 TODO_TYPES = [('manual', 'Launch Manually'),('once', 'Launch Manually Once'),
1006               ('automatic', 'Launch Automatically')]
1007 class ir_actions_todo(osv.osv):
1008     """
1009     Configuration Wizards
1010     """
1011     _name = 'ir.actions.todo'
1012     _description = "Configuration Wizards"
1013     _columns={
1014         'action_id': fields.many2one(
1015             'ir.actions.actions', 'Action', select=True, required=True),
1016         'sequence': fields.integer('Sequence'),
1017         'state': fields.selection(TODO_STATES, string='Status', required=True),
1018         'name': fields.char('Name', size=64),
1019         'type': fields.selection(TODO_TYPES, 'Type', required=True,
1020             help="""Manual: Launched manually.
1021 Automatic: Runs whenever the system is reconfigured.
1022 Launch Manually Once: after having been launched manually, it sets automatically to Done."""),
1023         'groups_id': fields.many2many('res.groups', 'res_groups_action_rel', 'uid', 'gid', 'Groups'),
1024         'note': fields.text('Text', translate=True),
1025     }
1026     _defaults={
1027         'state': 'open',
1028         'sequence': 10,
1029         'type': 'manual',
1030     }
1031     _order="sequence,id"
1032
1033     def name_get(self, cr, uid, ids, context=None):
1034         return [(action["id"], "%s" % (action['action_id'][1])) for action in self.read(cr, uid, ids, ['action_id'], context=context)]
1035
1036     def action_launch(self, cr, uid, ids, context=None):
1037         """ Launch Action of Wizard"""
1038         wizard_id = ids and ids[0] or False
1039         wizard = self.browse(cr, uid, wizard_id, context=context)
1040         if wizard.type in ('automatic', 'once'):
1041             wizard.write({'state': 'done'})
1042
1043         # Load action
1044         act_type = self.pool.get('ir.actions.actions').read(cr, uid, wizard.action_id.id, ['type'], context=context)
1045
1046         res = self.pool[act_type['type']].read(cr, uid, wizard.action_id.id, [], context=context)
1047         if act_type['type'] != 'ir.actions.act_window':
1048             return res
1049         res.setdefault('context','{}')
1050         res['nodestroy'] = True
1051
1052         # Open a specific record when res_id is provided in the context
1053         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1054         ctx = eval(res['context'], {'user': user})
1055         if ctx.get('res_id'):
1056             res.update({'res_id': ctx.pop('res_id')})
1057
1058         # disable log for automatic wizards
1059         if wizard.type == 'automatic':
1060             ctx.update({'disable_log': True})
1061         res.update({'context': ctx})
1062
1063         return res
1064
1065     def action_open(self, cr, uid, ids, context=None):
1066         """ Sets configuration wizard in TODO state"""
1067         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
1068
1069     def progress(self, cr, uid, context=None):
1070         """ Returns a dict with 3 keys {todo, done, total}.
1071
1072         These keys all map to integers and provide the number of todos
1073         marked as open, the total number of todos and the number of
1074         todos not open (which is basically a shortcut to total-todo)
1075
1076         :rtype: dict
1077         """
1078         user_groups = set(map(
1079             lambda x: x.id,
1080             self.pool['res.users'].browse(cr, uid, [uid], context=context)[0].groups_id))
1081         def groups_match(todo):
1082             """ Checks if the todo's groups match those of the current user
1083             """
1084             return not todo.groups_id \
1085                    or bool(user_groups.intersection((
1086                         group.id for group in todo.groups_id)))
1087
1088         done = filter(
1089             groups_match,
1090             self.browse(cr, uid,
1091                 self.search(cr, uid, [('state', '!=', 'open')], context=context),
1092                         context=context))
1093
1094         total = filter(
1095             groups_match,
1096             self.browse(cr, uid,
1097                 self.search(cr, uid, [], context=context),
1098                         context=context))
1099
1100         return {
1101             'done': len(done),
1102             'total': len(total),
1103             'todo': len(total) - len(done)
1104         }
1105
1106
1107 class ir_actions_act_client(osv.osv):
1108     _name = 'ir.actions.client'
1109     _inherit = 'ir.actions.actions'
1110     _table = 'ir_act_client'
1111     _sequence = 'ir_actions_id_seq'
1112     _order = 'name'
1113
1114     def _get_params(self, cr, uid, ids, field_name, arg, context):
1115         result = {}
1116         for record in self.browse(cr, uid, ids, context=context):
1117             result[record.id] = record.params_store and eval(record.params_store, {'uid': uid}) or False
1118         return result
1119
1120     def _set_params(self, cr, uid, id, field_name, field_value, arg, context):
1121         if isinstance(field_value, dict):
1122             self.write(cr, uid, id, {'params_store': repr(field_value)}, context=context)
1123         else:
1124             self.write(cr, uid, id, {'params_store': field_value}, context=context)
1125
1126     _columns = {
1127         'name': fields.char('Action Name', required=True, size=64, translate=True),
1128         'tag': fields.char('Client action tag', size=64, required=True,
1129                            help="An arbitrary string, interpreted by the client"
1130                                 " according to its own needs and wishes. There "
1131                                 "is no central tag repository across clients."),
1132         'res_model': fields.char('Destination Model', size=64, 
1133             help="Optional model, mostly used for needactions."),
1134         'context': fields.char('Context Value', size=250, required=True,
1135             help="Context dictionary as Python expression, empty by default (Default: {})"),
1136         'params': fields.function(_get_params, fnct_inv=_set_params,
1137                                   type='binary', 
1138                                   string="Supplementary arguments",
1139                                   help="Arguments sent to the client along with"
1140                                        "the view tag"),
1141         'params_store': fields.binary("Params storage", readonly=True)
1142     }
1143     _defaults = {
1144         'type': 'ir.actions.client',
1145         'context': '{}',
1146
1147     }
1148
1149
1150
1151 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
1152