a5f4946b12986a21c3c404a7d01b80c790c5a40c
[odoo/odoo.git] / addons / process / process.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2005-TODAY TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # WARNING: This program as such is intended to be used by professional
7 # programmers who take the whole responsability of assessing all potential
8 # consequences resulting from its eventual inadequacies and bugs
9 # End users who are looking for a ready-to-use solution with commercial
10 # garantees and support are strongly adviced to contract a Free Software
11 # Service Company
12 #
13 # This program is Free Software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; either version 2
16 # of the License, or (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26 #
27 ##############################################################################
28
29 import netsvc
30 import pooler, tools
31
32 from osv import fields, osv
33
34 class Env(dict):
35     
36     def __init__(self, obj, user):
37         self.__obj = obj
38         self.__usr = user
39         
40     def __getitem__(self, name):
41         
42         if name in ('__obj', '__user'):
43             return super(ExprContext, self).__getitem__(name)
44         
45         if name == 'user':
46             return self.__user
47         
48         if name == 'object':
49             return self.__obj
50         
51         return self.__obj[name]
52
53 class process_process(osv.osv):
54     _name = "process.process"
55     _description = "Process"
56     _columns = {
57         'name': fields.char('Name', size=30,required=True, translate=True),
58         'active': fields.boolean('Active'),
59         'note': fields.text('Notes', translate=True),
60         'node_ids': fields.one2many('process.node', 'process_id', 'Nodes')
61     }
62     _defaults = {
63         'active' : lambda *a: True,
64     }
65
66     def search_by_model(self, cr, uid, res_model, context):
67         pool = pooler.get_pool(cr.dbname)
68
69         model_ids = pool.get('ir.model').search(cr, uid, [('model', '=', res_model)])
70         if not model_ids:
71             return []
72
73         nodes = pool.get('process.node').search(cr, uid, [('model_id', 'in', model_ids)])
74         if not nodes:
75             return []
76
77         nodes = pool.get('process.node').browse(cr, uid, nodes, context)
78
79         unique = []
80         result = []
81         
82         for node in nodes:
83             if node.process_id.id not in unique:
84                 result.append((node.process_id.id, node.process_id.name))
85                 unique.append(node.process_id.id)
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         current_object = pool.get(res_model).browse(cr, uid, [res_id], context)[0]
95         current_user = pool.get('res.users').browse(cr, uid, [uid], context)[0]
96         
97         expr_context = Env(current_object, current_user)
98         
99         notes = process.note
100         nodes = {}
101         start = []
102         transitions = {}
103
104         states = dict(pool.get(res_model).fields_get(cr, uid, context=context).get('state', {}).get('selection', {}))
105         title = "%s - Resource: %s, State: %s" % (process.name, current_object.name, states.get(getattr(current_object, 'state'), 'N/A'))
106
107         perm = pool.get(res_model).perm_read(cr, uid, [res_id], context)[0]
108
109         for node in process.node_ids:
110             data = {}
111             data['name'] = node.name
112             data['model'] = (node.model_id or None) and node.model_id.model
113             data['kind'] = node.kind
114             data['subflow'] = (node.subflow_id or False) and [node.subflow_id.id, node.subflow_id.name]
115             data['notes'] = node.note
116             data['active'] = False
117             data['gray'] = False
118             data['url'] = node.help_url
119
120             if node.menu_id:
121                 data['menu'] = {'name': node.menu_id.complete_name, 'id': node.menu_id.id}
122             
123             if node.model_id and node.model_id.model == res_model:
124                 try:
125                     data['active'] = eval(node.model_states, expr_context)
126                 except Exception, e:
127                     # waring: invalid state expression
128                     pass
129
130             if not data['active']:
131                 try:
132                     gray = True
133                     for cond in node.condition_ids:
134                         if cond.model_id and cond.model_id.model == res_model:
135                             gray = gray and eval(cond.model_states, expr_context)
136                     data['gray'] = not gray
137                 except:
138                     pass
139
140             nodes[node.id] = data
141             if node.flow_start:
142                 start.append(node.id)
143
144             for tr in node.transition_out:
145                 data = {}
146                 data['name'] = tr.name
147                 data['source'] = tr.source_node_id.id
148                 data['target'] = tr.target_node_id.id
149                 data['notes'] = tr.note
150                 data['buttons'] = buttons = []
151                 for b in tr.action_ids:
152                     button = {}
153                     button['name'] = b.name
154                     button['state'] = b.state
155                     button['action'] = b.action
156                     buttons.append(button)
157                 data['roles'] = roles = []
158                 for r in tr.transition_ids:
159                     if r.role_id:
160                         role = {}
161                         role['name'] = r.role_id.name
162                         roles.append(role)
163                 for r in tr.role_ids:
164                     role = {}
165                     role['name'] = r.name
166                     roles.append(role)
167                 transitions[tr.id] = data
168
169         # now populate resource information
170         def update_relatives(nid, ref_id, ref_model):
171             relatives = []
172
173             for tid, tr in transitions.items():
174                 if tr['source'] == nid:
175                     relatives.append(tr['target'])
176                 if tr['target'] == nid:
177                     relatives.append(tr['source'])
178
179             if not ref_id:
180                 nodes[nid]['res'] = False
181                 return
182
183             nodes[nid]['res'] = resource = {'id': ref_id, 'model': ref_model}
184
185             refobj = pool.get(ref_model).browse(cr, uid, [ref_id], context)[0]
186             fields = pool.get(ref_model).fields_get(cr, uid, context=context)
187
188             resource['name'] = refobj.name_get(context)[0][1]
189             resource['perm'] = pool.get(ref_model).perm_read(cr, uid, [ref_id], context)[0]
190
191             for r in relatives:
192                 node = nodes[r]
193                 if 'res' not in node:
194                     for n, f in fields.items():
195                         if node['model'] == ref_model:
196                             update_relatives(r, ref_id, ref_model)
197
198                         elif f.get('relation') == node['model']:
199                             rel = refobj[n]
200                             if rel and isinstance(rel, list) :
201                                 rel = rel[0]
202                             if isinstance(rel, basestring):
203                                 print "XXX: ", rel
204                             try: # XXXXXXXXXXXXXXXXXXX
205                                 _id = (rel or False) and rel.id
206                                 _model = node['model']
207                                 update_relatives(r, _id, _model)
208                             except:
209                                 pass
210
211         for nid, node in nodes.items():
212             if not node['gray'] and (node['active'] or node['model'] == res_model):
213                 update_relatives(nid, res_id, res_model)
214                 break
215
216         # calculate graph layout
217         g = tools.graph(nodes.keys(), map(lambda x: (x['source'], x['target']), transitions.values()))
218         g.process(start)        
219         g.scale(*scale) #g.scale(100, 100, 180, 120)
220         graph = g.result_get()
221
222         # fix the height problem
223         miny = -1
224         for k,v in nodes.items():
225             x = graph[k]['y']
226             y = graph[k]['x']
227             if miny == -1:
228                 miny = y
229             miny = min(y, miny)
230             v['x'] = x
231             v['y'] = y
232
233         for k, v in nodes.items():
234             y = v['y']
235             v['y'] = min(y - miny + 10, y)
236
237         return dict(title=title, perm=perm, notes=notes, nodes=nodes, transitions=transitions)
238
239     def copy(self, cr, uid, id, default=None, context={}):
240         """ Deep copy the entire process.
241         """
242
243         if not default:
244             default = {}
245
246         pool = pooler.get_pool(cr.dbname)
247         process = pool.get('process.process').browse(cr, uid, [id], context)[0]
248
249         nodes = {}
250         transitions = {}
251
252         # first copy all nodes and and map the new nodes with original for later use in transitions
253         for node in process.node_ids:
254             for t in node.transition_in:
255                 tr = transitions.setdefault(t.id, {})
256                 tr['target'] = node.id
257             for t in node.transition_out:
258                 tr = transitions.setdefault(t.id, {})
259                 tr['source'] = node.id
260             nodes[node.id] = pool.get('process.node').copy(cr, uid, node.id, context=context)
261
262         # then copy transitions with new nodes
263         for tid, tr in transitions.items():
264             vals = {
265                 'source_node_id': nodes[tr['source']],
266                 'target_node_id': nodes[tr['target']]
267             }
268             tr = pool.get('process.transition').copy(cr, uid, tid, default=vals, context=context)
269
270         # and finally copy the process itself with new nodes
271         default.update({
272             'active': True,
273             'node_ids': [(6, 0, nodes.values())]
274         })
275         return super(process_process, self).copy(cr, uid, id, default, context)
276
277 process_process()
278
279 class process_node(osv.osv):
280     _name = 'process.node'
281     _description ='Process Nodes'
282     _columns = {
283         'name': fields.char('Name', size=30,required=True, translate=True),
284         'process_id': fields.many2one('process.process', 'Process', required=True, ondelete='cascade'),
285         'kind': fields.selection([('state','State'), ('subflow','Subflow')], 'Kind of Node', required=True),
286         'menu_id': fields.many2one('ir.ui.menu', 'Related Menu'),
287         'note': fields.text('Notes', translate=True),
288         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
289         'model_states': fields.char('States Expression', size=128),
290         'subflow_id': fields.many2one('process.process', 'Subflow', ondelete='set null'),
291         'flow_start': fields.boolean('Starting Flow'),
292         'transition_in': fields.one2many('process.transition', 'target_node_id', 'Starting Transitions'),
293         'transition_out': fields.one2many('process.transition', 'source_node_id', 'Ending Transitions'),
294         'condition_ids': fields.one2many('process.condition', 'node_id', 'Conditions'),
295         'help_url': fields.char('Help URL', size=255)
296     }
297     _defaults = {
298         'kind': lambda *args: 'state',
299         'model_states': lambda *args: False,
300         'flow_start': lambda *args: False,
301     }
302
303     def copy(self, cr, uid, id, default=None, context={}):
304         if not default:
305             default = {}
306         default.update({
307             'transition_in': [],
308             'transition_out': []
309         })
310         return super(process_node, self).copy(cr, uid, id, default, context)
311
312 process_node()
313
314 class process_node_condition(osv.osv):
315     _name = 'process.condition'
316     _description = 'Condition'
317     _columns = {
318         'name': fields.char('Name', size=30, required=True),
319         'node_id': fields.many2one('process.node', 'Node', required=True, ondelete='cascade'),
320         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
321         'model_states': fields.char('Expression', required=True, size=128)
322     }
323 process_node_condition()
324
325 class process_transition(osv.osv):
326     _name = 'process.transition'
327     _description ='Process Transitions'
328     _columns = {
329         'name': fields.char('Name', size=32, required=True, translate=True),
330         'source_node_id': fields.many2one('process.node', 'Source Node', required=True, ondelete='cascade'),
331         'target_node_id': fields.many2one('process.node', 'Target Node', required=True, ondelete='cascade'),
332         'action_ids': fields.one2many('process.transition.action', 'transition_id', 'Buttons'),
333         'transition_ids': fields.many2many('workflow.transition', 'process_transition_ids', 'ptr_id', 'wtr_id', 'Workflow Transitions'),
334         'role_ids': fields.many2many('res.roles', 'process_transition_roles_rel', 'tid', 'rid', 'Roles'),
335         'note': fields.text('Description', translate=True),
336     }
337 process_transition()
338
339 class process_transition_action(osv.osv):
340     _name = 'process.transition.action'
341     _description ='Process Transitions Actions'
342     _columns = {
343         'name': fields.char('Name', size=32, required=True, translate=True),
344         'state': fields.selection([('dummy','Dummy'),
345                                    ('object','Object Method'),
346                                    ('workflow','Workflow Trigger'),
347                                    ('action','Action')], 'Type', required=True),
348         'action': fields.char('Action ID', size=64, states={
349             'dummy':[('readonly',1)],
350             'object':[('required',1)],
351             'workflow':[('required',1)],
352             'action':[('required',1)],
353         },),
354         'transition_id': fields.many2one('process.transition', 'Transition', required=True, ondelete='cascade')
355     }
356     _defaults = {
357         'state': lambda *args: 'dummy',
358     }
359
360     def copy(self, cr, uid, id, default=None, context={}):
361         if not default:
362             default = {}
363
364         state = self.pool.get('process.transition.action').browse(cr, uid, [id], context)[0].state
365         if state:
366             default['state'] = state
367
368         return super(process_transition_action, self).copy(cr, uid, id, default, context)
369
370 process_transition_action()
371