[MERGE] OPW 574806: process: process node active state should be evaluated on related...
[odoo/odoo.git] / addons / process / process.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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 import pooler
23 import tools
24 from osv import fields, osv
25
26 class Env(dict):
27
28     def __init__(self, obj, user):
29         self.__obj = obj
30         self.__usr = user
31
32     def __getitem__(self, name):
33         if name in ('__obj', '__user'):
34             return super(Env, self).__getitem__(name)
35         if name == 'user':
36             return self.__user
37         if name == 'object':
38             return self.__obj
39         return self.__obj[name]
40
41 class process_process(osv.osv):
42     _name = "process.process"
43     _description = "Process"
44     _columns = {
45         'name': fields.char('Name', size=30,required=True, translate=True),
46         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the process without removing it."),
47         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
48         'note': fields.text('Notes', translate=True),
49         'node_ids': fields.one2many('process.node', 'process_id', 'Nodes')
50     }
51     _defaults = {
52         'active' : lambda *a: True,
53     }
54
55     def search_by_model(self, cr, uid, res_model, context=None):
56         pool = pooler.get_pool(cr.dbname)
57         model_ids = (res_model or None) and pool.get('ir.model').search(cr, uid, [('model', '=', res_model)])
58
59         domain = (model_ids or []) and [('model_id', 'in', model_ids)]
60         result = []
61
62         # search all processes
63         res = pool.get('process.process').search(cr, uid, domain)
64         if res:
65             res = pool.get('process.process').browse(cr, uid, res, context=context)
66             for process in res:
67                 result.append((process.id, process.name))
68             return result
69
70         # else search process nodes
71         res = pool.get('process.node').search(cr, uid, domain)
72         if res:
73             res = pool.get('process.node').browse(cr, uid, res, context=context)
74             for node in res:
75                 if (node.process_id.id, node.process_id.name) not in result:
76                     result.append((node.process_id.id, node.process_id.name))
77
78         return result
79
80     def graph_get(self, cr, uid, id, res_model, res_id, scale, context=None):
81
82         pool = pooler.get_pool(cr.dbname)
83
84         process = pool.get('process.process').browse(cr, uid, id, context=context)
85
86         name = process.name
87         resource = None
88         state = 'N/A'
89
90         expr_context = {}
91         states = {}
92         perm = None
93
94         if res_model:
95             states = dict(pool.get(res_model).fields_get(cr, uid, context=context).get('state', {}).get('selection', {}))
96
97         if res_id:
98             current_object = pool.get(res_model).browse(cr, uid, res_id, context=context)
99             current_user = pool.get('res.users').browse(cr, uid, uid, context=context)
100             expr_context = Env(current_object, current_user)
101             resource = current_object.name
102             if 'state' in current_object:
103                 state = states.get(current_object.state, 'N/A')
104             perm = pool.get(res_model).perm_read(cr, uid, [res_id], context=context)[0]
105
106         notes = process.note or "N/A"
107         nodes = {}
108         start = []
109         transitions = {}
110
111         for node in process.node_ids:
112             data = {}
113             data['name'] = node.name
114             data['model'] = (node.model_id or None) and node.model_id.model
115             data['kind'] = node.kind
116             data['subflow'] = (node.subflow_id or False) and [node.subflow_id.id, node.subflow_id.name]
117             data['notes'] = node.note
118             data['active'] = False
119             data['gray'] = False
120             data['url'] = node.help_url
121             data['model_states'] = node.model_states
122
123             # get assosiated workflow
124             if data['model']:
125                 wkf_ids = self.pool.get('workflow').search(cr, uid, [('osv', '=', data['model'])])
126                 data['workflow'] = (wkf_ids or False) and wkf_ids[0]
127
128             if 'directory_id' in node and node.directory_id:
129                 data['directory_id'] = node.directory_id.id
130                 data['directory'] = self.pool.get('document.directory').get_resource_path(cr, uid, data['directory_id'], data['model'], False)
131
132             if node.menu_id:
133                 data['menu'] = {'name': node.menu_id.complete_name, 'id': node.menu_id.id}
134
135             try:
136                 gray = True
137                 for cond in node.condition_ids:
138                     if cond.model_id and cond.model_id.model == res_model:
139                         gray = gray and eval(cond.model_states, expr_context)
140                 data['gray'] = not gray
141             except:
142                 pass
143
144             if not data['gray']:
145                 if node.model_id and node.model_id.model == res_model:
146                     try:
147                         data['active'] = eval(node.model_states, expr_context)
148                     except Exception:
149                         pass
150
151             nodes[node.id] = data
152             if node.flow_start:
153                 start.append(node.id)
154
155             for tr in node.transition_out:
156                 data = {}
157                 data['name'] = tr.name
158                 data['source'] = tr.source_node_id.id
159                 data['target'] = tr.target_node_id.id
160                 data['notes'] = tr.note
161                 data['buttons'] = buttons = []
162                 for b in tr.action_ids:
163                     button = {}
164                     button['name'] = b.name
165                     button['state'] = b.state
166                     button['action'] = b.action
167                     buttons.append(button)
168                 data['groups'] = groups = []
169                 for r in tr.transition_ids:
170                     if r.group_id:
171                         groups.append({'name': r.group_id.name})
172                 for r in tr.group_ids:
173                     groups.append({'name': r.name})
174                 transitions[tr.id] = data
175
176         # now populate resource information
177         def update_relatives(nid, ref_id, ref_model):
178             relatives = []
179
180             for dummy, tr in transitions.items():
181                 if tr['source'] == nid:
182                     relatives.append(tr['target'])
183                 if tr['target'] == nid:
184                     relatives.append(tr['source'])
185
186             if not ref_id:
187                 nodes[nid]['res'] = False
188                 return
189
190             nodes[nid]['res'] = resource = {'id': ref_id, 'model': ref_model}
191
192             refobj = pool.get(ref_model).browse(cr, uid, ref_id, context=context)
193             fields = pool.get(ref_model).fields_get(cr, uid, context=context)
194
195             # check for directory_id from inherited from document module
196             if nodes[nid].get('directory_id', False):
197                 resource['directory'] = self.pool.get('document.directory').get_resource_path(cr, uid, nodes[nid]['directory_id'], ref_model, ref_id)
198
199             resource['name'] = refobj.name_get(context)[0][1]
200             resource['perm'] = pool.get(ref_model).perm_read(cr, uid, [ref_id], context)[0]
201
202             ref_expr_context = Env(refobj, current_user)
203             try:
204                 if not nodes[nid]['gray']:
205                     nodes[nid]['active'] = eval(nodes[nid]['model_states'], ref_expr_context)
206             except:
207                 pass
208             for r in relatives:
209                 node = nodes[r]
210                 if 'res' not in node:
211                     for n, f in fields.items():
212                         if node['model'] == ref_model:
213                             update_relatives(r, ref_id, ref_model)
214
215                         elif f.get('relation') == node['model']:
216                             rel = refobj[n]
217                             if rel and isinstance(rel, list) :
218                                 rel = rel[0]
219                             try: # XXX: rel has been reported as string (check it)
220                                 _id = (rel or False) and rel.id
221                                 _model = node['model']
222                                 update_relatives(r, _id, _model)
223                             except:
224                                 pass
225
226         if res_id:
227             for nid, node in nodes.items():
228                 if not node['gray'] and (node['active'] or node['model'] == res_model):
229                     update_relatives(nid, res_id, res_model)
230                     break
231
232         # calculate graph layout
233         g = tools.graph(nodes.keys(), map(lambda x: (x['source'], x['target']), transitions.values()))
234         g.process(start)
235         g.scale(*scale) #g.scale(100, 100, 180, 120)
236         graph = g.result_get()
237
238         # fix the height problem
239         miny = -1
240         for k,v in nodes.items():
241             x = graph[k]['x']
242             y = graph[k]['y']
243             if miny == -1:
244                 miny = y
245             miny = min(y, miny)
246             v['x'] = x
247             v['y'] = y
248
249         for k, v in nodes.items():
250             y = v['y']
251             v['y'] = min(y - miny + 10, y)
252
253         return dict(name=name, resource=resource, state=state, perm=perm, notes=notes, nodes=nodes, transitions=transitions)
254
255     def copy(self, cr, uid, id, default=None, context=None):
256         """ Deep copy the entire process.
257         """
258
259         if not default:
260             default = {}
261         
262         pool = pooler.get_pool(cr.dbname)
263         process = pool.get('process.process').browse(cr, uid, id, context=context)
264
265         nodes = {}
266         transitions = {}
267
268         # first copy all nodes and and map the new nodes with original for later use in transitions
269         for node in process.node_ids:
270             for t in node.transition_in:
271                 tr = transitions.setdefault(t.id, {})
272                 tr['target'] = node.id
273             for t in node.transition_out:
274                 tr = transitions.setdefault(t.id, {})
275                 tr['source'] = node.id
276             nodes[node.id] = pool.get('process.node').copy(cr, uid, node.id, context=context)
277
278         # then copy transitions with new nodes
279         for tid, tr in transitions.items():
280             vals = {
281                 'source_node_id': nodes[tr['source']],
282                 'target_node_id': nodes[tr['target']]
283             }
284             tr = pool.get('process.transition').copy(cr, uid, tid, default=vals, context=context)
285
286         # and finally copy the process itself with new nodes
287         default.update({
288             'active': True,
289             'node_ids': [(6, 0, nodes.values())]
290         })
291         return super(process_process, self).copy(cr, uid, id, default, context)
292
293 process_process()
294
295 class process_node(osv.osv):
296     _name = 'process.node'
297     _description ='Process Node'
298     _columns = {
299         'name': fields.char('Name', size=30,required=True, translate=True),
300         'process_id': fields.many2one('process.process', 'Process', required=True, ondelete='cascade'),
301         'kind': fields.selection([('state','State'), ('subflow','Subflow')], 'Kind of Node', required=True),
302         'menu_id': fields.many2one('ir.ui.menu', 'Related Menu'),
303         'note': fields.text('Notes', translate=True),
304         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
305         'model_states': fields.char('States Expression', size=128),
306         'subflow_id': fields.many2one('process.process', 'Subflow', ondelete='set null'),
307         'flow_start': fields.boolean('Starting Flow'),
308         'transition_in': fields.one2many('process.transition', 'target_node_id', 'Starting Transitions'),
309         'transition_out': fields.one2many('process.transition', 'source_node_id', 'Ending Transitions'),
310         'condition_ids': fields.one2many('process.condition', 'node_id', 'Conditions'),
311         'help_url': fields.char('Help URL', size=255)
312     }
313     _defaults = {
314         'kind': lambda *args: 'state',
315         'model_states': lambda *args: False,
316         'flow_start': lambda *args: False,
317     }
318
319     def copy_data(self, cr, uid, id, default=None, context=None):
320         if not default:
321             default = {}
322         default.update({
323             'transition_in': [],
324             'transition_out': []
325         })
326         return super(process_node, self).copy_data(cr, uid, id, default, context=context)
327
328 process_node()
329
330 class process_node_condition(osv.osv):
331     _name = 'process.condition'
332     _description = 'Condition'
333     _columns = {
334         'name': fields.char('Name', size=30, required=True),
335         'node_id': fields.many2one('process.node', 'Node', required=True, ondelete='cascade'),
336         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
337         'model_states': fields.char('Expression', required=True, size=128)
338     }
339 process_node_condition()
340
341 class process_transition(osv.osv):
342     _name = 'process.transition'
343     _description ='Process Transition'
344     _columns = {
345         'name': fields.char('Name', size=32, required=True, translate=True),
346         'source_node_id': fields.many2one('process.node', 'Source Node', required=True, ondelete='cascade'),
347         'target_node_id': fields.many2one('process.node', 'Target Node', required=True, ondelete='cascade'),
348         'action_ids': fields.one2many('process.transition.action', 'transition_id', 'Buttons'),
349         'transition_ids': fields.many2many('workflow.transition', 'process_transition_ids', 'ptr_id', 'wtr_id', 'Workflow Transitions'),
350         'group_ids': fields.many2many('res.groups', 'process_transition_group_rel', 'tid', 'rid', string='Required Groups'),
351         'note': fields.text('Description', translate=True),
352     }
353 process_transition()
354
355 class process_transition_action(osv.osv):
356     _name = 'process.transition.action'
357     _description ='Process Transitions Actions'
358     _columns = {
359         'name': fields.char('Name', size=32, required=True, translate=True),
360         'state': fields.selection([('dummy','Dummy'),
361                                    ('object','Object Method'),
362                                    ('workflow','Workflow Trigger'),
363                                    ('action','Action')], 'Type', required=True),
364         'action': fields.char('Action ID', size=64, states={
365             'dummy':[('readonly',1)],
366             'object':[('required',1)],
367             'workflow':[('required',1)],
368             'action':[('required',1)],
369         },),
370         'transition_id': fields.many2one('process.transition', 'Transition', required=True, ondelete='cascade')
371     }
372     _defaults = {
373         'state': lambda *args: 'dummy',
374     }
375
376     def copy_data(self, cr, uid, id, default=None, context=None):
377         if not default:
378             default = {}
379             
380         state = self.pool.get('process.transition.action').browse(cr, uid, id, context=context).state
381         if state:
382             default['state'] = state
383
384         return super(process_transition_action, self).copy_data(cr, uid, id, default, context)
385
386 process_transition_action()
387
388 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: