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