1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 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 operator import attrgetter
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp import netsvc
28 import openerp.addons.decimal_precision as dp
31 # ------------------------------------------------------------------
33 # Produce, Buy or Find products and place a move
34 # then wizard for picking lists & move
37 class mrp_property_group(osv.osv):
39 Group of mrp properties.
41 _name = 'mrp.property.group'
42 _description = 'Property Group'
44 'name': fields.char('Property Group', size=64, required=True),
45 'description': fields.text('Description'),
48 class mrp_property(osv.osv):
52 _name = 'mrp.property'
53 _description = 'Property'
55 'name': fields.char('Name', size=64, required=True),
56 'composition': fields.selection([('min','min'),('max','max'),('plus','plus')], 'Properties composition', required=True, help="Not used in computations, for information purpose only."),
57 'group_id': fields.many2one('mrp.property.group', 'Property Group', required=True),
58 'description': fields.text('Description'),
61 'composition': lambda *a: 'min',
64 class StockMove(osv.osv):
65 _inherit = 'stock.move'
67 'procurements': fields.one2many('procurement.order', 'move_id', 'Procurements'),
68 'group_id':fields.many2one('procurement.group', 'Move Group'),
71 def copy_data(self, cr, uid, id, default=None, context=None):
74 default['procurements'] = []
75 return super(StockMove, self).copy_data(cr, uid, id, default, context=context)
78 class procurement_group(osv.osv):
80 The procurement requirement class is used to group products together
81 when computing procurements. (tasks, physical products, ...)
83 The goal is that when you have one sale order of several products
84 and the products are pulled from the same or several location(s), to keep
85 having the moves grouped into pickings that represent the sale order.
87 Used in: sales order (to group delivery order lines like the so), pull/push
88 rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
89 all the similar products together).
91 Grouping is made only if the source and the destination is the same.
92 Suppose you have 4 lines on a picking from Output where 2 lines will need
93 to come from Input (crossdock) and 2 lines coming from Stock -> Output As
94 the four procurement orders will have the same group ids from the SO, the
95 move from input will have a stock.picking with 2 grouped lines and the move
96 from stock will have 2 grouped lines also.
98 The name is usually the name of the original document (sale order) or a
99 sequence computed if created manually.
101 _name = 'procurement.group'
102 _description = 'Procurement Requisition'
105 'name': fields.char('Reference'),
108 'name': lambda self,cr,uid,c: self.pool.get('ir.sequence').get(cr,uid,'procurement.group') or ''
113 class procurement_order(osv.osv):
117 _name = "procurement.order"
118 _description = "Procurement"
119 _order = 'priority desc,date_planned'
120 _inherit = ['mail.thread']
123 'name': fields.text('Description', required=True),
124 'origin': fields.char('Source Document', size=64,
125 help="Reference of the document that created this Procurement.\n"
126 "This is automatically completed by OpenERP."),
127 'priority': fields.selection([('0','Not urgent'),('1','Normal'),('2','Urgent'),('3','Very Urgent')], 'Priority', required=True, select=True),
128 'date_planned': fields.datetime('Scheduled date', required=True, select=True),
129 'date_close': fields.datetime('Date Closed'),
130 'product_id': fields.many2one('product.product', 'Product', required=True, states={'draft':[('readonly',False)]}, readonly=True),
131 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True, states={'draft':[('readonly',False)]}, readonly=True),
132 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True, states={'draft':[('readonly',False)]}, readonly=True),
133 'product_uos_qty': fields.float('UoS Quantity', states={'draft':[('readonly',False)]}, readonly=True),
134 'product_uos': fields.many2one('product.uom', 'Product UoS', states={'draft':[('readonly',False)]}, readonly=True),
135 'close_move': fields.boolean('Close Move at end'),
136 'move_id': fields.many2one('stock.move', 'Reservation', ondelete='set null'),
137 'location_id': fields.many2one('stock.location', 'Location', required=True, states={'draft':[('readonly',False)]}, readonly=True),
138 'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procurement Method', states={'draft':[('readonly',False)], 'confirmed':[('readonly',False)]},
139 readonly=True, required=True, help="If you encode manually a Procurement, you probably want to use" \
140 " a make to order method."),
141 'note': fields.text('Note'),
142 'message': fields.text('Latest error', help="Exception occurred while computing procurement orders."),
143 'state': fields.selection([
145 ('cancel','Cancelled'),
146 ('confirmed','Confirmed'),
147 ('exception','Exception'),
148 ('running','Running'),
151 ('waiting','Waiting')], 'Status', required=True, track_visibility='onchange',
152 help='When a procurement is created the status is set to \'Draft\'.\n If the procurement is confirmed, the status is set to \'Confirmed\'.\
153 \nAfter confirming the status is set to \'Running\'.\n If any exception arises in the order then the status is set to \'Exception\'.\n Once the exception is removed the status becomes \'Ready\'.\n It is in \'Waiting\'. status when the procurement is waiting for another one to finish.'),
154 'note': fields.text('Note'),
155 'company_id': fields.many2one('res.company','Company',required=True),
156 'group_id':fields.many2one('procurement.group', 'Procurement Requisition'),
161 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
163 'procure_method': 'make_to_order',
164 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c)
167 def unlink(self, cr, uid, ids, context=None):
168 procurements = self.read(cr, uid, ids, ['state'], context=context)
170 for s in procurements:
171 if s['state'] in ['draft','cancel']:
172 unlink_ids.append(s['id'])
174 raise osv.except_osv(_('Invalid Action!'),
175 _('Cannot delete Procurement Order(s) which are in %s state.') % \
177 return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
179 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
180 """ Finds UoM and UoS of changed product.
181 @param product_id: Changed id of product.
182 @return: Dictionary of values.
185 w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
187 'product_uom': w.uom_id.id,
188 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
193 def is_product(self, cr, uid, ids, context=None):
194 """ Checks product type to decide which transition of the workflow to follow.
195 @return: True if all product ids received in argument are of type 'product' or 'consummable'. False if any is of type 'service'
197 return all(proc.product_id.type in ('product', 'consu') for proc in self.browse(cr, uid, ids, context=context))
199 def check_move_cancel(self, cr, uid, ids, context=None):
200 """ Checks if move is cancelled or not.
201 @return: True or False.
203 return all(procurement.move_id.state == 'cancel' for procurement in self.browse(cr, uid, ids, context=context))
205 #This Function is create to avoid a server side Error Like 'ERROR:tests.mrp:name 'check_move' is not defined'
206 def check_move(self, cr, uid, ids, context=None):
209 def check_move_done(self, cr, uid, ids, context=None):
210 """ Checks if move is done or not.
211 @return: True or False.
213 return all(proc.product_id.type == 'service' or (proc.move_id and proc.move_id.state == 'done') \
214 for proc in self.browse(cr, uid, ids, context=context))
217 # This method may be overrided by objects that override procurement.order
218 # for computing their own purpose
220 def _quantity_compute_get(self, cr, uid, proc, context=None):
221 """ Finds sold quantity of product.
222 @param proc: Current procurement.
223 @return: Quantity or False.
225 if proc.product_id.type == 'product' and proc.move_id:
226 if proc.move_id.product_uos:
227 return proc.move_id.product_uos_qty
230 def _uom_compute_get(self, cr, uid, proc, context=None):
231 """ Finds UoS if product is Stockable Product.
232 @param proc: Current procurement.
233 @return: UoS or False.
235 if proc.product_id.type == 'product' and proc.move_id:
236 if proc.move_id.product_uos:
237 return proc.move_id.product_uos.id
241 # Return the quantity of product shipped/produced/served, which may be
242 # different from the planned quantity
244 def quantity_get(self, cr, uid, id, context=None):
245 """ Finds quantity of product used in procurement.
246 @return: Quantity of product.
248 proc = self.browse(cr, uid, id, context=context)
249 result = self._quantity_compute_get(cr, uid, proc, context=context)
251 result = proc.product_qty
254 def uom_get(self, cr, uid, id, context=None):
255 """ Finds UoM of product used in procurement.
256 @return: UoM of product.
258 proc = self.browse(cr, uid, id, context=context)
259 result = self._uom_compute_get(cr, uid, proc, context=context)
261 result = proc.product_uom.id
264 def check_waiting(self, cr, uid, ids, context=None):
265 """ Checks state of move.
266 @return: True or False
268 for procurement in self.browse(cr, uid, ids, context=context):
269 if procurement.move_id and procurement.move_id.state == 'auto':
273 def check_produce_service(self, cr, uid, procurement, context=None):
274 """ Depicts the capacity of the procurement workflow to deal with production of services.
275 By default, it's False. Overwritten by project_mrp module.
279 def check_produce_product(self, cr, uid, procurement, context=None):
280 """ Depicts the capacity of the procurement workflow to deal with production of products.
281 By default, it's False. Overwritten by mrp module.
285 def check_make_to_stock(self, cr, uid, ids, context=None):
286 """ Checks product type.
287 @return: True or False
290 for procurement in self.browse(cr, uid, ids, context=context):
291 if procurement.product_id.type == 'service':
292 ok = ok and self._check_make_to_stock_service(cr, uid, procurement, context)
294 ok = ok and self._check_make_to_stock_product(cr, uid, procurement, context)
297 def check_produce(self, cr, uid, ids, context=None):
298 """ Checks product type.
299 @return: True or False
301 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
302 for procurement in self.browse(cr, uid, ids, context=context):
303 product = procurement.product_id
304 #TOFIX: if product type is 'service' but supply_method is 'buy'.
305 if product.supply_method <> 'produce':
307 if product.type=='service':
308 res = self.check_produce_service(cr, uid, procurement, context)
310 res = self.check_produce_product(cr, uid, procurement, context)
315 def check_buy(self, cr, uid, ids):
316 """ Depicts the capacity of the procurement workflow to manage the supply_method == 'buy'.
317 By default, it's False. Overwritten by purchase module.
321 def check_conditions_confirm2wait(self, cr, uid, ids):
322 """ condition on the transition to go from 'confirm' activity to 'confirm_wait' activity """
323 return not self.test_cancel(cr, uid, ids)
325 def test_cancel(self, cr, uid, ids):
326 """ Tests whether state of move is cancelled or not.
327 @return: True or False
329 for record in self.browse(cr, uid, ids):
330 if record.move_id and record.move_id.state == 'cancel':
334 #Initialize get_phantom_bom_id method as it is raising an error from yml of mrp_jit
335 #when one install first mrp and after that, mrp_jit. get_phantom_bom_id defined in mrp module
336 #which is not dependent for mrp_jit.
337 def get_phantom_bom_id(self, cr, uid, ids, context=None):
340 def action_confirm(self, cr, uid, ids, context=None):
341 """ Confirms procurement and writes exception message if any.
344 move_obj = self.pool.get('stock.move')
345 for procurement in self.browse(cr, uid, ids, context=context):
346 if procurement.product_qty <= 0.00:
347 raise osv.except_osv(_('Data Insufficient!'),
348 _('Please check the quantity in procurement order(s) for the product "%s", it should not be 0 or less!' % procurement.product_id.name))
349 if procurement.product_id.type in ('product', 'consu'):
350 if not procurement.move_id:
351 source = procurement.location_id.id
352 if procurement.procure_method == 'make_to_order':
353 source = procurement.product_id.property_stock_procurement.id
354 id = move_obj.create(cr, uid, {
355 'name': procurement.name,
356 'location_id': source,
357 'location_dest_id': procurement.location_id.id,
358 'product_id': procurement.product_id.id,
359 'product_qty': procurement.product_qty,
360 'product_uom': procurement.product_uom.id,
361 'date_expected': procurement.date_planned,
363 'company_id': procurement.company_id.id,
364 'auto_validate': True,
366 move_obj.action_confirm(cr, uid, [id], context=context)
367 self.write(cr, uid, [procurement.id], {'move_id': id, 'close_move': 1})
368 self.write(cr, uid, ids, {'state': 'confirmed', 'message': ''})
371 def action_move_assigned(self, cr, uid, ids, context=None):
372 """ Changes procurement state to Running and writes message.
375 message = _('Products reserved from stock.')
376 self.write(cr, uid, ids, {'state': 'running',
377 'message': message}, context=context)
378 self.message_post(cr, uid, ids, body=message, context=context)
381 def _check_make_to_stock_service(self, cr, uid, procurement, context=None):
383 This method may be overrided by objects that override procurement.order
384 for computing their own purpose
388 def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
389 """ Checks procurement move state.
390 @param procurement: Current procurement.
391 @return: True or move id.
394 if procurement.move_id:
396 id = procurement.move_id.id
397 if not (procurement.move_id.state in ('done','assigned','cancel')):
398 ok = ok and self.pool.get('stock.move').action_assign(cr, uid, [id])
399 order_point_id = self.pool.get('stock.warehouse.orderpoint').search(cr, uid, [('product_id', '=', procurement.product_id.id)], context=context)
400 if not order_point_id and not ok:
401 message = _("Not enough stock and no minimum orderpoint rule defined.")
403 message = _("Not enough stock.")
406 message = _("Procurement '%s' is in exception: ") % (procurement.name) + message
407 #temporary context passed in write to prevent an infinite loop
408 ctx_wkf = dict(context or {})
409 ctx_wkf['workflow.trg_write.%s' % self._name] = False
410 self.write(cr, uid, [procurement.id], {'message': message},context=ctx_wkf)
411 self.message_post(cr, uid, [procurement.id], body=message, context=context)
414 def step_workflow(self, cr, uid, ids, context=None):
415 """ Don't trigger workflow for the element specified in trigger """
416 wkf_op_key = 'workflow.trg_write.%s' % self._name
417 if context and not context.get(wkf_op_key, True):
418 # make sure we don't have a trigger loop while processing triggers
420 return super(procurement_order, self).step_workflow(cr, uid, ids, context=context)
422 def action_produce_assign_service(self, cr, uid, ids, context=None):
423 """ Changes procurement state to Running.
426 for procurement in self.browse(cr, uid, ids, context=context):
427 self.write(cr, uid, [procurement.id], {'state': 'running'})
430 def action_produce_assign_product(self, cr, uid, ids, context=None):
431 """ This is action which call from workflow to assign production order to procurements
437 def action_po_assign(self, cr, uid, ids, context=None):
438 """ This is action which call from workflow to assign purchase order to procurements
443 # XXX action_cancel() should accept a context argument
444 def action_cancel(self, cr, uid, ids):
445 """Cancel Procurements and either cancel or assign the related Stock Moves, depending on the procurement configuration.
451 move_obj = self.pool.get('stock.move')
452 for proc in self.browse(cr, uid, ids):
453 if proc.close_move and proc.move_id:
454 if proc.move_id.state not in ('done', 'cancel'):
455 to_cancel.append(proc.move_id.id)
457 if proc.move_id and proc.move_id.state == 'waiting':
458 to_assign.append(proc.move_id.id)
460 move_obj.action_cancel(cr, uid, to_cancel)
462 move_obj.write(cr, uid, to_assign, {'state': 'assigned'})
463 self.write(cr, uid, ids, {'state': 'cancel'})
464 wf_service = netsvc.LocalService("workflow")
466 wf_service.trg_trigger(uid, 'procurement.order', id, cr)
469 def action_check_finished(self, cr, uid, ids):
470 return self.check_move_done(cr, uid, ids)
472 def action_check(self, cr, uid, ids):
473 """ Checks procurement move state whether assigned or done.
477 for procurement in self.browse(cr, uid, ids):
478 if procurement.move_id and procurement.move_id.state == 'assigned' or procurement.move_id.state == 'done':
479 self.action_done(cr, uid, [procurement.id])
483 def action_ready(self, cr, uid, ids):
484 """ Changes procurement state to Ready.
487 res = self.write(cr, uid, ids, {'state': 'ready'})
490 def action_done(self, cr, uid, ids):
491 """ Changes procurement state to Done and writes Closed date.
494 move_obj = self.pool.get('stock.move')
495 for procurement in self.browse(cr, uid, ids):
496 if procurement.move_id:
497 if procurement.close_move and (procurement.move_id.state <> 'done'):
498 move_obj.action_done(cr, uid, [procurement.move_id.id])
499 res = self.write(cr, uid, ids, {'state': 'done', 'date_close': time.strftime('%Y-%m-%d')})
500 wf_service = netsvc.LocalService("workflow")
502 wf_service.trg_trigger(uid, 'procurement.order', id, cr)
505 class StockPicking(osv.osv):
506 _inherit = 'stock.picking'
507 def test_finished(self, cr, uid, ids):
508 res = super(StockPicking, self).test_finished(cr, uid, ids)
509 for picking in self.browse(cr, uid, ids):
510 for move in picking.move_lines:
511 if move.state == 'done' and move.procurements:
512 self.pool.get('procurement.order').signal_button_check(cr, uid, map(attrgetter('id'), move.procurements))
515 class stock_warehouse_orderpoint(osv.osv):
517 Defines Minimum stock rules.
519 _name = "stock.warehouse.orderpoint"
520 _description = "Minimum Inventory Rule"
522 def _get_draft_procurements(self, cr, uid, ids, field_name, arg, context=None):
526 procurement_obj = self.pool.get('procurement.order')
527 for orderpoint in self.browse(cr, uid, ids, context=context):
528 procurement_ids = procurement_obj.search(cr, uid , [('state', '=', 'draft'), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)])
529 result[orderpoint.id] = procurement_ids
532 def _check_product_uom(self, cr, uid, ids, context=None):
534 Check if the UoM has the same category as the product standard UoM
539 for rule in self.browse(cr, uid, ids, context=context):
540 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
546 'name': fields.char('Name', size=32, required=True),
547 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
548 'logic': fields.selection([('max','Order to Max'),('price','Best price (not yet active!)')], 'Reordering Mode', required=True),
549 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
550 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
551 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type','!=','service')]),
552 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
553 'product_min_qty': fields.float('Minimum Quantity', required=True,
554 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
555 "a procurement to bring the forecasted quantity to the Max Quantity."),
556 'product_max_qty': fields.float('Maximum Quantity', required=True,
557 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
558 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
559 'qty_multiple': fields.integer('Qty Multiple', required=True,
560 help="The procurement quantity will be rounded up to this multiple."),
561 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
562 'company_id': fields.many2one('res.company','Company',required=True),
563 'procurement_draft_ids': fields.function(_get_draft_procurements, type='many2many', relation="procurement.order", \
564 string="Related Procurement Orders",help="Draft procurement of the product and location of that orderpoint"),
567 'active': lambda *a: 1,
568 'logic': lambda *a: 'max',
569 'qty_multiple': lambda *a: 1,
570 'name': lambda x,y,z,c: x.pool.get('ir.sequence').get(y,z,'stock.orderpoint') or '',
571 'product_uom': lambda sel, cr, uid, context: context.get('product_uom', False),
572 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=c)
575 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
578 (_check_product_uom, 'You have to select a product unit of measure in the same category than the default unit of measure of the product', ['product_id', 'product_uom']),
581 def default_get(self, cr, uid, fields, context=None):
582 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
583 # default 'warehouse_id' and 'location_id'
584 if 'warehouse_id' not in res:
585 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
586 res['warehouse_id'] = warehouse.id
587 if 'location_id' not in res:
588 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
589 res['location_id'] = warehouse.lot_stock_id.id
592 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
593 """ Finds location id for changed warehouse.
594 @param warehouse_id: Changed id of warehouse.
595 @return: Dictionary of values.
598 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
599 v = {'location_id': w.lot_stock_id.id}
603 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
604 """ Finds UoM for changed product.
605 @param product_id: Changed id of product.
606 @return: Dictionary of values.
609 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
610 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
611 v = {'product_uom': prod.uom_id.id}
612 return {'value': v, 'domain': d}
613 return {'domain': {'product_uom': []}}
615 def copy(self, cr, uid, id, default=None, context=None):
619 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
621 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
623 class product_template(osv.osv):
624 _inherit="product.template"
627 'type': fields.selection([('product','Stockable Product'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Consumable: Will not imply stock management for this product. \nStockable product: Will imply stock management for this product."),
628 'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procurement Method', required=True, help="Make to Stock: When needed, the product is taken from the stock or we wait for replenishment. \nMake to Order: When needed, the product is purchased or produced."),
629 'supply_method': fields.selection([('produce','Manufacture'),('buy','Buy')], 'Supply Method', required=True, help="Manufacture: When procuring the product, a manufacturing order or a task will be generated, depending on the product type. \nBuy: When procuring the product, a purchase order will be generated."),
632 'procure_method': 'make_to_stock',
633 'supply_method': 'buy',
636 class product_product(osv.osv):
637 _inherit="product.product"
639 'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
644 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: