73af1beffecfd66f088b01ecf2c680a989df28d3
[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         def get_resource_info(node):
77             ret = False
78
79             src_model = res_model
80             src_id = res_id
81             
82             if node.transition_in:
83                 tr = node.transition_in[0]
84                 src = nodes.get(tr.source_node_id.id)
85                 if src['res']:
86                     src_model = src['res']['model']
87                     src_id = src['res']['id']
88                 else:
89                     return False
90
91             fields = pool.get(src_model).fields_get(cr, uid, context=context)
92
93             for name, field in fields.items():
94                 if node.model_id and field.get('relation', False) == node.model_id.model:
95                     src_obj = pool.get(src_model).browse(cr, uid, [src_id], context)[0]
96                     rel = src_obj[name]
97                     if rel:
98                         if isinstance(rel, (list, tuple)):
99                             rel = rel[0]
100                         ret = {}
101                         ret['name'] = rel.name_get(context)[0][1]
102                         ret['model'] = field['relation']
103                         ret['id'] = rel.id
104
105             return ret
106         
107         notes = process.note
108         nodes = {}
109         start = []
110         transitions = {}
111
112         for node in process.node_ids:
113             data = {}
114             data['name'] = node.name
115             data['model'] = (node.model_id or None) and node.model_id.model
116             data['kind'] = node.kind
117             data['subflow'] = (node.subflow_id or False) and [node.subflow_id.id, node.subflow_id.name]
118             data['notes'] = node.note
119             data['active'] = False
120             data['gray'] = False
121             data['res'] = get_resource_info(node)
122
123             if node.menu_id:
124                 data['menu'] = {'name': node.menu_id.complete_name, 'id': node.menu_id.id}
125             
126             if node.model_id and node.model_id.model == res_model:
127
128                 data['res'] = resource = {}
129                 resource['name'] = current_object.name_get(context)[0][1]
130                 resource['model'] = res_model
131                 resource['id'] = res_id
132
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         g = tools.graph(nodes.keys(), map(lambda x: (x['source'], x['target']), transitions.values()))
179         g.process(start)
180         #g.scale(100, 100, 180, 120)
181         g.scale(*scale)
182         graph = g.result_get()
183         miny = -1
184
185         for k,v in nodes.items():
186             x = graph[k]['y']
187             y = graph[k]['x']
188             if miny == -1:
189                 miny = y
190             miny = min(y, miny)
191             v['x'] = x
192             v['y'] = y
193
194         for k, v in nodes.items():
195             y = v['y']
196             v['y'] = min(y - miny + 10, y)
197         return dict(notes=notes, nodes=nodes, transitions=transitions)
198
199 process_process()
200
201 class process_node(osv.osv):
202     _name = 'process.node'
203     _description ='Process Nodes'
204     _columns = {
205         'name': fields.char('Name', size=30,required=True, translate=True),
206         'process_id': fields.many2one('process.process', 'Process', required=True, ondelete='cascade'),
207         'kind': fields.selection([('state','State'), ('subflow','Subflow')], 'Kind of Node', required=True),
208         'menu_id': fields.many2one('ir.ui.menu', 'Related Menu'),
209         'note': fields.text('Notes', translate=True),
210         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
211         'model_states': fields.char('States Expression', size=128),
212         'subflow_id': fields.many2one('process.process', 'Subflow', ondelete='set null'),
213         'flow_start': fields.boolean('Starting Flow'),
214         'transition_in': fields.one2many('process.transition', 'target_node_id', 'Starting Transitions'),
215         'transition_out': fields.one2many('process.transition', 'source_node_id', 'Ending Transitions'),
216         'condition_ids': fields.one2many('process.condition', 'node_id', 'Conditions')
217     }
218     _defaults = {
219         'kind': lambda *args: 'state',
220         'model_states': lambda *args: False,
221         'flow_start': lambda *args: False,
222     }
223 process_node()
224
225 class process_node_condition(osv.osv):
226     _name = 'process.condition'
227     _description = 'Condition'
228     _columns = {
229         'name': fields.char('Name', size=30, required=True),
230         'node_id': fields.many2one('process.node', 'Node', required=True, ondelete='cascade'),
231         'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
232         'model_states': fields.char('Expression', required=True, size=128)
233     }
234 process_node_condition()
235
236 class process_transition(osv.osv):
237     _name = 'process.transition'
238     _description ='Process Transitions'
239     _columns = {
240         'name': fields.char('Name', size=32, required=True, translate=True),
241         'source_node_id': fields.many2one('process.node', 'Source Node', required=True, ondelete='cascade'),
242         'target_node_id': fields.many2one('process.node', 'Target Node', required=True, ondelete='cascade'),
243         'action_ids': fields.one2many('process.transition.action', 'transition_id', 'Buttons'),
244         'transition_ids': fields.many2many('workflow.transition', 'process_transition_ids', 'ptr_id', 'wtr_id', 'Workflow Transitions'),
245         'role_ids': fields.many2many('res.roles', 'process_transition_roles_rel', 'tid', 'rid', 'Roles'),
246         'note': fields.text('Description', translate=True),
247     }
248 process_transition()
249
250 class process_transition_action(osv.osv):
251     _name = 'process.transition.action'
252     _description ='Process Transitions Actions'
253     _columns = {
254         'name': fields.char('Name', size=32, required=True, translate=True),
255         'state': fields.selection([('dummy','Dummy'),
256                                    ('object','Object Method'),
257                                    ('workflow','Workflow Trigger'),
258                                    ('action','Action')], 'Type', required=True),
259         'action': fields.char('Action ID', size=64, states={
260             'dummy':[('readonly',1)],
261             'object':[('required',1)],
262             'workflow':[('required',1)],
263             'action':[('required',1)],
264         },),
265         'transition_id': fields.many2one('process.transition', 'Transition', required=True, ondelete='cascade')
266     }
267     _defaults = {
268         'state': lambda *args: 'dummy',
269     }
270 process_transition_action()
271