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