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