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