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