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