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