[FIX] mrp_operations:https://bugs.launchpad.net/openobject-addons/+bug/489239
[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-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 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 # Work Centers
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('resource.calendar').interval_get(cr, uid, op.workcenter_id.calendar_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     _order = "sequence, date_planned"
71     _columns = {
72        'state': fields.selection([('draft','Draft'),('startworking', 'In Progress'),('pause','Pause'),('cancel','Canceled'),('done','Finished')],'State', readonly=True,
73                                  help="* When a work order is created it is set in 'Draft' state.\n" \
74                                        "* When user sets work order in start mode that time it will be set in 'In Progress' state.\n" \
75                                        "* When work order is in running mode, during that time if user wants to stop or to make changes in order then can set in 'Pause' state.\n" \
76                                        "* When the user cancels the work order it will be set in 'Canceled' state.\n" \
77                                        "* When order is completely processed that time it is set in 'Finished' state."),
78        'date_start_date': fields.function(_get_date_date, method=True, string='Start Date', type='date'),
79        'date_planned': fields.datetime('Scheduled Date'),
80        'date_planned_end': fields.function(_get_date_end, method=True, string='End Date', type='datetime'),
81        'date_start': fields.datetime('Start Date'),
82        'date_finnished': fields.datetime('End Date'),
83        'delay': fields.float('Working Hours',help="This is lead time between operation start and stop in this workcenter",readonly=True),
84        'production_state':fields.related('production_id','state',
85             type='selection',
86             selection=[('draft','Draft'),('picking_except', 'Picking Exception'),('confirmed','Waiting Goods'),('ready','Ready to Produce'),('in_production','In Production'),('cancel','Canceled'),('done','Done')],
87             string='Production State', readonly=True),
88        'product':fields.related('production_id','product_id',type='many2one',relation='product.product',string='Product',
89             readonly=True),
90        'qty':fields.related('production_id','product_qty',type='float',string='Qty',readonly=True),
91        'uom':fields.related('production_id','product_uom',type='many2one',relation='product.uom',string='UOM',readonly=True),
92     }
93     _defaults = {
94         'state': lambda *a: 'draft',
95         'delay': lambda *a: 0.0
96     }
97
98     def modify_production_order_state(self,cr,uid,ids,action):
99         wf_service = netsvc.LocalService("workflow")
100         oper_obj=self.browse(cr,uid,ids)[0]
101         prod_obj=oper_obj.production_id
102         if action=='start':
103                if prod_obj.state =='confirmed':
104                    self.pool.get('mrp.production').force_production(cr, uid, [prod_obj.id])
105                    wf_service.trg_validate(uid, 'mrp.production', prod_obj.id, 'button_produce', cr)
106                elif prod_obj.state =='ready':
107                    wf_service.trg_validate(uid, 'mrp.production', prod_obj.id, 'button_produce', cr)
108                elif prod_obj.state =='in_production':
109                    return
110                else:
111                    raise osv.except_osv(_('Error!'),_('Production Order Cannot start in [%s] state') % (prod_obj.state,))
112         else:
113             oper_ids=self.search(cr,uid,[('production_id','=',prod_obj.id)])
114             obj=self.browse(cr,uid,oper_ids)
115             flag=True
116             for line in obj:
117                 if line.state!='done':
118                      flag=False
119             if flag:
120                 wf_service.trg_validate(uid, 'mrp.production', oper_obj.production_id.id, 'button_produce_done', cr)
121         return
122
123     def write(self, cr, uid, ids, vals, context={}, update=True):
124         result = super(mrp_production_workcenter_line, self).write(cr, uid, ids, vals, context=context)
125         if vals.get('date_planned', False) and update:
126             pids = {}
127             pids2 = {}
128             for prod in self.browse(cr, uid, ids, context=context):
129                 if prod.production_id.workcenter_lines:
130                     dstart = min(vals['date_planned'], prod.production_id.workcenter_lines[0]['date_planned'])
131                     self.pool.get('mrp.production').write(cr, uid, [prod.production_id.id], {'date_start':dstart}, context=context, mini=False)
132         return result
133
134     def action_draft(self, cr, uid, ids):
135         self.write(cr, uid, ids, {'state':'draft'})
136         return True
137
138     def action_start_working(self, cr, uid, ids):
139         self.modify_production_order_state(cr,uid,ids,'start')
140         self.write(cr, uid, ids, {'state':'startworking', 'date_start': time.strftime('%Y-%m-%d %H:%M:%S')})
141         return True
142
143     def action_done(self, cr, uid, ids):
144         delay = 0.0
145         date_now = time.strftime('%Y-%m-%d %H:%M:%S')
146         obj_line = self.browse(cr, uid, ids[0])
147         
148         date_start = datetime.datetime.strptime(obj_line.date_start,'%Y-%m-%d %H:%M:%S')
149         date_finished = datetime.datetime.strptime(date_now,'%Y-%m-%d %H:%M:%S')
150         delay += (date_finished-date_start).days * 24
151         delay += (date_finished-date_start).seconds / float(60*60)
152         
153         self.write(cr, uid, ids, {'state':'done', 'date_finnished': date_now,'delay':delay})
154         self.modify_production_order_state(cr,uid,ids,'done')
155         return True
156
157     def action_cancel(self, cr, uid, ids):
158         self.write(cr, uid, ids, {'state':'cancel'})
159         return True
160
161     def action_pause(self, cr, uid, ids):
162         self.write(cr, uid, ids, {'state':'pause'})
163         return True
164
165     def action_resume(self, cr, uid, ids):
166         self.write(cr, uid, ids, {'state':'startworking'})
167         return True
168
169 mrp_production_workcenter_line()
170
171 class mrp_production(osv.osv):
172     _inherit = 'mrp.production'
173     _columns = {
174         'allow_reorder': fields.boolean('Free Serialisation', help="Check this to be able to move independently all production orders, without moving dependent ones."),
175     }
176
177     def _production_date_end(self, cr, uid, ids, prop, unknow_none, context={}):
178         result = {}
179         for prod in self.browse(cr, uid, ids, context=context):
180             result[prod.id] = prod.date_planned
181             for line in prod.workcenter_lines:
182                 result[prod.id] = max(line.date_planned_end, result[prod.id])
183         return result
184
185     def action_production_end(self, cr, uid, ids):
186         obj=self.browse(cr,uid,ids)[0]
187         for workcenter_line in obj.workcenter_lines:
188             tmp=self.pool.get('mrp.production.workcenter.line').action_done(cr,uid,[workcenter_line.id])
189         return super(mrp_production,self).action_production_end(cr,uid,ids)
190     
191     def action_in_production(self, cr, uid, ids):
192         """ Changes state to In Production and writes starting date.
193         @return: True 
194         """        
195         obj = self.browse(cr, uid, ids)[0]
196         workcenter_line_obj = self.pool.get('mrp.production.workcenter.line')
197         for workcenter_line in obj.workcenter_lines:
198             workcenter_line_obj.action_start_working(cr, uid, [workcenter_line.id])
199         return super(mrp_production,self).action_in_production(cr, uid, ids)
200     
201     def action_cancel(self, cr, uid, ids):
202         obj=self.browse(cr,uid,ids)[0]
203         for workcenter_line in obj.workcenter_lines:
204             tmp=self.pool.get('mrp.production.workcenter.line').action_cancel(cr,uid,[workcenter_line.id])
205         return super(mrp_production,self).action_cancel(cr,uid,ids)
206
207     def _compute_planned_workcenter(self, cr, uid, ids, context={}, mini=False):
208         dt_end = DateTime.now()
209         for po in self.browse(cr, uid, ids, context=context):
210             dt_end = DateTime.strptime(po.date_start or po.date_planned, '%Y-%m-%d %H:%M:%S')
211             if not po.date_start:
212                 self.write(cr, uid, [po.id], {
213                     'date_start': po.date_planned
214                 }, context=context, update=False)
215             old = None
216             for wci in range(len(po.workcenter_lines)):
217                 wc  = po.workcenter_lines[wci]
218                 if (old is None) or (wc.sequence>old):
219                     dt = dt_end
220                 if context.get('__last_update'):
221                     del context['__last_update']
222                 if (wc.date_planned<dt.strftime('%Y-%m-%d %H:%M:%S')) or mini:
223                     self.pool.get('mrp.production.workcenter.line').write(cr, uid, [wc.id],  {
224                         'date_planned':dt.strftime('%Y-%m-%d %H:%M:%S')
225                     }, context=context, update=False)
226                     i = self.pool.get('resource.calendar').interval_get(
227                         cr,
228                         uid,
229                         wc.workcenter_id.calendar_id and wc.workcenter_id.calendar_id.id or False,
230                         dt,
231                         wc.hour or 0.0
232                     )
233                     if i:
234                         dt_end = max(dt_end, i[-1][1])
235                 else:
236                     dt_end = DateTime.strptime(wc.date_planned_end, '%Y-%m-%d %H:%M:%S')
237                 old = wc.sequence or 0
238             super(mrp_production, self).write(cr, uid, [po.id], {
239                 'date_finnished': dt_end
240             })
241         return dt_end
242
243     def _move_pass(self, cr, uid, ids, context={}):
244         for po in self.browse(cr, uid, ids, context):
245             if po.allow_reorder:
246                 continue
247             todo = po.move_lines
248             dt = DateTime.strptime(po.date_start,'%Y-%m-%d %H:%M:%S')
249             while todo:
250                 l = todo.pop(0)
251                 if l.state in ('done','cancel','draft'):
252                     continue
253                 todo += l.move_dest_id_lines
254                 if l.production_id and (l.production_id.date_finnished>dt):
255                     if l.production_id.state not in ('done','cancel'):
256                         for wc in l.production_id.workcenter_lines:
257                             i = self.pool.get('resource.calendar').interval_min_get(
258                                 cr,
259                                 uid,
260                                 wc.workcenter_id.calendar_id.id or False,
261                                 dt, wc.hour or 0.0
262                             )
263                             dt = i[0][0]
264                         if l.production_id.date_start>dt.strftime('%Y-%m-%d %H:%M:%S'):
265                             self.write(cr, uid, [l.production_id.id], {'date_start':dt.strftime('%Y-%m-%d %H:%M:%S')}, mini=True)
266         return True
267
268     def _move_futur(self, cr, uid, ids, context={}):
269         for po in self.browse(cr, uid, ids, context):
270             if po.allow_reorder:
271                 continue
272             for line in po.move_created_ids:
273                 l = line
274                 while l.move_dest_id:
275                     l = l.move_dest_id
276                     if l.state in ('done','cancel','draft'):
277                         break
278                     if l.production_id.state in ('done','cancel'):
279                         break
280                     if l.production_id and (l.production_id.date_start<po.date_finnished):
281                         self.write(cr, uid, [l.production_id.id], {'date_start':po.date_finnished})
282                         break
283
284
285     def write(self, cr, uid, ids, vals, context={}, update=True, mini=True):
286         direction = {}
287         if vals.get('date_start', False):
288             for po in self.browse(cr, uid, ids, context=context):
289                 direction[po.id] = cmp(po.date_start, vals.get('date_start', False))
290         result = super(mrp_production, self).write(cr, uid, ids, vals, context=context)
291         if (vals.get('workcenter_lines', False) or vals.get('date_start', False)) and update:
292             self._compute_planned_workcenter(cr, uid, ids, context=context, mini=mini)
293         for d in direction:
294             if direction[d]==1:
295                 # the production order has been moved to the passed
296                 self._move_pass(cr, uid, [d], context=context)
297                 pass
298             elif direction[d]==-1:
299                 self._move_futur(cr, uid, [d], context=context)
300                 # the production order has been moved to the future
301                 pass
302         return result
303
304     def action_compute(self, cr, uid, ids, properties=[]):
305         result = super(mrp_production, self).action_compute(cr, uid, ids, properties=properties)
306         self._compute_planned_workcenter(cr, uid, ids, context={})
307         return result
308
309 mrp_production()
310
311 class mrp_operations_operation_code(osv.osv):
312     _name="mrp_operations.operation.code"
313     _columns={
314         'name': fields.char('Operation Name',size=64, required=True),
315         'code': fields.char('Code', size=16, required=True),
316         'start_stop': fields.selection([('start','Start'),('pause','Pause'),('resume','Resume'),('cancel','Cancelled'),('done','Done')], 'Status', required=True),
317     }
318 mrp_operations_operation_code()
319
320 class mrp_operations_operation(osv.osv):
321     _name="mrp_operations.operation"
322
323     def _order_date_search_production(self, cr, uid, ids, context=None):
324         operation_ids=self.pool.get('mrp_operations.operation').search(cr, uid, [('production_id','=',ids[0])], context=context)
325         return operation_ids
326
327     def _get_order_date(self, cr, uid, ids, field_name, arg, context):
328         res={}
329         operation_obj=self.browse(cr, uid, ids, context=context)
330         for operation in operation_obj:
331                 res[operation.id]=operation.production_id.date_planned
332         return res
333
334     def calc_delay(self,cr,uid,vals):
335         code_lst=[]
336         time_lst=[]
337
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
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         for oper in oper_objs:
345             code_lst.append(oper.code_id.start_stop)
346             time_lst.append(oper.date_start)
347
348         code_lst.append(code.start_stop)
349         time_lst.append(vals['date_start'])
350         diff = 0
351         for i in range(0,len(code_lst)):
352             if code_lst[i]=='pause' or code_lst[i]=='done' or code_lst[i]=='cancel':
353                 if not i: continue
354                 if code_lst[i-1] not in ('resume','start'):
355                    continue
356                 a = datetime.datetime.strptime(time_lst[i-1],'%Y-%m-%d %H:%M:%S')
357                 b = datetime.datetime.strptime(time_lst[i],'%Y-%m-%d %H:%M:%S')
358                 diff += (b-a).days * 24
359                 diff += (b-a).seconds / float(60*60)
360         return diff
361
362     def check_operation(self,cr,uid,vals):
363         code_ids=self.pool.get('mrp_operations.operation.code').search(cr,uid,[('id','=',vals['code_id'])])
364         code=self.pool.get('mrp_operations.operation.code').browse(cr,uid,code_ids)[0]
365         code_lst = []
366         oper_ids=self.search(cr,uid,[('production_id','=',vals['production_id']),('workcenter_id','=',vals['workcenter_id'])])
367         oper_objs=self.browse(cr,uid,oper_ids)
368
369         if not oper_objs:
370             if code.start_stop!='start':
371                 raise osv.except_osv(_('Sorry!'),_('Operation is not started yet !'))
372                 return False
373         else:
374             for oper in oper_objs:
375                  code_lst.append(oper.code_id.start_stop)
376             if code.start_stop=='start':
377                     if 'start' in code_lst:
378                         raise osv.except_osv(_('Sorry!'),_('Operation has already started !' 'You  can either Pause /Finish/Cancel the operation'))
379                         return False
380             if code.start_stop=='pause':
381                     if  code_lst[len(code_lst)-1]!='resume' and code_lst[len(code_lst)-1]!='start':
382                         raise osv.except_osv(_('Error!'),_('You cannot Pause the Operation other then Start/Resume state !'))
383                         return False
384             if code.start_stop=='resume':
385                 if code_lst[len(code_lst)-1]!='pause':
386                    raise osv.except_osv(_('Error!'),_(' You cannot Resume the operation other then Pause state !'))
387                    return False
388
389             if code.start_stop=='done':
390                if code_lst[len(code_lst)-1]!='start' and code_lst[len(code_lst)-1]!='resume':
391                   raise osv.except_osv(_('Sorry!'),_('You cannot finish the operation without Starting/Resuming it !'))
392                   return False
393                if 'cancel' in code_lst:
394                   raise osv.except_osv(_('Sorry!'),_('Operation is Already Cancelled  !'))
395                   return False
396             if code.start_stop=='cancel':
397                if  not 'start' in code_lst :
398                    raise osv.except_osv(_('Error!'),_('There is no Operation to be cancelled !'))
399                    return False
400                if 'done' in code_lst:
401                   raise osv.except_osv(_('Error!'),_('Operation is already finished !'))
402                   return False
403         return True
404
405     def write(self, cr, uid, ids, vals, context=None):
406         oper_objs=self.browse(cr,uid,ids)[0]
407         vals['production_id']=oper_objs.production_id.id
408         vals['workcenter_id']=oper_objs.workcenter_id.id
409
410         if 'code_id' in vals:
411             self.check_operation(cr, uid, vals)
412
413         if 'date_start' in vals:
414             vals['date_start']=vals['date_start']
415             vals['code_id']=oper_objs.code_id.id
416             delay=self.calc_delay(cr, uid, vals)
417             wc_op_id=self.pool.get('mrp.production.workcenter.line').search(cr,uid,[('workcenter_id','=',vals['workcenter_id']),('production_id','=',vals['production_id'])])
418             self.pool.get('mrp.production.workcenter.line').write(cr,uid,wc_op_id,{'delay':delay})
419
420         return super(mrp_operations_operation, self).write(cr, uid, ids, vals, context=context)
421
422     def create(self, cr, uid, vals, context=None):
423         wf_service = netsvc.LocalService('workflow')
424         code_ids=self.pool.get('mrp_operations.operation.code').search(cr,uid,[('id','=',vals['code_id'])])
425         code=self.pool.get('mrp_operations.operation.code').browse(cr,uid,code_ids)[0]
426         wc_op_id=self.pool.get('mrp.production.workcenter.line').search(cr,uid,[('workcenter_id','=',vals['workcenter_id']),('production_id','=',vals['production_id'])])
427         if code.start_stop in ('start','done','pause','cancel','resume'):
428             if not wc_op_id:
429                 production_obj=self.pool.get('mrp.production').browse(cr,uid,vals['production_id'])
430                 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']}))
431             if code.start_stop=='start':
432                 tmp=self.pool.get('mrp.production.workcenter.line').action_start_working(cr,uid,wc_op_id)
433                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_start_working', cr)
434                 
435
436             if code.start_stop=='done':
437                 tmp=self.pool.get('mrp.production.workcenter.line').action_done(cr,uid,wc_op_id)
438                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_done', cr)
439                 self.pool.get('mrp.production').write(cr,uid,vals['production_id'],{'date_finnished':DateTime.now().strftime('%Y-%m-%d %H:%M:%S')})
440
441             if code.start_stop=='pause':
442                 tmp=self.pool.get('mrp.production.workcenter.line').action_pause(cr,uid,wc_op_id)
443                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_pause', cr)
444
445             if code.start_stop=='resume':
446                 tmp=self.pool.get('mrp.production.workcenter.line').action_resume(cr,uid,wc_op_id)
447                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_resume', cr)
448
449             if code.start_stop=='cancel':
450                 tmp=self.pool.get('mrp.production.workcenter.line').action_cancel(cr,uid,wc_op_id)
451                 wf_service.trg_validate(uid, 'mrp.production.workcenter.line', wc_op_id[0], 'button_cancel', cr)
452
453         if not self.check_operation(cr, uid, vals):
454             return
455         delay=self.calc_delay(cr, uid, vals)
456         line_vals = {}
457         line_vals['delay'] = delay
458         if vals.get('date_start',False):
459             if code.start_stop == 'done':
460                 line_vals['date_finnished'] = vals['date_start']
461             elif code.start_stop == 'start':    
462                 line_vals['date_start'] = vals['date_start']
463
464         self.pool.get('mrp.production.workcenter.line').write(cr, uid, wc_op_id, line_vals, context=context)
465
466         return super(mrp_operations_operation, self).create(cr, uid, vals, context=context)
467
468     _columns={
469         'production_id':fields.many2one('mrp.production','Production',required=True),
470         'workcenter_id':fields.many2one('mrp.workcenter','Work Center',required=True),
471         'code_id':fields.many2one('mrp_operations.operation.code','Code',required=True),
472         'date_start': fields.datetime('Start Date'),
473         'date_finished': fields.datetime('End Date'),
474         'order_date': fields.function(_get_order_date,method=True,string='Order Date',type='date',store={'mrp.production':(_order_date_search_production,['date_planned'], 10)}),
475         }
476     _defaults={
477         'date_start': lambda *a:DateTime.now().strftime('%Y-%m-%d %H:%M:%S')
478     }
479
480 mrp_operations_operation()
481 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
482