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