1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from osv import fields
28 from mx import DateTime
29 from tools.translate import _
31 #----------------------------------------------------------
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
38 # TODO: Work Center may be recursive ?
41 class stock_move(osv.osv):
42 _inherit = 'stock.move'
44 'move_dest_id_lines': fields.one2many('stock.move','move_dest_id', 'Children Moves')
48 class mrp_production_workcenter_line(osv.osv):
49 def _get_date_date(self, cr, uid, ids, field_name, arg, context):
51 for op in self.browse(cr, uid, ids, context=context):
53 res[op.id] = op.date_start[:10]
57 def _get_date_end(self, cr, uid, ids, field_name, arg, context):
59 for op in self.browse(cr, uid, ids, context=context):
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)
65 res[op.id] = i[-1][1].strftime('%Y-%m-%d %H:%M:%S')
67 res[op.id] = op.date_planned
69 _inherit = 'mrp.production.workcenter.line'
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',
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',
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),
88 'state': lambda *a: 'draft',
89 'delay': lambda *a: 0.0
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
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':
105 raise osv.except_osv(_('Error!'),_('Production Order Cannot start in [%s] state') % (prod_obj.state,))
107 oper_ids=self.search(cr,uid,[('production_id','=',prod_obj.id)])
108 obj=self.browse(cr,uid,oper_ids)
111 if line.state!='done':
114 wf_service.trg_validate(uid, 'mrp.production', oper_obj.production_id.id, 'button_produce_done', cr)
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:
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)
128 def action_draft(self, cr, uid, ids):
129 self.write(cr, uid, ids, {'state':'draft'})
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')})
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')
142 def action_cancel(self, cr, uid, ids):
143 self.write(cr, uid, ids, {'state':'cancel'})
146 def action_pause(self, cr, uid, ids):
147 self.write(cr, uid, ids, {'state':'pause'})
150 def action_resume(self, cr, uid, ids):
151 self.write(cr, uid, ids, {'state':'startworking'})
154 mrp_production_workcenter_line()
156 class mrp_production(osv.osv):
157 _inherit = 'mrp.production'
159 'allow_reorder': fields.boolean('Free Serialisation', help="Check this to be able to move independently all production orders, without moving dependent ones."),
162 def _production_date_end(self, cr, uid, ids, prop, unknow_none, context={}):
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])
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)
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)
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)
191 for wci in range(len(po.workcenter_lines)):
192 wc = po.workcenter_lines[wci]
193 if (old is None) or (wc.sequence>old):
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(
204 wc.workcenter_id.timesheet_id and wc.workcenter_id.timesheet_id.id or False,
209 dt_end = max(dt_end, i[-1][1])
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
218 def _move_pass(self, cr, uid, ids, context={}):
219 for po in self.browse(cr, uid, ids, context):
223 dt = DateTime.strptime(po.date_start,'%Y-%m-%d %H:%M:%S')
226 if l.state in ('done','cancel','draft'):
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(
235 wc.workcenter_id.timesheet_id.id or False,
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)
243 def _move_futur(self, cr, uid, ids, context={}):
244 for po in self.browse(cr, uid, ids, context):
247 for line in po.move_created_ids:
249 while l.move_dest_id:
251 if l.state in ('done','cancel','draft'):
253 if l.production_id.state in ('done','cancel'):
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})
260 def write(self, cr, uid, ids, vals, context={}, update=True, mini=True):
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)
270 # the production order has been moved to the passed
271 self._move_pass(cr, uid, [d], context=context)
273 elif direction[d]==-1:
274 self._move_futur(cr, uid, [d], context=context)
275 # the production order has been moved to the future
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={})
286 class mrp_operations_operation_code(osv.osv):
287 _name="mrp_operations.operation.code"
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),
293 mrp_operations_operation_code()
295 class mrp_operations_operation(osv.osv):
296 _name="mrp_operations.operation"
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)
302 def _get_order_date(self, cr, uid, ids, field_name, arg, context):
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
309 def calc_delay(self,cr,uid,vals):
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]
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)
319 for oper in oper_objs:
320 code_lst.append(oper.code_id.start_stop)
321 time_lst.append(oper.date_start)
323 code_lst.append(code.start_stop)
324 time_lst.append(vals['date_start'])
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':
329 if code_lst[i-1] not in ('resume','start'):
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)
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]
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)
345 if code.start_stop!='start':
346 raise osv.except_osv(_('Sorry!'),_('Operation is not started yet !'))
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'))
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 !'))
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 !'))
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 !'))
368 if 'cancel' in code_lst:
369 raise osv.except_osv(_('Sorry!'),_('Operation is Already Cancelled !'))
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 !'))
375 if 'done' in code_lst:
376 raise osv.except_osv(_('Error!'),_('Operation is already finished !'))
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
385 if 'code_id' in vals:
386 self.check_operation(cr, uid, vals)
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})
395 return super(mrp_operations_operation, self).write(cr, uid, ids, vals, context=context)
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'):
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)
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')})
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)
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)
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)
427 if not self.check_operation(cr, uid, vals):
429 delay=self.calc_delay(cr, uid, vals)
430 self.pool.get('mrp.production.workcenter.line').write(cr,uid,wc_op_id,{'delay':delay})
432 return super(mrp_operations_operation, self).create(cr, uid, vals, context=context)
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)}),
443 'date_start': lambda *a:DateTime.now().strftime('%Y-%m-%d %H:%M:%S')
446 mrp_operations_operation()
447 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: