[IMP]: Improvement for bug-701017
[odoo/odoo.git] / addons / mrp / mrp.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 datetime import datetime
23 from osv import osv, fields
24 from tools.translate import _
25 import netsvc
26 import time
27 import tools
28
29
30 #----------------------------------------------------------
31 # Work Centers
32 #----------------------------------------------------------
33 # capacity_hour : capacity per hour. default: 1.0.
34 #          Eg: If 5 concurrent operations at one time: capacity = 5 (because 5 employees)
35 # unit_per_cycle : how many units are produced for one cycle
36
37 class mrp_workcenter(osv.osv):
38     _name = 'mrp.workcenter'
39     _description = 'Work Center'
40     _inherits = {'resource.resource':"resource_id"}
41     _columns = {
42         'note': fields.text('Description', help="Description of the work center. Explain here what's a cycle according to this work center."),
43         'capacity_per_cycle': fields.float('Capacity per Cycle', help="Number of operations this work center can do in parallel. If this work center represents a team of 5 workers, the capacity per cycle is 5."),
44         'time_cycle': fields.float('Time for 1 cycle (hour)', help="Time in hours for doing one cycle."),
45         'time_start': fields.float('Time before prod.', help="Time in hours for the setup."),
46         'time_stop': fields.float('Time after prod.', help="Time in hours for the cleaning."),
47         'costs_hour': fields.float('Cost per hour', help="Specify Cost of Work center per hour."),
48         'costs_hour_account_id': fields.many2one('account.analytic.account', 'Hour Account', domain=[('type','<>','view')],
49             help="Complete this only if you want automatic analytic accounting entries on production orders."),
50         'costs_cycle': fields.float('Cost per cycle', help="Specify Cost of Work center per cycle."),
51         'costs_cycle_account_id': fields.many2one('account.analytic.account', 'Cycle Account', domain=[('type','<>','view')],
52             help="Complete this only if you want automatic analytic accounting entries on production orders."),
53         'costs_journal_id': fields.many2one('account.analytic.journal', 'Analytic Journal'),
54         'costs_general_account_id': fields.many2one('account.account', 'General Account', domain=[('type','<>','view')]),
55         'resource_id': fields.many2one('resource.resource','Resource', ondelete='cascade', required=True),
56         'product_id': fields.many2one('product.product','Work Center Product', help="Fill this product to track easily your production costs in the analytic accounting."),
57     }
58     _defaults = {
59         'capacity_per_cycle': 1.0,
60         'resource_type': 'material',
61      }
62
63     def on_change_product_cost(self, cr, uid, ids, product_id, context=None):
64         if context is None:
65             context = {}
66         value = {}
67
68         if product_id:
69             cost = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
70             value = {'costs_hour': cost.standard_price}
71         return {'value': value}
72
73 mrp_workcenter()
74
75
76 class mrp_routing(osv.osv):
77     """
78     For specifying the routings of workcenters.
79     """
80     _name = 'mrp.routing'
81     _description = 'Routing'
82     _columns = {
83         'name': fields.char('Name', size=64, required=True),
84         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the routing without removing it."),
85         'code': fields.char('Code', size=8),
86
87         'note': fields.text('Description'),
88         'workcenter_lines': fields.one2many('mrp.routing.workcenter', 'routing_id', 'Work Centers'),
89
90         'location_id': fields.many2one('stock.location', 'Production Location',
91             help="Keep empty if you produce at the location where the finished products are needed." \
92                 "Set a location if you produce at a fixed location. This can be a partner location " \
93                 "if you subcontract the manufacturing operations."
94         ),
95         'company_id': fields.many2one('res.company', 'Company'),
96     }
97     _defaults = {
98         'active': lambda *a: 1,
99         'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'mrp.routing', context=context)
100     }
101 mrp_routing()
102
103 class mrp_routing_workcenter(osv.osv):
104     """
105     Defines working cycles and hours of a workcenter using routings.
106     """
107     _name = 'mrp.routing.workcenter'
108     _description = 'Workcenter Usage'
109     _columns = {
110         'workcenter_id': fields.many2one('mrp.workcenter', 'Work Center', required=True),
111         'name': fields.char('Name', size=64, required=True),
112         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of routing work centers."),
113         'cycle_nbr': fields.float('Number of Cycles', required=True,
114             help="Number of iterations this work center has to do in the specified operation of the routing."),
115         'hour_nbr': fields.float('Number of Hours', required=True, help="Time in hours for this work center to achieve the operation of the specified routing."),
116         'routing_id': fields.many2one('mrp.routing', 'Parent Routing', select=True, ondelete='cascade',
117              help="Routing indicates all the workcenters used, for how long and/or cycles." \
118                 "If Routing is indicated then,the third tab of a production order (workcenters) will be automatically pre-completed."),
119         'note': fields.text('Description'),
120         'company_id': fields.related('routing_id', 'company_id', type='many2one', relation='res.company', string='Company'),
121     }
122     _defaults = {
123         'cycle_nbr': lambda *a: 1.0,
124         'hour_nbr': lambda *a: 0.0,
125     }
126 mrp_routing_workcenter()
127
128 class mrp_bom(osv.osv):
129     """
130     Defines bills of material for a product.
131     """
132     _name = 'mrp.bom'
133     _description = 'Bill of Material'
134
135     def _child_compute(self, cr, uid, ids, name, arg, context=None):
136         """ Gets child bom.
137         @param self: The object pointer
138         @param cr: The current row, from the database cursor,
139         @param uid: The current user ID for security checks
140         @param ids: List of selected IDs
141         @param name: Name of the field
142         @param arg: User defined argument
143         @param context: A standard dictionary for contextual values
144         @return:  Dictionary of values
145         """
146         result = {}
147         if context is None:
148             context = {}
149         bom_obj = self.pool.get('mrp.bom')
150         bom_id = context and context.get('active_id', False) or False
151         cr.execute('select id from mrp_bom')
152         if all(bom_id != r[0] for r in cr.fetchall()):
153             ids.sort()
154             bom_id = ids[0]
155         bom_parent = bom_obj.browse(cr, uid, bom_id, context=context)
156         for bom in self.browse(cr, uid, ids, context=context):
157             if (bom_parent) or (bom.id == bom_id):
158                 result[bom.id] = map(lambda x: x.id, bom.bom_lines)
159             else:
160                 result[bom.id] = []
161             if bom.bom_lines:
162                 continue
163             ok = ((name=='child_complete_ids') and (bom.product_id.supply_method=='produce'))
164             if (bom.type=='phantom' or ok):
165                 sids = bom_obj.search(cr, uid, [('bom_id','=',False),('product_id','=',bom.product_id.id)])
166                 if sids:
167                     bom2 = bom_obj.browse(cr, uid, sids[0], context=context)
168                     result[bom.id] += map(lambda x: x.id, bom2.bom_lines)
169
170         return result
171
172     def _compute_type(self, cr, uid, ids, field_name, arg, context=None):
173         """ Sets particular method for the selected bom type.
174         @param field_name: Name of the field
175         @param arg: User defined argument
176         @return:  Dictionary of values
177         """
178         res = dict(map(lambda x: (x,''), ids))
179         for line in self.browse(cr, uid, ids, context=context):
180             if line.type == 'phantom' and not line.bom_id:
181                 res[line.id] = 'set'
182                 continue
183             if line.bom_lines or line.type == 'phantom':
184                 continue
185             if line.product_id.supply_method == 'produce':
186                 if line.product_id.procure_method == 'make_to_stock':
187                     res[line.id] = 'stock'
188                 else:
189                     res[line.id] = 'order'
190         return res
191
192     _columns = {
193         'name': fields.char('Name', size=64, required=True),
194         'code': fields.char('Reference', size=16),
195         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the bills of material without removing it."),
196         'type': fields.selection([('normal','Normal BoM'),('phantom','Sets / Phantom')], 'BoM Type', required=True,
197                                  help= "If a sub-product is used in several products, it can be useful to create its own BoM. "\
198                                  "Though if you don't want separated production orders for this sub-product, select Set/Phantom as BoM type. "\
199                                  "If a Phantom BoM is used for a root product, it will be sold and shipped as a set of components, instead of being produced."),
200         'method': fields.function(_compute_type, string='Method', method=True, type='selection', selection=[('',''),('stock','On Stock'),('order','On Order'),('set','Set / Pack')]),
201         'date_start': fields.date('Valid From', help="Validity of this BoM or component. Keep empty if it's always valid."),
202         'date_stop': fields.date('Valid Until', help="Validity of this BoM or component. Keep empty if it's always valid."),
203         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bills of material."),
204         'position': fields.char('Internal Reference', size=64, help="Reference to a position in an external plan."),
205         'product_id': fields.many2one('product.product', 'Product', required=True),
206         'product_uos_qty': fields.float('Product UOS Qty'),
207         'product_uos': fields.many2one('product.uom', 'Product UOS', help="Product UOS (Unit of Sale) is the unit of measurement for the invoicing and promotion of stock."),
208         'product_qty': fields.float('Product Qty', required=True),
209         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True, help="UoM (Unit of Measure) is the unit of measurement for the inventory control"),
210         'product_rounding': fields.float('Product Rounding', help="Rounding applied on the product quantity."),
211         'product_efficiency': fields.float('Manufacturing Efficiency', required=True, help="A factor of 0.9 means a loss of 10% within the production process."),
212         'bom_lines': fields.one2many('mrp.bom', 'bom_id', 'BoM Lines'),
213         'bom_id': fields.many2one('mrp.bom', 'Parent BoM', ondelete='cascade', select=True),
214         'routing_id': fields.many2one('mrp.routing', 'Routing', help="The list of operations (list of work centers) to produce the finished product. The routing is mainly used to compute work center costs during operations and to plan future loads on work centers based on production planning."),
215         'property_ids': fields.many2many('mrp.property', 'mrp_bom_property_rel', 'bom_id','property_id', 'Properties'),
216         'revision_ids': fields.one2many('mrp.bom.revision', 'bom_id', 'BoM Revisions'),
217         'child_complete_ids': fields.function(_child_compute, relation='mrp.bom', method=True, string="BoM Hierarchy", type='many2many'),
218         'company_id': fields.many2one('res.company','Company',required=True),
219     }
220     _defaults = {
221         'active': lambda *a: 1,
222         'product_efficiency': lambda *a: 1.0,
223         'product_qty': lambda *a: 1.0,
224         'product_rounding': lambda *a: 0.0,
225         'type': lambda *a: 'normal',
226         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'mrp.bom', context=c),
227     }
228     _order = "sequence"
229     _sql_constraints = [
230         ('bom_qty_zero', 'CHECK (product_qty>0)',  'All product quantities must be greater than 0.\n' \
231             'You should install the mrp_subproduct module if you want to manage extra products on BoMs !'),
232     ]
233
234     def _check_recursion(self, cr, uid, ids, context=None):
235         level = 100
236         while len(ids):
237             cr.execute('select distinct bom_id from mrp_bom where id IN %s',(tuple(ids),))
238             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
239             if not level:
240                 return False
241             level -= 1
242         return True
243     _constraints = [
244         (_check_recursion, 'Error ! You can not create recursive BoM.', ['parent_id'])
245     ]
246
247
248     def onchange_product_id(self, cr, uid, ids, product_id, name, context=None):
249         """ Changes UoM and name if product_id changes.
250         @param name: Name of the field
251         @param product_id: Changed product_id
252         @return:  Dictionary of changed values
253         """
254         if product_id:
255             prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
256             v = {'product_uom': prod.uom_id.id}
257             if not name:
258                 v['name'] = prod.name
259             return {'value': v}
260         return {}
261
262     def _bom_find(self, cr, uid, product_id, product_uom, properties=[]):
263         """ Finds BoM for particular product and product uom.
264         @param product_id: Selected product.
265         @param product_uom: Unit of measure of a product.
266         @param properties: List of related properties.
267         @return: False or BoM id.
268         """
269         cr.execute('select id from mrp_bom where product_id=%s and bom_id is null order by sequence', (product_id,))
270         ids = map(lambda x: x[0], cr.fetchall())
271         max_prop = 0
272         result = False
273         for bom in self.pool.get('mrp.bom').browse(cr, uid, ids):
274             prop = 0
275             for prop_id in bom.property_ids:
276                 if prop_id.id in properties:
277                     prop += 1
278             if (prop > max_prop) or ((max_prop == 0) and not result):
279                 result = bom.id
280                 max_prop = prop
281         return result
282
283     def _bom_explode(self, cr, uid, bom, factor, properties=[], addthis=False, level=0):
284         """ Finds Products and Workcenters for related BoM for manufacturing order.
285         @param bom: BoM of particular product.
286         @param factor: Factor of product UoM.
287         @param properties: A List of properties Ids.
288         @param addthis: If BoM found then True else False.
289         @param level: Depth level to find BoM lines starts from 10.
290         @return: result: List of dictionaries containing product details.
291                  result2: List of dictionaries containing workcenter details.
292         """
293         factor = factor / (bom.product_efficiency or 1.0)
294         factor = rounding(factor, bom.product_rounding)
295         if factor < bom.product_rounding:
296             factor = bom.product_rounding
297         result = []
298         result2 = []
299         phantom = False
300         if bom.type == 'phantom' and not bom.bom_lines:
301             newbom = self._bom_find(cr, uid, bom.product_id.id, bom.product_uom.id, properties)
302             if newbom:
303                 res = self._bom_explode(cr, uid, self.browse(cr, uid, [newbom])[0], factor*bom.product_qty, properties, addthis=True, level=level+10)
304                 result = result + res[0]
305                 result2 = result2 + res[1]
306                 phantom = True
307             else:
308                 phantom = False
309         if not phantom:
310             if addthis and not bom.bom_lines:
311                 result.append(
312                 {
313                     'name': bom.product_id.name,
314                     'product_id': bom.product_id.id,
315                     'product_qty': bom.product_qty * factor,
316                     'product_uom': bom.product_uom.id,
317                     'product_uos_qty': bom.product_uos and bom.product_uos_qty * factor or False,
318                     'product_uos': bom.product_uos and bom.product_uos.id or False,
319                 })
320             if bom.routing_id:
321                 for wc_use in bom.routing_id.workcenter_lines:
322                     wc = wc_use.workcenter_id
323                     d, m = divmod(factor, wc_use.workcenter_id.capacity_per_cycle)
324                     mult = (d + (m and 1.0 or 0.0))
325                     cycle = mult * wc_use.cycle_nbr
326                     result2.append({
327                         'name': tools.ustr(wc_use.name) + ' - '  + tools.ustr(bom.product_id.name),
328                         'workcenter_id': wc.id,
329                         'sequence': level+(wc_use.sequence or 0),
330                         'cycle': cycle,
331                         'hour': float(wc_use.hour_nbr*mult + ((wc.time_start or 0.0)+(wc.time_stop or 0.0)+cycle*(wc.time_cycle or 0.0)) * (wc.time_efficiency or 1.0)),
332                     })
333             for bom2 in bom.bom_lines:
334                 res = self._bom_explode(cr, uid, bom2, factor, properties, addthis=True, level=level+10)
335                 result = result + res[0]
336                 result2 = result2 + res[1]
337         return result, result2
338
339     def copy_data(self, cr, uid, id, default=None, context=None):
340         if default is None:
341             default = {}
342         if context is None:
343             context = {}
344         bom_data = self.read(cr, uid, id, [], context=context)
345         default.update({'name': bom_data['name'] + ' ' + _('Copy')})
346         if context.get('copy_from_product',False):
347             #Check for the BOM LINES(child BoM)
348             if not bom_data['bom_lines']:
349                 return 0
350         return super(mrp_bom, self).copy_data(cr, uid, id, default, context=context)
351
352 mrp_bom()
353
354 class mrp_bom_revision(osv.osv):
355     _name = 'mrp.bom.revision'
356     _description = 'Bill of Material Revision'
357     _columns = {
358         'name': fields.char('Modification name', size=64, required=True),
359         'description': fields.text('Description'),
360         'date': fields.date('Modification Date'),
361         'indice': fields.char('Revision', size=16),
362         'last_indice': fields.char('last indice', size=64),
363         'author_id': fields.many2one('res.users', 'Author'),
364         'bom_id': fields.many2one('mrp.bom', 'BoM', select=True),
365     }
366
367     _defaults = {
368         'author_id': lambda x, y, z, c: z,
369         'date': lambda *a: time.strftime('%Y-%m-%d'),
370     }
371
372 mrp_bom_revision()
373
374 def rounding(f, r):
375     if not r:
376         return f
377     return round(f / r) * r
378
379 class mrp_production(osv.osv):
380     """
381     Production Orders / Manufacturing Orders
382     """
383     _name = 'mrp.production'
384     _description = 'Manufacturing Order'
385     _date_name  = 'date_planned'
386
387     def _production_calc(self, cr, uid, ids, prop, unknow_none, context=None):
388         """ Calculates total hours and total no. of cycles for a production order.
389         @param prop: Name of field.
390         @param unknow_none:
391         @return: Dictionary of values.
392         """
393         result = {}
394         for prod in self.browse(cr, uid, ids, context=context):
395             result[prod.id] = {
396                 'hour_total': 0.0,
397                 'cycle_total': 0.0,
398             }
399             for wc in prod.workcenter_lines:
400                 result[prod.id]['hour_total'] += wc.hour
401                 result[prod.id]['cycle_total'] += wc.cycle
402         return result
403
404     def _production_date_end(self, cr, uid, ids, prop, unknow_none, context=None):
405         """ Finds production end date.
406         @param prop: Name of field.
407         @param unknow_none:
408         @return: Dictionary of values.
409         """
410         result = {}
411         for prod in self.browse(cr, uid, ids, context=context):
412             result[prod.id] = prod.date_planned
413         return result
414
415     def _production_date(self, cr, uid, ids, prop, unknow_none, context=None):
416         """ Finds production planned date.
417         @param prop: Name of field.
418         @param unknow_none:
419         @return: Dictionary of values.
420         """
421         result = {}
422         for prod in self.browse(cr, uid, ids, context=context):
423             result[prod.id] = prod.date_planned[:10]
424         return result
425
426     _columns = {
427         'name': fields.char('Reference', size=64, required=True),
428         'origin': fields.char('Source Document', size=64, help="Reference of the document that generated this production order request."),
429         'priority': fields.selection([('0','Not urgent'),('1','Normal'),('2','Urgent'),('3','Very Urgent')], 'Priority'),
430
431         'product_id': fields.many2one('product.product', 'Product', required=True, ),
432         'product_qty': fields.float('Product Qty', required=True, states={'draft':[('readonly',False)]}, readonly=True),
433         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True, states={'draft':[('readonly',False)]}, readonly=True),
434         'product_uos_qty': fields.float('Product UoS Qty', states={'draft':[('readonly',False)]}, readonly=True),
435         'product_uos': fields.many2one('product.uom', 'Product UoS', states={'draft':[('readonly',False)]}, readonly=True),
436
437         'location_src_id': fields.many2one('stock.location', 'Raw Materials Location', required=True,
438             help="Location where the system will look for components."),
439         'location_dest_id': fields.many2one('stock.location', 'Finished Products Location', required=True,
440             help="Location where the system will stock the finished products."),
441
442         'date_planned_end': fields.function(_production_date_end, method=True, type='date', string='Scheduled End Date'),
443         'date_planned_date': fields.function(_production_date, method=True, type='date', string='Scheduled Date'),
444         'date_planned': fields.datetime('Scheduled date', required=True, select=1),
445         'date_start': fields.datetime('Start Date'),
446         'date_finished': fields.datetime('End Date'),
447
448         'bom_id': fields.many2one('mrp.bom', 'Bill of Material', domain=[('bom_id','=',False)]),
449         'routing_id': fields.many2one('mrp.routing', string='Routing', on_delete='set null', help="The list of operations (list of work centers) to produce the finished product. The routing is mainly used to compute work center costs during operations and to plan future loads on work centers based on production plannification."),
450
451         'picking_id': fields.many2one('stock.picking', 'Picking list', readonly=True, ondelete="restrict",
452             help="This is the internal picking list that brings the finished product to the production plan"),
453         'move_prod_id': fields.many2one('stock.move', 'Move product', readonly=True),
454         'move_lines': fields.many2many('stock.move', 'mrp_production_move_ids', 'production_id', 'move_id', 'Products to Consume', domain=[('state','not in', ('done', 'cancel'))], states={'done':[('readonly',True)]}),
455         'move_lines2': fields.many2many('stock.move', 'mrp_production_move_ids', 'production_id', 'move_id', 'Consumed Products', domain=[('state','in', ('done', 'cancel'))]),
456         'move_created_ids': fields.one2many('stock.move', 'production_id', 'Moves Created', domain=[('state','not in', ('done', 'cancel'))], states={'done':[('readonly',True)]}),
457         'move_created_ids2': fields.one2many('stock.move', 'production_id', 'Moves Created', domain=[('state','in', ('done', 'cancel'))]),
458         'product_lines': fields.one2many('mrp.production.product.line', 'production_id', 'Scheduled goods'),
459         'workcenter_lines': fields.one2many('mrp.production.workcenter.line', 'production_id', 'Work Centers Utilisation'),
460         'state': fields.selection([('draft','Draft'),('picking_except', 'Picking Exception'),('confirmed','Waiting Goods'),('ready','Ready to Produce'),('in_production','In Production'),('cancel','Cancelled'),('done','Done')],'State', readonly=True,
461                                     help='When the production order is created the state is set to \'Draft\'.\n If the order is confirmed the state is set to \'Waiting Goods\'.\n If any exceptions are there, the state is set to \'Picking Exception\'.\
462                                     \nIf the stock is available then the state is set to \'Ready to Produce\'.\n When the production gets started then the state is set to \'In Production\'.\n When the production is over, the state is set to \'Done\'.'),
463         'hour_total': fields.function(_production_calc, method=True, type='float', string='Total Hours', multi='workorder', store=True),
464         'cycle_total': fields.function(_production_calc, method=True, type='float', string='Total Cycles', multi='workorder', store=True),
465         'company_id': fields.many2one('res.company','Company',required=True),
466     }
467     _defaults = {
468         'priority': lambda *a: '1',
469         'state': lambda *a: 'draft',
470         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
471         'product_qty':  lambda *a: 1.0,
472         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'mrp.production') or '/',
473         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'mrp.production', context=c),
474     }
475     _order = 'priority desc, date_planned asc';
476
477     def _check_qty(self, cr, uid, ids, context=None):
478         orders = self.browse(cr, uid, ids, context=context)
479         for order in orders:
480             if order.product_qty <= 0:
481                 return False
482         return True
483
484     _constraints = [
485         (_check_qty, 'Order quantity cannot be negative or zero !', ['product_qty']),
486     ]
487
488     def unlink(self, cr, uid, ids, context=None):
489         productions = self.read(cr, uid, ids, ['state'])
490         unlink_ids = []
491         for s in productions:
492             if s['state'] in ['draft','cancel']:
493                 unlink_ids.append(s['id'])
494             else:
495                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Production Order(s) which are in %s State!') % s['state'])
496         return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
497
498     def copy(self, cr, uid, id, default=None, context=None):
499         if default is None:
500             default = {}
501         default.update({
502             'name': self.pool.get('ir.sequence').get(cr, uid, 'mrp.production'),
503             'move_lines' : [],
504             'move_lines2' : [],
505             'move_created_ids' : [],
506             'move_created_ids2' : [],
507             'product_lines' : [],
508             'picking_id': False
509         })
510         return super(mrp_production, self).copy(cr, uid, id, default, context)
511
512     def location_id_change(self, cr, uid, ids, src, dest, context=None):
513         """ Changes destination location if source location is changed.
514         @param src: Source location id.
515         @param dest: Destination location id.
516         @return: Dictionary of values.
517         """
518         if dest:
519             return {}
520         if src:
521             return {'value': {'location_dest_id': src}}
522         return {}
523
524     def product_id_change(self, cr, uid, ids, product_id, context=None):
525         """ Finds UoM of changed product.
526         @param product_id: Id of changed product.
527         @return: Dictionary of values.
528         """
529         if not product_id:
530             return {'value': {
531                 'product_uom': False,
532                 'bom_id': False,
533                 'routing_id': False
534             }}
535         bom_obj = self.pool.get('mrp.bom')
536         product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
537         bom_id = bom_obj._bom_find(cr, uid, product.id, product.uom_id and product.uom_id.id, [])
538         routing_id = False
539         if bom_id:
540             bom_point = bom_obj.browse(cr, uid, bom_id, context=context)
541             routing_id = bom_point.routing_id.id or False
542         result = {
543             'product_uom': product.uom_id and product.uom_id.id or False,
544             'bom_id': bom_id,
545             'routing_id': routing_id
546         }
547         return {'value': result}
548
549     def bom_id_change(self, cr, uid, ids, bom_id, context=None):
550         """ Finds routing for changed BoM.
551         @param product: Id of product.
552         @return: Dictionary of values.
553         """
554         if not bom_id:
555             return {'value': {
556                 'routing_id': False
557             }}
558         bom_pool = self.pool.get('mrp.bom')
559         bom_point = bom_pool.browse(cr, uid, bom_id, context=context)
560         routing_id = bom_point.routing_id.id or False
561         result = {
562             'routing_id': routing_id
563         }
564         return {'value': result}
565
566     def action_picking_except(self, cr, uid, ids):
567         """ Changes the state to Exception.
568         @return: True
569         """
570         self.write(cr, uid, ids, {'state': 'picking_except'})
571         return True
572
573     def action_compute(self, cr, uid, ids, properties=[]):
574         """ Computes bills of material of a product.
575         @param properties: List containing dictionaries of properties.
576         @return: No. of products.
577         """
578         results = []
579         bom_obj = self.pool.get('mrp.bom')
580         prod_line_obj = self.pool.get('mrp.production.product.line')
581         workcenter_line_obj = self.pool.get('mrp.production.workcenter.line')
582         for production in self.browse(cr, uid, ids):
583             cr.execute('delete from mrp_production_product_line where production_id=%s', (production.id,))
584             cr.execute('delete from mrp_production_workcenter_line where production_id=%s', (production.id,))
585             bom_point = production.bom_id
586             bom_id = production.bom_id.id
587             if not bom_point:
588                 bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties)
589                 if bom_id:
590                     bom_point = bom_obj.browse(cr, uid, bom_id)
591                     routing_id = bom_point.routing_id.id or False
592                     self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id})
593
594             if not bom_id:
595                 raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product"))
596
597             factor = production.product_qty * production.product_uom.factor / bom_point.product_uom.factor
598             res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties)
599             results = res[0]
600             results2 = res[1]
601             for line in results:
602                 line['production_id'] = production.id
603                 prod_line_obj.create(cr, uid, line)
604             for line in results2:
605                 line['production_id'] = production.id
606                 workcenter_line_obj.create(cr, uid, line)
607         return len(results)
608
609     def action_cancel(self, cr, uid, ids, context=None):
610         """ Cancels the production order and related stock moves.
611         @return: True
612         """
613         if context is None:
614             context = {}
615         move_obj = self.pool.get('stock.move')
616         for production in self.browse(cr, uid, ids, context=context):
617             if production.state == 'confirmed' and production.picking_id.state not in ('draft', 'cancel'):
618                 raise osv.except_osv(
619                     _('Could not cancel manufacturing order !'),
620                     _('You must first cancel related internal picking attached to this manufacturing order.'))
621             if production.move_created_ids:
622                 move_obj.action_cancel(cr, uid, [x.id for x in production.move_created_ids])
623             move_obj.action_cancel(cr, uid, [x.id for x in production.move_lines])
624         self.write(cr, uid, ids, {'state': 'cancel'})
625         return True
626
627     def action_ready(self, cr, uid, ids):
628         """ Changes the production state to Ready and location id of stock move.
629         @return: True
630         """
631         move_obj = self.pool.get('stock.move')
632         self.write(cr, uid, ids, {'state': 'ready'})
633
634         for (production_id,name) in self.name_get(cr, uid, ids):
635             production = self.browse(cr, uid, production_id)
636             if production.move_prod_id:
637                 move_obj.write(cr, uid, [production.move_prod_id.id],
638                         {'location_id': production.location_dest_id.id})
639
640             message = _("Manufacturing order '%s' is ready to produce.") % ( name,)
641             self.log(cr, uid, production_id, message)
642         return True
643
644     def action_production_end(self, cr, uid, ids):
645         """ Changes production state to Finish and writes finished date.
646         @return: True
647         """
648         for production in self.browse(cr, uid, ids):
649             self._costs_generate(cr, uid, production)
650         return self.write(cr, uid, ids, {'state': 'done', 'date_finished': time.strftime('%Y-%m-%d %H:%M:%S')})
651
652     def test_production_done(self, cr, uid, ids):
653         """ Tests whether production is done or not.
654         @return: True or False
655         """
656         res = True
657         for production in self.browse(cr, uid, ids):
658             if production.move_lines:
659                res = False
660
661             if production.move_created_ids:
662                res = False
663         return res
664
665     def action_produce(self, cr, uid, production_id, production_qty, production_mode, context=None):
666         """ To produce final product based on production mode (consume/consume&produce).
667         If Production mode is consume, all stock move lines of raw materials will be done/consumed.
668         If Production mode is consume & produce, all stock move lines of raw materials will be done/consumed
669         and stock move lines of final product will be also done/produced.
670         @param production_id: the ID of mrp.production object
671         @param production_qty: specify qty to produce
672         @param production_mode: specify production mode (consume/consume&produce).
673         @return: True
674         """
675         stock_mov_obj = self.pool.get('stock.move')
676         production = self.browse(cr, uid, production_id, context=context)
677
678         final_product_todo = []
679
680         produced_qty = 0
681         if production_mode == 'consume_produce':
682             produced_qty = production_qty
683
684         for produced_product in production.move_created_ids2:
685             if (produced_product.scrapped) or (produced_product.product_id.id<>production.product_id.id):
686                 continue
687             produced_qty += produced_product.product_qty
688
689         if production_mode in ['consume','consume_produce']:
690             consumed_products = {}
691             check = {}
692             scrapped = map(lambda x:x.scrapped,production.move_lines2).count(True)
693
694             for consumed_product in production.move_lines2:
695                 consumed = consumed_product.product_qty
696                 if consumed_product.scrapped:
697                     continue
698                 if not consumed_products.get(consumed_product.product_id.id, False):
699                     consumed_products[consumed_product.product_id.id] = consumed_product.product_qty
700                     check[consumed_product.product_id.id] = 0
701                 for f in production.product_lines:
702                     if f.product_id.id == consumed_product.product_id.id:
703                         if (len(production.move_lines2) - scrapped) > len(production.product_lines):
704                             check[consumed_product.product_id.id] += consumed_product.product_qty
705                             consumed = check[consumed_product.product_id.id]
706                         rest_consumed = produced_qty * f.product_qty / production.product_qty - consumed
707                         consumed_products[consumed_product.product_id.id] = rest_consumed
708
709             for raw_product in production.move_lines:
710                 for f in production.product_lines:
711                     if f.product_id.id == raw_product.product_id.id:
712                         consumed_qty = consumed_products.get(raw_product.product_id.id, 0)
713                         if consumed_qty == 0:
714                             consumed_qty = production_qty * f.product_qty / production.product_qty
715                         if consumed_qty > 0:
716                             stock_mov_obj.action_consume(cr, uid, [raw_product.id], consumed_qty, production.location_src_id.id, context=context)
717
718         if production_mode == 'consume_produce':
719             # To produce remaining qty of final product
720             vals = {'state':'confirmed'}
721             #final_product_todo = [x.id for x in production.move_created_ids]
722             #stock_mov_obj.write(cr, uid, final_product_todo, vals)
723             #stock_mov_obj.action_confirm(cr, uid, final_product_todo, context)
724             produced_products = {}
725             for produced_product in production.move_created_ids2:
726                 if produced_product.scrapped:
727                     continue
728                 if not produced_products.get(produced_product.product_id.id, False):
729                     produced_products[produced_product.product_id.id] = 0
730                 produced_products[produced_product.product_id.id] += produced_product.product_qty
731
732             for produce_product in production.move_created_ids:
733                 produced_qty = produced_products.get(produce_product.product_id.id, 0)
734                 rest_qty = production.product_qty - produced_qty
735                 if rest_qty <= production_qty:
736                    production_qty = rest_qty
737                 if rest_qty > 0 :
738                     stock_mov_obj.action_consume(cr, uid, [produce_product.id], production_qty, context=context)
739
740         for raw_product in production.move_lines2:
741             new_parent_ids = []
742             parent_move_ids = [x.id for x in raw_product.move_history_ids]
743             for final_product in production.move_created_ids2:
744                 if final_product.id not in parent_move_ids:
745                     new_parent_ids.append(final_product.id)
746             for new_parent_id in new_parent_ids:
747                 stock_mov_obj.write(cr, uid, [raw_product.id], {'move_history_ids': [(4,new_parent_id)]})
748
749         wf_service = netsvc.LocalService("workflow")
750         wf_service.trg_validate(uid, 'mrp.production', production_id, 'button_produce_done', cr)
751         return True
752
753     def _costs_generate(self, cr, uid, production):
754         """ Calculates total costs at the end of the production.
755         @param production: Id of production order.
756         @return: Calculated amount.
757         """
758         amount = 0.0
759         analytic_line_obj = self.pool.get('account.analytic.line')
760         for wc_line in production.workcenter_lines:
761             wc = wc_line.workcenter_id
762             if wc.costs_journal_id and wc.costs_general_account_id:
763                 value = wc_line.hour * wc.costs_hour
764                 account = wc.costs_hour_account_id.id
765                 if value and account:
766                     amount += value
767                     analytic_line_obj.create(cr, uid, {
768                         'name': wc_line.name + ' (H)',
769                         'amount': value,
770                         'account_id': account,
771                         'general_account_id': wc.costs_general_account_id.id,
772                         'journal_id': wc.costs_journal_id.id,
773                         'ref': wc.code,
774                         'product_id': wc.product_id.id,
775                         'unit_amount': wc_line.hour,
776                         'product_uom_id': wc.product_id.uom_id.id
777                     } )
778             if wc.costs_journal_id and wc.costs_general_account_id:
779                 value = wc_line.cycle * wc.costs_cycle
780                 account = wc.costs_cycle_account_id.id
781                 if value and account:
782                     amount += value
783                     analytic_line_obj.create(cr, uid, {
784                         'name': wc_line.name+' (C)',
785                         'amount': value,
786                         'account_id': account,
787                         'general_account_id': wc.costs_general_account_id.id,
788                         'journal_id': wc.costs_journal_id.id,
789                         'ref': wc.code,
790                         'product_id': wc.product_id.id,
791                         'unit_amount': wc_line.cycle,
792                         'product_uom_id': wc.product_id.uom_id.id
793                     } )
794         return amount
795
796     def action_in_production(self, cr, uid, ids):
797         """ Changes state to In Production and writes starting date.
798         @return: True
799         """
800         self.write(cr, uid, ids, {'state': 'in_production', 'date_start': time.strftime('%Y-%m-%d %H:%M:%S')})
801         return True
802
803     def test_if_product(self, cr, uid, ids):
804         """
805         @return: True or False
806         """
807         res = True
808         for production in self.browse(cr, uid, ids):
809             if not production.product_lines:
810                 if not self.action_compute(cr, uid, [production.id]):
811                     res = False
812         return res
813
814     def _get_auto_picking(self, cr, uid, production):
815         return True
816
817     def action_confirm(self, cr, uid, ids):
818         """ Confirms production order.
819         @return: Newly generated picking Id.
820         """
821         picking_id = False
822         proc_ids = []
823         seq_obj = self.pool.get('ir.sequence')
824         pick_obj = self.pool.get('stock.picking')
825         move_obj = self.pool.get('stock.move')
826         proc_obj = self.pool.get('procurement.order')
827         wf_service = netsvc.LocalService("workflow")
828         for production in self.browse(cr, uid, ids):
829             if not production.product_lines:
830                 self.action_compute(cr, uid, [production.id])
831                 production = self.browse(cr, uid, [production.id])[0]
832             routing_loc = None
833             pick_type = 'internal'
834             address_id = False
835             if production.bom_id.routing_id and production.bom_id.routing_id.location_id:
836                 routing_loc = production.bom_id.routing_id.location_id
837                 if routing_loc.usage <> 'internal':
838                     pick_type = 'out'
839                 address_id = routing_loc.address_id and routing_loc.address_id.id or False
840                 routing_loc = routing_loc.id
841             pick_name = seq_obj.get(cr, uid, 'stock.picking.' + pick_type)
842             picking_id = pick_obj.create(cr, uid, {
843                 'name': pick_name,
844                 'origin': (production.origin or '').split(':')[0] + ':' + production.name,
845                 'type': pick_type,
846                 'move_type': 'one',
847                 'state': 'auto',
848                 'address_id': address_id,
849                 'auto_picking': self._get_auto_picking(cr, uid, production),
850                 'company_id': production.company_id.id,
851             })
852
853             source = production.product_id.product_tmpl_id.property_stock_production.id
854             data = {
855                 'name':'PROD:' + production.name,
856                 'date': production.date_planned,
857                 'product_id': production.product_id.id,
858                 'product_qty': production.product_qty,
859                 'product_uom': production.product_uom.id,
860                 'product_uos_qty': production.product_uos and production.product_uos_qty or False,
861                 'product_uos': production.product_uos and production.product_uos.id or False,
862                 'location_id': source,
863                 'location_dest_id': production.location_dest_id.id,
864                 'move_dest_id': production.move_prod_id.id,
865                 'state': 'waiting',
866                 'company_id': production.company_id.id,
867             }
868             res_final_id = move_obj.create(cr, uid, data)
869
870             self.write(cr, uid, [production.id], {'move_created_ids': [(6, 0, [res_final_id])]})
871             moves = []
872             for line in production.product_lines:
873                 move_id = False
874                 newdate = production.date_planned
875                 if line.product_id.type in ('product', 'consu'):
876                     res_dest_id = move_obj.create(cr, uid, {
877                         'name':'PROD:' + production.name,
878                         'date': production.date_planned,
879                         'product_id': line.product_id.id,
880                         'product_qty': line.product_qty,
881                         'product_uom': line.product_uom.id,
882                         'product_uos_qty': line.product_uos and line.product_uos_qty or False,
883                         'product_uos': line.product_uos and line.product_uos.id or False,
884                         'location_id': routing_loc or production.location_src_id.id,
885                         'location_dest_id': source,
886                         'move_dest_id': res_final_id,
887                         'state': 'waiting',
888                         'company_id': production.company_id.id,
889                     })
890                     moves.append(res_dest_id)
891                     move_id = move_obj.create(cr, uid, {
892                         'name':'PROD:' + production.name,
893                         'picking_id':picking_id,
894                         'product_id': line.product_id.id,
895                         'product_qty': line.product_qty,
896                         'product_uom': line.product_uom.id,
897                         'product_uos_qty': line.product_uos and line.product_uos_qty or False,
898                         'product_uos': line.product_uos and line.product_uos.id or False,
899                         'date': newdate,
900                         'move_dest_id': res_dest_id,
901                         'location_id': production.location_src_id.id,
902                         'location_dest_id': routing_loc or production.location_src_id.id,
903                         'state': 'waiting',
904                         'company_id': production.company_id.id,
905                     })
906                 proc_id = proc_obj.create(cr, uid, {
907                     'name': (production.origin or '').split(':')[0] + ':' + production.name,
908                     'origin': (production.origin or '').split(':')[0] + ':' + production.name,
909                     'date_planned': newdate,
910                     'product_id': line.product_id.id,
911                     'product_qty': line.product_qty,
912                     'product_uom': line.product_uom.id,
913                     'product_uos_qty': line.product_uos and line.product_qty or False,
914                     'product_uos': line.product_uos and line.product_uos.id or False,
915                     'location_id': production.location_src_id.id,
916                     'procure_method': line.product_id.procure_method,
917                     'move_id': move_id,
918                     'company_id': production.company_id.id,
919                 })
920                 wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
921                 proc_ids.append(proc_id)
922             wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
923             self.write(cr, uid, [production.id], {'picking_id': picking_id, 'move_lines': [(6,0,moves)], 'state':'confirmed'})
924             message = _("Manufacturing order '%s' is scheduled for the %s.") % (
925                 production.name,
926                 datetime.strptime(production.date_planned,'%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y'),
927             )
928             self.log(cr, uid, production.id, message)
929         return picking_id
930
931     def force_production(self, cr, uid, ids, *args):
932         """ Assigns products.
933         @param *args: Arguments
934         @return: True
935         """
936         pick_obj = self.pool.get('stock.picking')
937         pick_obj.force_assign(cr, uid, [prod.picking_id.id for prod in self.browse(cr, uid, ids)])
938         return True
939
940 mrp_production()
941
942 class mrp_production_workcenter_line(osv.osv):
943     _name = 'mrp.production.workcenter.line'
944     _description = 'Work Order'
945     _order = 'sequence'
946
947     _columns = {
948         'name': fields.char('Work Order', size=64, required=True),
949         'workcenter_id': fields.many2one('mrp.workcenter', 'Work Center', required=True),
950         'cycle': fields.float('Nbr of cycles', digits=(16,2)),
951         'hour': fields.float('Nbr of hours', digits=(16,2)),
952         'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when displaying a list of work orders."),
953         'production_id': fields.many2one('mrp.production', 'Production Order', select=True, ondelete='cascade', required=True),
954     }
955     _defaults = {
956         'sequence': lambda *a: 1,
957         'hour': lambda *a: 0,
958         'cycle': lambda *a: 0,
959     }
960 mrp_production_workcenter_line()
961
962 class mrp_production_product_line(osv.osv):
963     _name = 'mrp.production.product.line'
964     _description = 'Production Scheduled Product'
965     _columns = {
966         'name': fields.char('Name', size=64, required=True),
967         'product_id': fields.many2one('product.product', 'Product', required=True),
968         'product_qty': fields.float('Product Qty', required=True),
969         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
970         'product_uos_qty': fields.float('Product UOS Qty'),
971         'product_uos': fields.many2one('product.uom', 'Product UOS'),
972         'production_id': fields.many2one('mrp.production', 'Production Order', select=True),
973     }
974 mrp_production_product_line()
975
976 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: