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