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