[ADD]: Added tooltips for all state fields.
[odoo/odoo.git] / addons / mrp_operations / mrp_operations.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 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 from osv import fields
23 from osv import osv
24 import ir
25 import datetime
26 import netsvc
27 import time
28 from mx import DateTime
29 from tools.translate import _
30
31 #----------------------------------------------------------
32 # Workcenters
33 #----------------------------------------------------------
34 # capacity_hour : capacity per hour. default: 1.0.
35 #          Eg: If 5 concurrent operations at one time: capacity = 5 (because 5 employees)
36 # unit_per_cycle : how many units are produced for one cycle
37 #
38 # TODO: Work Center may be recursive ?
39 #
40
41 class stock_move(osv.osv):
42     _inherit = 'stock.move'
43     _columns = {
44         'move_dest_id_lines': fields.one2many('stock.move','move_dest_id', 'Children Moves')
45     }
46 stock_move()
47
48 class mrp_production_workcenter_line(osv.osv):
49     def _get_date_date(self, cr, uid, ids, field_name, arg, context):
50         res={}
51         for op in self.browse(cr, uid, ids, context=context):
52             if op.date_start:
53                 res[op.id] = op.date_start[:10]
54             else:
55                 res[op.id]=False
56         return res
57     def _get_date_end(self, cr, uid, ids, field_name, arg, context):
58         res = {}
59         for op in self.browse(cr, uid, ids, context=context):
60             res[op.id]= False
61             if op.date_planned:
62                 d = DateTime.strptime(op.date_planned,'%Y-%m-%d %H:%M:%S')
63                 i = self.pool.get('hr.timesheet.group').interval_get(cr, uid, op.workcenter_id.timesheet_id.id or False, d, op.hour or 0.0)
64                 if i:
65                     res[op.id] = i[-1][1].strftime('%Y-%m-%d %H:%M:%S')
66                 else:
67                     res[op.id] = op.date_planned
68         return res
69     _inherit = 'mrp.production.workcenter.line'
70     _columns = {
71        'state': fields.selection([('draft','Draft'),('startworking', 'In Progress'),('pause','Pause'),('cancel','Canceled'),('done','Finished')],'State', readonly=True),
72        'date_start_date': fields.function(_get_date_date, method=True, string='Start Date', type='date'),
73        'date_planned': fields.related('production_id', 'date_planned', type='datetime', string='Date Planned'),
74        'date_planned_end': fields.function(_get_date_end, method=True, string='End Date', type='datetime'),
75        'date_start': fields.datetime('Start Date'),
76        'date_finnished': fields.datetime('End Date'),
77        'delay': fields.float('Working Hours',help="This is delay between operation start and stop in this workcenter",readonly=True),
78        'production_state':fields.related('production_id','state',
79             type='selection',
80             selection=[('draft','Draft'),('picking_except', 'Packing Exception'),('confirmed','Waiting Goods'),('ready','Ready to Produce'),('in_production','In Production'),('cancel','Canceled'),('done','Done')],
81             string='Prod.State', readonly=True),
82        'product':fields.related('production_id','product_id',type='many2one',relation='product.product',string='Product',
83             readonly=True),
84        'qty':fields.related('production_id','product_qty',type='float',string='Qty',readonly=True),
85        'uom':fields.related('production_id','product_uom',type='many2one',relation='product.uom',string='UOM',readonly=True),
86     }
87     _defaults = {
88         'state': lambda *a: 'draft',
89         'delay': lambda *a: 0.0
90     }
91
92     def modify_production_order_state(self,cr,uid,ids,action):
93         wf_service = netsvc.LocalService("workflow")
94         oper_obj=self.browse(cr,uid,ids)[0]
95         prod_obj=oper_obj.production_id
96         if action=='start':
97                if prod_obj.state =='confirmed':
98                    self.pool.get('mrp.production').force_production(cr, uid, [prod_obj.id])
99                    wf_service.trg_validate(uid, 'mrp.production', prod_obj.id, 'button_produce', cr)
100                elif prod_obj.state =='ready':
101                    wf_service.trg_validate(uid, 'mrp.production', prod_obj.id, 'button_produce', cr)
102                elif prod_obj.state =='in_production':
103                    return
104                else:
105                    raise osv.except_osv(_('Error!'),_('Production Order Cannot start in [%s] state') % (prod_obj.state,))
106         else:
107             oper_ids=self.search(cr,uid,[('production_id','=',prod_obj.id)])
108             obj=self.browse(cr,uid,oper_ids)
109             flag=True
110             for line in obj:
111                 if line.state!='done':
112                      flag=False
113             if flag:
114                 wf_service.trg_validate(uid, 'mrp.production', oper_obj.production_id.id, 'button_produce_done', cr)
115         return
116
117     def write(self, cr, uid, ids, vals, context={}, update=True):
118         result = super(mrp_production_workcenter_line, self).write(cr, uid, ids, vals, context=context)
119         if vals.get('date_planned', False) and update:
120             pids = {}
121             pids2 = {}
122             for prod in self.browse(cr, uid, ids, context=context):
123                 if prod.production_id.workcenter_lines:
124                     dstart = min(vals['date_planned'], prod.production_id.workcenter_lines[0]['date_planned'])
125                     self.pool.get('mrp.production').write(cr, uid, [prod.production_id.id], {'date_start':dstart}, context=context, mini=False)
126         return result
127
128     def action_draft(self, cr, uid, ids):
129         self.write(cr, uid, ids, {'state':'draft'})
130         return True
131
132     def action_start_working(self, cr, uid, ids):
133         self.modify_production_order_state(cr,uid,ids,'start')
134         self.write(cr, uid, ids, {'state':'startworking', 'date_start': time.strftime('%Y-%m-%d %H:%M:%S')})
135         return True
136
137     def action_done(self, cr, uid, ids):
138         self.write(cr, uid, ids, {'state':'done', 'date_finnished': time.strftime('%Y-%m-%d %H:%M:%S')})
139         self.modify_production_order_state(cr,uid,ids,'done')
140         return True
141
142     def action_cancel(self, cr, uid, ids):
143         self.write(cr, uid, ids, {'state':'cancel'})
144         return True
145
146     def action_pause(self, cr, uid, ids):
147         self.write(cr, uid, ids, {'state':'pause'})
148         return True
149
150     def action_resume(self, cr, uid, ids):
151         self.write(cr, uid, ids, {'state':'startworking'})
152         return True
153
154 mrp_production_workcenter_line()
155
156 class mrp_production(osv.osv):
157     _inherit = 'mrp.production'
158     _columns = {
159         'allow_reorder': fields.boolean('Free Serialisation', help="Check this to be able to move independently all production orders, without moving dependent ones."),
160     }
161
162     def _production_date_end(self, cr, uid, ids, prop, unknow_none, context={}):
163         result = {}
164         for prod in self.browse(cr, uid, ids, context=context):
165             result[prod.id] = prod.date_planned
166             for line in prod.workcenter_lines:
167                 result[prod.id] = max(line.date_planned_end, result[prod.id])
168         return result
169
170     def action_production_end(self, cr, uid, ids):
171         obj=self.browse(cr,uid,ids)[0]
172         for workcenter_line in obj.workcenter_lines:
173             tmp=self.pool.get('mrp.production.workcenter.line').action_done(cr,uid,[workcenter_line.id])
174         return super(mrp_production,self).action_production_end(cr,uid,ids)
175
176     def action_cancel(self, cr, uid, ids):
177         obj=self.browse(cr,uid,ids)[0]
178         for workcenter_line in obj.workcenter_lines:
179             tmp=self.pool.get('mrp.production.workcenter.line').action_cancel(cr,uid,[workcenter_line.id])
180         return super(mrp_production,self).action_cancel(cr,uid,ids)
181
182     def _compute_planned_workcenter(self, cr, uid, ids, context={}, mini=False):
183         dt_end = DateTime.now()
184         for po in self.browse(cr, uid, ids, context=context):
185             dt_end = DateTime.strptime(po.date_start or po.date_planned, '%Y-%m-%d %H:%M:%S')
186             if not po.date_start:
187                 self.write(cr, uid, [po.id], {
188                     'date_start': po.date_planned
189                 }, context=context, update=False)
190             old = None
191             for wci in range(len(po.workcenter_lines)):
192                 wc  = po.workcenter_lines[wci]
193                 if (old is None) or (wc.sequence>old):
194                     dt = dt_end
195                 if context.get('__last_update'):
196                     del context['__last_update']
197                 if (wc.date_planned<dt.strftime('%Y-%m-%d %H:%M:%S')) or mini:
198                     self.pool.get('mrp.production.workcenter.line').write(cr, uid, [wc.id],  {
199                         'date_planned':dt.strftime('%Y-%m-%d %H:%M:%S')
200                     }, context=context, update=False)
201                     i = self.pool.get('hr.timesheet.group').interval_get(
202                         cr,
203                         uid,
204                         wc.workcenter_id.timesheet_id and wc.workcenter_id.timesheet_id.id or False,
205                         dt,
206                         wc.hour or 0.0
207                     )
208                     if i:
209                         dt_end = max(dt_end, i[-1][1])
210                 else:
211                     dt_end = DateTime.strptime(wc.date_planned_end, '%Y-%m-%d %H:%M:%S')
212                 old = wc.sequence or 0
213             super(mrp_production, self).write(cr, uid, [po.id], {
214                 'date_finnished': dt_end
215             })
216         return dt_end
217
218     def _move_pass(self, cr, uid, ids, context={}):
219         for po in self.browse(cr, uid, ids, context):
220             if po.allow_reorder:
221                 continue
222             todo = po.move_lines
223             dt = DateTime.strptime(po.date_start,'%Y-%m-%d %H:%M:%S')
224             while todo:
225                 l = todo.pop(0)
226                 if l.state in ('done','cancel','draft'):
227                     continue
228                 todo += l.move_dest_id_lines
229                 if l.production_id and (l.production_id.date_finnished>dt):
230                     if l.production_id.state not in ('done','cancel'):
231                         for wc in l.production_id.workcenter_lines:
232                             i = self.pool.get('hr.timesheet.group').interval_min_get(
233                                 cr, 
234                                 uid, 
235                                 wc.workcenter_id.timesheet_id.id or False, 
236                                 dt, wc.hour or 0.0
237                             )
238                             dt = i[0][0]
239                         if l.production_id.date_start>dt.strftime('%Y-%m-%d %H:%M:%S'):
240                             self.write(cr, uid, [l.production_id.id], {'date_start':dt.strftime('%Y-%m-%d %H:%M:%S')}, mini=True)
241         return True
242
243     def _move_futur(self, cr, uid, ids, context={}):
244         for po in self.browse(cr, uid, ids, context):
245             if po.allow_reorder:
246                 continue
247             for line in po.move_created_ids:
248                 l = line
249                 while l.move_dest_id:
250                     l = l.move_dest_id
251                     if l.state in ('done','cancel','draft'):
252                         break
253                     if l.production_id.state in ('done','cancel'):
254                         break
255                     if l.production_id and (l.production_id.date_start<po.date_finnished):
256                         self.write(cr, uid, [l.production_id.id], {'date_start':po.date_finnished})
257                         break
258
259
260     def write(self, cr, uid, ids, vals, context={}, update=True, mini=True):
261         direction = {}
262         if vals.get('date_start', False):
263             for po in self.browse(cr, uid, ids, context=context):
264                 direction[po.id] = cmp(po.date_start, vals.get('date_start', False))
265         result = super(mrp_production, self).write(cr, uid, ids, vals, context=context)
266         if (vals.get('workcenter_lines', False) or vals.get('date_start', False)) and update:
267             self._compute_planned_workcenter(cr, uid, ids, context=context, mini=mini)
268         for d in direction:
269             if direction[d]==1:
270                 # the production order has been moved to the passed
271                 self._move_pass(cr, uid, [d], context=context)
272                 pass
273             elif direction[d]==-1:
274                 self._move_futur(cr, uid, [d], context=context)
275                 # the production order has been moved to the future
276                 pass
277         return result
278
279     def action_compute(self, cr, uid, ids, properties=[]):
280         result = super(mrp_production, self).action_compute(cr, uid, ids, properties=properties)
281         self._compute_planned_workcenter(cr, uid, ids, context={})
282         return result
283
284 mrp_production()
285
286 class mrp_operations_operation_code(osv.osv):
287     _name="mrp_operations.operation.code"
288     _columns={
289         'name': fields.char('Operation Name',size=64, required=True),
290         'code': fields.char('Code', size=16, required=True),
291         'start_stop': fields.selection([('start','Start'),('pause','Pause'),('resume','Resume'),('cancel','Cancelled'),('done','Done')], 'Status', required=True),
292     }
293 mrp_operations_operation_code()
294
295 class mrp_operations_operation(osv.osv):
296     _name="mrp_operations.operation"
297
298     def _order_date_search_production(self, cr, uid, ids, context=None):
299         operation_ids=self.pool.get('mrp_operations.operation').search(cr, uid, [('production_id','=',ids[0])], context=context)
300         return operation_ids
301
302     def _get_order_date(self, cr, uid, ids, field_name, arg, context):
303         res={}
304         operation_obj=self.browse(cr, uid, ids, context=context)
305         for operation in operation_obj:
306                 res[operation.id]=operation.production_id.date_planned
307         return res
308
309     def calc_delay(self,cr,uid,vals):
310         code_lst=[]
311         time_lst=[]
312
313         code_ids=self.pool.get('mrp_operations.operation.code').search(cr,uid,[('id','=',vals['code_id'])])
314         code=self.pool.get('mrp_operations.operation.code').browse(cr,uid,code_ids)[0]
315
316         oper_ids=self.search(cr,uid,[('production_id','=',vals['production_id']),('workcenter_id','=',vals['workcenter_id'])])
317         oper_objs=self.browse(cr,uid,oper_ids)
318
319         for oper in oper_objs:
320             code_lst.append(oper.code_id.start_stop)
321             time_lst.append(oper.date_start)
322
323         code_lst.append(code.start_stop)
324         time_lst.append(vals['date_start'])
325         diff = 0
326         for i in range(0,len(code_lst)):
327             if code_lst[i]=='pause' or code_lst[i]=='done' or code_lst[i]=='cancel':
328                 if not i: continue
329                 if code_lst[i-1] not in ('resume','start'):
330                    continue
331                 a = datetime.datetime.strptime(time_lst[i-1],'%Y:%m:%d %H:%M:%S')
332                 b = datetime.datetime.strptime(time_lst[i],'%Y:%m:%d %H:%M:%S')
333                 diff += (b-a).days * 24
334                 diff += (b-a).seconds / (60*60)
335         return diff
336
337     def check_operation(self,cr,uid,vals):
338         code_ids=self.pool.get('mrp_operations.operation.code').search(cr,uid,[('id','=',vals['code_id'])])
339         code=self.pool.get('mrp_operations.operation.code').browse(cr,uid,code_ids)[0]
340         code_lst = []
341         oper_ids=self.search(cr,uid,[('production_id','=',vals['production_id']),('workcenter_id','=',vals['workcenter_id'])])
342         oper_objs=self.browse(cr,uid,oper_ids)
343
344         if not oper_objs:
345             if code.start_stop!='start':
346                 raise osv.except_osv(_('Sorry!'),_('Operation is not started yet !'))
347                 return False
348         else:
349             for oper in oper_objs:
350                  code_lst.append(oper.code_id.start_stop)
351             if code.start_stop=='start':
352                     if 'start' in code_lst:
353                         raise osv.except_osv(_('Sorry!'),_('Operation has already started !' 'You  can either Pause /Finish/Cancel the operation'))
354                         return False
355             if code.start_stop=='pause':
356                     if  code_lst[len(code_lst)-1]!='resume' and code_lst[len(code_lst)-1]!='start':
357                         raise osv.except_osv(_('Error!'),_('You cannot Pause the Operation other then Start/Resume state !'))
358                         return False
359             if code.start_stop=='resume':
360                 if code_lst[len(code_lst)-1]!='pause':
361                    raise osv.except_osv(_('Error!'),_(' You cannot Resume the operation other then Pause state !'))
362                    return False
363
364             if code.start_stop=='done':
365                if code_lst[len(code_lst)-1]!='start' and code_lst[len(code_lst)-1]!='resume':
366                   raise osv.except_osv(_('Sorry!'),_('You cannot finish the operation without Starting/Resuming it !'))
367                   return False
368                if 'cancel' in code_lst:
369                   raise osv.except_osv(_('Sorry!'),_('Operation is Already Cancelled  !'))
370                   return False
371             if code.start_stop=='cancel':
372                if  not 'start' in code_lst :
373                    raise osv.except_osv(_('Error!'),_('There is no Operation to be cancelled !'))
374                    return False
375                if 'done' in code_lst:
376                   raise osv.except_osv(_('Error!'),_('Operation is already finished !'))
377                   return False
378         return True
379
380     def write(self, cr, uid, ids, vals, context=None):
381         oper_objs=self.browse(cr,uid,ids)[0]
382         vals['production_id']=oper_objs.production_id.id
383         vals['workcenter_id']=oper_objs.workcenter_id.id
384
385         if 'code_id' in vals:
386             self.check_operation(cr, uid, vals)
387
388         if 'date_start' in vals:
389             vals['date_start']=vals['date_start']
390             vals['code_id']=oper_objs.code_id.id
391             delay=self.calc_delay(cr, uid, vals)
392             wc_op_id=self.pool.get('mrp.production.workcenter.line').search(cr,uid,[('workcenter_id','=',vals['workcenter_id']),('production_id','=',vals['production_id'])])
393             self.pool.get('mrp.production.workcenter.line').write(cr,uid,wc_op_id,{'delay':delay})
394
395         return super(mrp_operations_operation, self).write(cr, uid, ids, vals, context=context)
396
397     def create(self, cr, uid, vals, context=None):
398         wf_service = netsvc.LocalService('workflow')
399         code_ids=self.pool.get('mrp_operations.operation.code').search(cr,uid,[('id','=',vals['code_id'])])
400         code=self.pool.get('mrp_operations.operation.code').browse(cr,uid,code_ids)[0]
401         wc_op_id=self.pool.get('mrp.production.workcenter.line').search(cr,uid,[('workcenter_id','=',vals['workcenter_id']),('production_id','=',vals['production_id'])])
402         if code.start_stop in ('start','done','pause','cancel','resume'):
403             if not wc_op_id:
404                 production_obj=self.pool.get('mrp.production').browse(cr,uid,vals['production_id'])
405                 wc_op_id.append(self.pool.get('mrp.production.workcenter.line').create(cr,uid,{'production_id':vals['production_id'],'name':production_obj.product_id.name,'workcenter_id':vals['workcenter_id']}))
406             if code.start_stop=='start':
407                 tmp=self.pool.get('mrp.production.workcenter.line').action_start_working(cr,uid,wc_op_id)
408                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_start_working', cr)
409
410             if code.start_stop=='done':
411                 tmp=self.pool.get('mrp.production.workcenter.line').action_done(cr,uid,wc_op_id)
412                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_done', cr)
413                 self.pool.get('mrp.production').write(cr,uid,vals['production_id'],{'date_finnished':DateTime.now().strftime('%Y-%m-%d %H:%M:%S')})
414
415             if code.start_stop=='pause':
416                 tmp=self.pool.get('mrp.production.workcenter.line').action_pause(cr,uid,wc_op_id)
417                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_pause', cr)
418
419             if code.start_stop=='resume':
420                 tmp=self.pool.get('mrp.production.workcenter.line').action_resume(cr,uid,wc_op_id)
421                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_resume', cr)
422
423             if code.start_stop=='cancel':
424                 tmp=self.pool.get('mrp.production.workcenter.line').action_cancel(cr,uid,wc_op_id)
425                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_cancel', cr)
426
427         if not self.check_operation(cr, uid, vals):
428             return
429         delay=self.calc_delay(cr, uid, vals)
430         self.pool.get('mrp.production.workcenter.line').write(cr,uid,wc_op_id,{'delay':delay})
431
432         return super(mrp_operations_operation, self).create(cr, uid, vals,  context=context)
433
434     _columns={
435         'production_id':fields.many2one('mrp.production','Production',required=True),
436         'workcenter_id':fields.many2one('mrp.workcenter','Workcenter',required=True),
437         'code_id':fields.many2one('mrp_operations.operation.code','Code',required=True),
438         'date_start': fields.datetime('Start Date'),
439         'date_finished': fields.datetime('End Date'),
440         'order_date': fields.function(_get_order_date,method=True,string='Order Date',type='date',store={'mrp.production':(_order_date_search_production,['date_planned'], 10)}),
441         }
442     _defaults={
443         'date_start': lambda *a:DateTime.now().strftime('%Y-%m-%d %H:%M:%S')
444     }
445
446 mrp_operations_operation()
447 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
448