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 openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 from openerp import netsvc
26 import openerp.addons.decimal_precision as dp
29 # ------------------------------------------------------------------
31 # Produce, Buy or Find products and place a move
32 # then wizard for picking lists & move
35 class mrp_property_group(osv.osv):
37 Group of mrp properties.
39 _name = 'mrp.property.group'
40 _description = 'Property Group'
42 'name': fields.char('Property Group', size=64, required=True),
43 'description': fields.text('Description'),
47 class mrp_property(osv.osv):
51 _name = 'mrp.property'
52 _description = 'Property'
54 'name': fields.char('Name', size=64, required=True),
55 'composition': fields.selection([('min','min'),('max','max'),('plus','plus')], 'Properties composition', required=True, help="Not used in computations, for information purpose only."),
56 'group_id': fields.many2one('mrp.property.group', 'Property Group', required=True),
57 'description': fields.text('Description'),
60 'composition': lambda *a: 'min',
64 class StockMove(osv.osv):
65 _inherit = 'stock.move'
67 'procurements': fields.one2many('procurement.order', 'move_id', 'Procurements'),
70 def copy_data(self, cr, uid, id, default=None, context=None):
73 default['procurements'] = []
74 return super(StockMove, self).copy_data(cr, uid, id, default, context=context)
78 class procurement_order(osv.osv):
82 _name = "procurement.order"
83 _description = "Procurement"
84 _order = 'priority desc,date_planned'
85 _inherit = ['mail.thread']
88 'name': fields.text('Description', required=True),
89 'origin': fields.char('Source Document', size=64,
90 help="Reference of the document that created this Procurement.\n"
91 "This is automatically completed by OpenERP."),
92 'priority': fields.selection([('0','Not urgent'),('1','Normal'),('2','Urgent'),('3','Very Urgent')], 'Priority', required=True, select=True),
93 'date_planned': fields.datetime('Scheduled date', required=True, select=True),
94 'date_close': fields.datetime('Date Closed'),
95 'product_id': fields.many2one('product.product', 'Product', required=True, states={'draft':[('readonly',False)]}, readonly=True),
96 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True, states={'draft':[('readonly',False)]}, readonly=True),
97 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True, states={'draft':[('readonly',False)]}, readonly=True),
98 'product_uos_qty': fields.float('UoS Quantity', states={'draft':[('readonly',False)]}, readonly=True),
99 'product_uos': fields.many2one('product.uom', 'Product UoS', states={'draft':[('readonly',False)]}, readonly=True),
100 'move_id': fields.many2one('stock.move', 'Reservation', ondelete='set null'),
101 'close_move': fields.boolean('Close Move at end'),
102 'location_id': fields.many2one('stock.location', 'Location', required=True, states={'draft':[('readonly',False)]}, readonly=True),
103 '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)]},
104 readonly=True, required=True, help="If you encode manually a Procurement, you probably want to use" \
105 " a make to order method."),
106 'note': fields.text('Note'),
107 'message': fields.char('Latest error', size=124, help="Exception occurred while computing procurement orders."),
108 'state': fields.selection([
110 ('cancel','Cancelled'),
111 ('confirmed','Confirmed'),
112 ('exception','Exception'),
113 ('running','Running'),
116 ('waiting','Waiting')], 'Status', required=True, track_visibility='onchange',
117 help='When a procurement is created the status is set to \'Draft\'.\n If the procurement is confirmed, the status is set to \'Confirmed\'.\
118 \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.'),
119 'note': fields.text('Note'),
120 'company_id': fields.many2one('res.company','Company',required=True),
125 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
127 'procure_method': 'make_to_order',
128 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c)
131 def unlink(self, cr, uid, ids, context=None):
132 procurements = self.read(cr, uid, ids, ['state'], context=context)
134 for s in procurements:
135 if s['state'] in ['draft','cancel']:
136 unlink_ids.append(s['id'])
138 raise osv.except_osv(_('Invalid Action!'),
139 _('Cannot delete Procurement Order(s) which are in %s state.') % \
141 return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
143 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
144 """ Finds UoM and UoS of changed product.
145 @param product_id: Changed id of product.
146 @return: Dictionary of values.
149 w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
151 'product_uom': w.uom_id.id,
152 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
157 def is_product(self, cr, uid, ids, context=None):
158 """ Checks product type to decide which transition of the workflow to follow.
159 @return: True if all product ids received in argument are of type 'product' or 'consummable'. False if any is of type 'service'
161 return all(proc.product_id.type in ('product', 'consu') for proc in self.browse(cr, uid, ids, context=context))
163 def check_move_cancel(self, cr, uid, ids, context=None):
164 """ Checks if move is cancelled or not.
165 @return: True or False.
167 return all(procurement.move_id.state == 'cancel' for procurement in self.browse(cr, uid, ids, context=context))
169 #This Function is create to avoid a server side Error Like 'ERROR:tests.mrp:name 'check_move' is not defined'
170 def check_move(self, cr, uid, ids, context=None):
173 def check_move_done(self, cr, uid, ids, context=None):
174 """ Checks if move is done or not.
175 @return: True or False.
177 return all(proc.product_id.type == 'service' or (proc.move_id and proc.move_id.state == 'done') \
178 for proc in self.browse(cr, uid, ids, context=context))
181 # This method may be overrided by objects that override procurement.order
182 # for computing their own purpose
184 def _quantity_compute_get(self, cr, uid, proc, context=None):
185 """ Finds sold quantity of product.
186 @param proc: Current procurement.
187 @return: Quantity or False.
189 if proc.product_id.type == 'product' and proc.move_id:
190 if proc.move_id.product_uos:
191 return proc.move_id.product_uos_qty
194 def _uom_compute_get(self, cr, uid, proc, context=None):
195 """ Finds UoS if product is Stockable Product.
196 @param proc: Current procurement.
197 @return: UoS or False.
199 if proc.product_id.type == 'product' and proc.move_id:
200 if proc.move_id.product_uos:
201 return proc.move_id.product_uos.id
205 # Return the quantity of product shipped/produced/served, which may be
206 # different from the planned quantity
208 def quantity_get(self, cr, uid, id, context=None):
209 """ Finds quantity of product used in procurement.
210 @return: Quantity of product.
212 proc = self.browse(cr, uid, id, context=context)
213 result = self._quantity_compute_get(cr, uid, proc, context=context)
215 result = proc.product_qty
218 def uom_get(self, cr, uid, id, context=None):
219 """ Finds UoM of product used in procurement.
220 @return: UoM of product.
222 proc = self.browse(cr, uid, id, context=context)
223 result = self._uom_compute_get(cr, uid, proc, context=context)
225 result = proc.product_uom.id
228 def check_waiting(self, cr, uid, ids, context=None):
229 """ Checks state of move.
230 @return: True or False
232 for procurement in self.browse(cr, uid, ids, context=context):
233 if procurement.move_id and procurement.move_id.state == 'auto':
237 def check_produce_service(self, cr, uid, procurement, context=None):
238 """ Depicts the capacity of the procurement workflow to deal with production of services.
239 By default, it's False. Overwritten by project_mrp module.
243 def check_produce_product(self, cr, uid, procurement, context=None):
244 """ Depicts the capacity of the procurement workflow to deal with production of products.
245 By default, it's False. Overwritten by mrp module.
249 def check_make_to_stock(self, cr, uid, ids, context=None):
250 """ Checks product type.
251 @return: True or False
254 for procurement in self.browse(cr, uid, ids, context=context):
255 if procurement.product_id.type == 'service':
256 ok = ok and self._check_make_to_stock_service(cr, uid, procurement, context)
258 ok = ok and self._check_make_to_stock_product(cr, uid, procurement, context)
261 def check_produce(self, cr, uid, ids, context=None):
262 """ Checks product type.
263 @return: True or False
265 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
266 for procurement in self.browse(cr, uid, ids, context=context):
267 product = procurement.product_id
268 #TOFIX: if product type is 'service' but supply_method is 'buy'.
269 if product.supply_method <> 'produce':
271 if product.type=='service':
272 res = self.check_produce_service(cr, uid, procurement, context)
274 res = self.check_produce_product(cr, uid, procurement, context)
279 def check_buy(self, cr, uid, ids):
280 """ Depicts the capacity of the procurement workflow to manage the supply_method == 'buy'.
281 By default, it's False. Overwritten by purchase module.
285 def check_conditions_confirm2wait(self, cr, uid, ids):
286 """ condition on the transition to go from 'confirm' activity to 'confirm_wait' activity """
287 return not self.test_cancel(cr, uid, ids)
289 def test_cancel(self, cr, uid, ids):
290 """ Tests whether state of move is cancelled or not.
291 @return: True or False
293 for record in self.browse(cr, uid, ids):
294 if record.move_id and record.move_id.state == 'cancel':
298 #Initialize get_phantom_bom_id method as it is raising an error from yml of mrp_jit
299 #when one install first mrp and after that, mrp_jit. get_phantom_bom_id defined in mrp module
300 #which is not dependent for mrp_jit.
301 def get_phantom_bom_id(self, cr, uid, ids, context=None):
304 def action_confirm(self, cr, uid, ids, context=None):
305 """ Confirms procurement and writes exception message if any.
308 move_obj = self.pool.get('stock.move')
309 for procurement in self.browse(cr, uid, ids, context=context):
310 if procurement.product_qty <= 0.00:
311 raise osv.except_osv(_('Data Insufficient!'),
312 _('Please check the quantity in procurement order(s) for the product "%s", it should not be 0 or less!' % procurement.product_id.name))
313 if procurement.product_id.type in ('product', 'consu'):
314 if not procurement.move_id:
315 source = procurement.location_id.id
316 if procurement.procure_method == 'make_to_order':
317 source = procurement.product_id.property_stock_procurement.id
318 id = move_obj.create(cr, uid, {
319 'name': procurement.name,
320 'location_id': source,
321 'location_dest_id': procurement.location_id.id,
322 'product_id': procurement.product_id.id,
323 'product_qty': procurement.product_qty,
324 'product_uom': procurement.product_uom.id,
325 'date_expected': procurement.date_planned,
327 'company_id': procurement.company_id.id,
328 'auto_validate': True,
330 move_obj.action_confirm(cr, uid, [id], context=context)
331 self.write(cr, uid, [procurement.id], {'move_id': id, 'close_move': 1})
332 self.write(cr, uid, ids, {'state': 'confirmed', 'message': ''})
335 def action_move_assigned(self, cr, uid, ids, context=None):
336 """ Changes procurement state to Running and writes message.
339 message = _('Products reserved from stock.')
340 self.write(cr, uid, ids, {'state': 'running',
341 'message': message}, context=context)
342 self.message_post(cr, uid, ids, body=message, context=context)
345 def _check_make_to_stock_service(self, cr, uid, procurement, context=None):
347 This method may be overrided by objects that override procurement.order
348 for computing their own purpose
352 def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
353 """ Checks procurement move state.
354 @param procurement: Current procurement.
355 @return: True or move id.
358 if procurement.move_id:
360 id = procurement.move_id.id
361 if not (procurement.move_id.state in ('done','assigned','cancel')):
362 ok = ok and self.pool.get('stock.move').action_assign(cr, uid, [id])
363 order_point_id = self.pool.get('stock.warehouse.orderpoint').search(cr, uid, [('product_id', '=', procurement.product_id.id)], context=context)
364 if not order_point_id and not ok:
365 message = _("Not enough stock and no minimum orderpoint rule defined.")
367 message = _("Not enough stock.")
370 message = _("Procurement '%s' is in exception: ") % (procurement.name) + message
371 #temporary context passed in write to prevent an infinite loop
372 ctx_wkf = dict(context or {})
373 ctx_wkf['workflow.trg_write.%s' % self._name] = False
374 self.write(cr, uid, [procurement.id], {'message': message},context=ctx_wkf)
375 self.message_post(cr, uid, [procurement.id], body=message, context=context)
378 def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
379 """ Don't trigger workflow for the element specified in trigger
381 wkf_op_key = 'workflow.%s.%s' % (trigger, self._name)
382 if context and not context.get(wkf_op_key, True):
383 # make sure we don't have a trigger loop while processing triggers
385 return super(procurement_order,self)._workflow_trigger(cr, uid, ids, trigger, context=context)
387 def action_produce_assign_service(self, cr, uid, ids, context=None):
388 """ Changes procurement state to Running.
391 for procurement in self.browse(cr, uid, ids, context=context):
392 self.write(cr, uid, [procurement.id], {'state': 'running'})
395 def action_produce_assign_product(self, cr, uid, ids, context=None):
396 """ This is action which call from workflow to assign production order to procurements
402 def action_po_assign(self, cr, uid, ids, context=None):
403 """ This is action which call from workflow to assign purchase order to procurements
408 # XXX action_cancel() should accept a context argument
409 def action_cancel(self, cr, uid, ids):
410 """Cancel Procurements and either cancel or assign the related Stock Moves, depending on the procurement configuration.
416 move_obj = self.pool.get('stock.move')
417 for proc in self.browse(cr, uid, ids):
418 if proc.close_move and proc.move_id:
419 if proc.move_id.state not in ('done', 'cancel'):
420 to_cancel.append(proc.move_id.id)
422 if proc.move_id and proc.move_id.state == 'waiting':
423 to_assign.append(proc.move_id.id)
425 move_obj.action_cancel(cr, uid, to_cancel)
427 move_obj.write(cr, uid, to_assign, {'state': 'assigned'})
428 self.write(cr, uid, ids, {'state': 'cancel'})
429 wf_service = netsvc.LocalService("workflow")
431 wf_service.trg_trigger(uid, 'procurement.order', id, cr)
434 def action_check_finished(self, cr, uid, ids):
435 return self.check_move_done(cr, uid, ids)
437 def action_check(self, cr, uid, ids):
438 """ Checks procurement move state whether assigned or done.
442 for procurement in self.browse(cr, uid, ids):
443 if procurement.move_id and procurement.move_id.state == 'assigned' or procurement.move_id.state == 'done':
444 self.action_done(cr, uid, [procurement.id])
448 def action_ready(self, cr, uid, ids):
449 """ Changes procurement state to Ready.
452 res = self.write(cr, uid, ids, {'state': 'ready'})
455 def action_done(self, cr, uid, ids):
456 """ Changes procurement state to Done and writes Closed date.
459 move_obj = self.pool.get('stock.move')
460 for procurement in self.browse(cr, uid, ids):
461 if procurement.move_id:
462 if procurement.close_move and (procurement.move_id.state <> 'done'):
463 move_obj.action_done(cr, uid, [procurement.move_id.id])
464 res = self.write(cr, uid, ids, {'state': 'done', 'date_close': time.strftime('%Y-%m-%d')})
465 wf_service = netsvc.LocalService("workflow")
467 wf_service.trg_trigger(uid, 'procurement.order', id, cr)
470 class StockPicking(osv.osv):
471 _inherit = 'stock.picking'
472 def test_finished(self, cursor, user, ids):
473 wf_service = netsvc.LocalService("workflow")
474 res = super(StockPicking, self).test_finished(cursor, user, ids)
475 for picking in self.browse(cursor, user, ids):
476 for move in picking.move_lines:
477 if move.state == 'done' and move.procurements:
478 for procurement in move.procurements:
479 wf_service.trg_validate(user, 'procurement.order',
480 procurement.id, 'button_check', cursor)
483 class stock_warehouse_orderpoint(osv.osv):
485 Defines Minimum stock rules.
487 _name = "stock.warehouse.orderpoint"
488 _description = "Minimum Inventory Rule"
490 def _get_draft_procurements(self, cr, uid, ids, field_name, arg, context=None):
494 procurement_obj = self.pool.get('procurement.order')
495 for orderpoint in self.browse(cr, uid, ids, context=context):
496 procurement_ids = procurement_obj.search(cr, uid , [('state', '=', 'draft'), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)])
497 result[orderpoint.id] = procurement_ids
500 def _check_product_uom(self, cr, uid, ids, context=None):
502 Check if the UoM has the same category as the product standard UoM
507 for rule in self.browse(cr, uid, ids, context=context):
508 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
514 'name': fields.char('Name', size=32, required=True),
515 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
516 'logic': fields.selection([('max','Order to Max'),('price','Best price (not yet active!)')], 'Reordering Mode', required=True),
517 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
518 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
519 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type','!=','service')]),
520 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
521 'product_min_qty': fields.float('Minimum Quantity', required=True,
522 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
523 "a procurement to bring the forecasted quantity to the Max Quantity."),
524 'product_max_qty': fields.float('Maximum Quantity', required=True,
525 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
526 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
527 'qty_multiple': fields.integer('Qty Multiple', required=True,
528 help="The procurement quantity will be rounded up to this multiple."),
529 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
530 'company_id': fields.many2one('res.company','Company',required=True),
531 'procurement_draft_ids': fields.function(_get_draft_procurements, type='many2many', relation="procurement.order", \
532 string="Related Procurement Orders",help="Draft procurement of the product and location of that orderpoint"),
535 'active': lambda *a: 1,
536 'logic': lambda *a: 'max',
537 'qty_multiple': lambda *a: 1,
538 'name': lambda x,y,z,c: x.pool.get('ir.sequence').get(y,z,'stock.orderpoint') or '',
539 'product_uom': lambda sel, cr, uid, context: context.get('product_uom', False),
540 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=c)
543 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
546 (_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']),
549 def default_get(self, cr, uid, fields, context=None):
550 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
551 # default 'warehouse_id' and 'location_id'
552 if 'warehouse_id' not in res:
553 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
554 res['warehouse_id'] = warehouse.id
555 if 'location_id' not in res:
556 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
557 res['location_id'] = warehouse.lot_stock_id.id
560 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
561 """ Finds location id for changed warehouse.
562 @param warehouse_id: Changed id of warehouse.
563 @return: Dictionary of values.
566 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
567 v = {'location_id': w.lot_stock_id.id}
571 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
572 """ Finds UoM for changed product.
573 @param product_id: Changed id of product.
574 @return: Dictionary of values.
577 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
578 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
579 v = {'product_uom': prod.uom_id.id}
580 return {'value': v, 'domain': d}
581 return {'domain': {'product_uom': []}}
583 def copy(self, cr, uid, id, default=None, context=None):
587 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
589 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
591 class product_template(osv.osv):
592 _inherit="product.template"
595 '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."),
596 '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."),
597 '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."),
600 'procure_method': 'make_to_stock',
601 'supply_method': 'buy',
604 class product_product(osv.osv):
605 _inherit="product.product"
607 'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
612 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: