Help URL
[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 graph_get(self, cr, uid, id, res_model, res_id, scale, context):
67         
68         pool = pooler.get_pool(cr.dbname)
69         
70         process = pool.get('process.process').browse(cr, uid, [id])[0]
71         current_object = pool.get(res_model).browse(cr, uid, [res_id], context)[0]
72         current_user = pool.get('res.users').browse(cr, uid, [uid], context)[0]
73         
74         expr_context = Env(current_object, current_user)
75         
76         notes = process.note
77         nodes = {}
78         start = []
79         transitions = {}
80
81         states = dict(pool.get(res_model).fields_get(cr, uid, context=context).get('state', {}).get('selection', {}))
82         title = "%s - Resource: %s, State: %s" % (process.name, current_object.name, states.get(getattr(current_object, 'state'), 'N/A'))
83
84         perm = pool.get(res_model).perm_read(cr, uid, [res_id], context)[0]
85
86         for node in process.node_ids:
87             data = {}
88             data['name'] = node.name
89             data['model'] = (node.model_id or None) and node.model_id.model
90             data['kind'] = node.kind
91             data['subflow'] = (node.subflow_id or False) and [node.subflow_id.id, node.subflow_id.name]
92             data['notes'] = node.note
93             data['active'] = False
94             data['gray'] = False
95             data['url'] = node.help_url
96
97             if node.menu_id:
98                 data['menu'] = {'name': node.menu_id.complete_name, 'id': node.menu_id.id}
99             
100             if node.model_id and node.model_id.model == res_model:
101                 try:
102                     data['active'] = eval(node.model_states, expr_context)
103                 except Exception, e:
104                     # waring: invalid state expression
105                     pass
106
107             if not data['active']:
108                 try:
109                     gray = True
110                     for cond in node.condition_ids:
111                         if cond.model_id and cond.model_id.model == res_model:
112                             gray = gray and eval(cond.model_states, expr_context)
113                     data['gray'] = not gray
114                 except:
115                     pass
116
117             nodes[node.id] = data
118             if node.flow_start:
119                 start.append(node.id)
120
121             for tr in node.transition_out:
122                 data = {}
123                 data['name'] = tr.name
124                 data['source'] = tr.source_node_id.id
125                 data['target'] = tr.target_node_id.id
126                 data['notes'] = tr.note
127                 data['buttons'] = buttons = []
128                 for b in tr.action_ids:
129                     button = {}
130                     button['name'] = b.name
131                     button['state'] = b.state
132                     button['action'] = b.action
133                     buttons.append(button)
134                 data['roles'] = roles = []
135                 for r in tr.transition_ids:
136                     if r.role_id:
137                         role = {}
138                         role['name'] = r.role_id.name
139                         roles.append(role)
140                 for r in tr.role_ids:
141                     role = {}
142                     role['name'] = r.name
143                     roles.append(role)
144                 transitions[tr.id] = data
145
146         # now populate resource information
147         def update_relatives(nid, ref_id, ref_model):
148             relatives = []
149
150             for tid, tr in transitions.items():
151                 if tr['source'] == nid:
152                     relatives.append(tr['target'])
153                 if tr['target'] == nid:
154                     relatives.append(tr['source'])
155
156             if not ref_id:
157                 nodes[nid]['res'] = False
158                 return
159
160             nodes[nid]['res'] = resource = {'id': ref_id, 'model': ref_model}
161
162             refobj = pool.get(ref_model).browse(cr, uid, [ref_id], context)[0]
163             fields = pool.get(ref_model).fields_get(cr, uid, context=context)
164
165             resource['name'] = refobj.name_get(context)[0][1]
166             resource['perm'] = pool.get(ref_model).perm_read(cr, uid, [ref_id], context)[0]
167
168             for r in relatives:
169                 node = nodes[r]
170                 if 'res' not in node:
171                     for n, f in fields.items():
172                         if node['model'] == ref_model:
173                             update_relatives(r, ref_id, ref_model)
174
175                         elif f.get('relation') == node['model']:
176                             rel = refobj[n]
177                             if rel and isinstance(rel, list) :
178                                 rel = rel[0]
179                             _id = (rel or False) and rel.id
180                             _model = node['model']
181                             update_relatives(r, _id, _model)
182
183         for nid, node in nodes.items():
184             if node['active'] or node['model'] == res_model:
185                 update_relatives(nid, res_id, res_model)
186                 break
187
188         # calculate graph layout
189         g = tools.graph(nodes.keys(), map(lambda x: (x['source'], x['target']), transitions.values()))
190         g.process(start)        
191         g.scale(*scale) #g.scale(100, 100, 180, 120)
192         graph = g.result_get()
193
194         # fix the height problem
195         miny = -1
196         for k,v in nodes.items():
197             x = graph[k]['y']
198             y = graph[k]['x']
199             if miny == -1:
200                 miny = y
201             miny = min(y, miny)
202             v['x'] = x
203             v['y'] = y
204
205         for k, v in nodes.items():
206             y = v['y']
207             v['y'] = min(y - miny + 10, y)
208
209         return dict(title=title, perm=perm, notes=notes, nodes=nodes, transitions=transitions)
210
211 process_process()
212
213 class process_node(osv.osv):
214     _name = 'process.node'
215     _description ='Process Nodes'
216     _columns = {
217         'name': fields.char('Name', size=30,required=True, translate=True),
218         'process_id': fields.many2one('process.process', 'Process', required=True, ondelete='cascade'),
219         'kind': fields.selection([('state','State'), ('subflow','Subflow')], 'Kind of Node', required=True),
220         'menu_id': fields.many2one('ir.ui.menu', 'Related Menu'),
221         'note': fields.text('Notes', translate=True),
222         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
223         'model_states': fields.char('States Expression', size=128),
224         'subflow_id': fields.many2one('process.process', 'Subflow', ondelete='set null'),
225         'flow_start': fields.boolean('Starting Flow'),
226         'transition_in': fields.one2many('process.transition', 'target_node_id', 'Starting Transitions'),
227         'transition_out': fields.one2many('process.transition', 'source_node_id', 'Ending Transitions'),
228         'condition_ids': fields.one2many('process.condition', 'node_id', 'Conditions'),
229         'help_url': fields.char('Help URL', size=255)
230     }
231     _defaults = {
232         'kind': lambda *args: 'state',
233         'model_states': lambda *args: False,
234         'flow_start': lambda *args: False,
235     }
236 process_node()
237
238 class process_node_condition(osv.osv):
239     _name = 'process.condition'
240     _description = 'Condition'
241     _columns = {
242         'name': fields.char('Name', size=30, required=True),
243         'node_id': fields.many2one('process.node', 'Node', required=True, ondelete='cascade'),
244         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
245         'model_states': fields.char('Expression', required=True, size=128)
246     }
247 process_node_condition()
248
249 class process_transition(osv.osv):
250     _name = 'process.transition'
251     _description ='Process Transitions'
252     _columns = {
253         'name': fields.char('Name', size=32, required=True, translate=True),
254         'source_node_id': fields.many2one('process.node', 'Source Node', required=True, ondelete='cascade'),
255         'target_node_id': fields.many2one('process.node', 'Target Node', required=True, ondelete='cascade'),
256         'action_ids': fields.one2many('process.transition.action', 'transition_id', 'Buttons'),
257         'transition_ids': fields.many2many('workflow.transition', 'process_transition_ids', 'ptr_id', 'wtr_id', 'Workflow Transitions'),
258         'role_ids': fields.many2many('res.roles', 'process_transition_roles_rel', 'tid', 'rid', 'Roles'),
259         'note': fields.text('Description', translate=True),
260     }
261 process_transition()
262
263 class process_transition_action(osv.osv):
264     _name = 'process.transition.action'
265     _description ='Process Transitions Actions'
266     _columns = {
267         'name': fields.char('Name', size=32, required=True, translate=True),
268         'state': fields.selection([('dummy','Dummy'),
269                                    ('object','Object Method'),
270                                    ('workflow','Workflow Trigger'),
271                                    ('action','Action')], 'Type', required=True),
272         'action': fields.char('Action ID', size=64, states={
273             'dummy':[('readonly',1)],
274             'object':[('required',1)],
275             'workflow':[('required',1)],
276             'action':[('required',1)],
277         },),
278         'transition_id': fields.many2one('process.transition', 'Transition', required=True, ondelete='cascade')
279     }
280     _defaults = {
281         'state': lambda *args: 'dummy',
282     }
283 process_transition_action()
284