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