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 datetime import date, datetime
23 from dateutil import relativedelta
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29 from openerp import tools
30 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
31 from openerp import SUPERUSER_ID
32 import openerp.addons.decimal_precision as dp
34 _logger = logging.getLogger(__name__)
37 #----------------------------------------------------------
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41 _name = "stock.incoterms"
42 _description = "Incoterms"
44 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
45 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
46 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
52 #----------------------------------------------------------
54 #----------------------------------------------------------
56 class stock_location(osv.osv):
57 _name = "stock.location"
58 _description = "Inventory Locations"
59 _parent_name = "location_id"
61 _parent_order = 'name'
62 _order = 'parent_left'
63 _rec_name = 'complete_name'
65 def _complete_name(self, cr, uid, ids, name, args, context=None):
66 """ Forms complete name of location from parent location to child location.
67 @return: Dictionary of values
70 for m in self.browse(cr, uid, ids, context=context):
72 parent = m.location_id
74 res[m.id] = parent.name + ' / ' + res[m.id]
75 parent = parent.location_id
78 def _get_sublocations(self, cr, uid, ids, context=None):
79 """ return all sublocations of the given stock locations (included) """
82 context_with_inactive = context.copy()
83 context_with_inactive['active_test'] = False
84 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
87 'name': fields.char('Location Name', size=64, required=True, translate=True),
88 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
89 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
90 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
91 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
92 \n* Internal Location: Physical locations inside your own warehouses,
93 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
94 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
95 \n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running.
96 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
99 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
100 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
101 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
102 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
104 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
106 'comment': fields.text('Additional Information'),
107 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
108 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
109 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
111 'parent_left': fields.integer('Left Parent', select=1),
112 'parent_right': fields.integer('Right Parent', select=1),
114 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
115 'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'),
116 'removal_strategy_ids': fields.one2many('product.removal', 'location_id', 'Removal Strategies'),
117 'putaway_strategy_ids': fields.one2many('product.putaway', 'location_id', 'Put Away Strategies'),
122 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
126 'scrap_location': False,
129 def get_putaway_strategy(self, cr, uid, location, product, context=None):
130 pa = self.pool.get('product.putaway')
131 categ = product.categ_id
132 categs = [categ.id, False]
133 while categ.parent_id:
134 categ = categ.parent_id
135 categs.append(categ.id)
137 result = pa.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
139 return pa.browse(cr, uid, result[0], context=context)
141 def get_removal_strategy(self, cr, uid, location, product, context=None):
142 pr = self.pool.get('product.removal')
143 categ = product.categ_id
144 categs = [categ.id, False]
145 while categ.parent_id:
146 categ = categ.parent_id
147 categs.append(categ.id)
149 result = pr.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
151 return pr.browse(cr, uid, result[0], context=context).method
154 #----------------------------------------------------------
156 #----------------------------------------------------------
158 class stock_location_route(osv.osv):
159 _name = 'stock.location.route'
160 _description = "Inventory Routes"
164 'name': fields.char('Route Name', required=True),
165 'sequence': fields.integer('Sequence'),
166 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'),
167 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
168 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'),
169 'product_selectable': fields.boolean('Applicable on Product'),
170 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
171 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
172 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
173 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
177 'sequence': lambda self, cr, uid, ctx: 0,
179 'product_selectable': True,
183 #----------------------------------------------------------
185 #----------------------------------------------------------
187 class stock_quant(osv.osv):
189 Quants are the smallest unit of stock physical instances
191 _name = "stock.quant"
192 _description = "Quants"
194 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
195 """ Forms complete name of location from parent location to child location.
196 @return: Dictionary of values
199 for q in self.browse(cr, uid, ids, context=context):
201 res[q.id] = q.product_id.code or ''
203 res[q.id] = q.lot_id.name
204 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
208 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
209 'product_id': fields.many2one('product.product', 'Product', required=True),
210 'location_id': fields.many2one('stock.location', 'Location', required=True),
211 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"),
212 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"),
213 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True),
214 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"),
215 'link_move_operation_id': fields.many2one('stock.move.operation.link', 'Reserved for Link between Move and Pack Operation', help="Technical field decpicting for with tuple (move, operation) this quant is reserved for"),
216 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
217 'cost': fields.float('Unit Cost'),
218 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"),
220 'create_date': fields.datetime('Creation Date'),
221 'in_date': fields.datetime('Incoming Date'),
223 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
224 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True),
226 # Used for negative quants to reconcile after compensated by a new positive one
227 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'),
228 'negative_dest_location_id': fields.many2one('stock.location', 'Destination Location', help='Technical field used to record the destination location of a move that created a negative quant'),
232 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
235 def action_view_quant_history(self, cr, uid, ids, context=None):
237 This function returns an action that display the history of the quant, which
238 mean all the stock moves that lead to this quant creation with this quant quantity.
240 mod_obj = self.pool.get('ir.model.data')
241 act_obj = self.pool.get('ir.actions.act_window')
243 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
244 id = result and result[1] or False
245 result = act_obj.read(cr, uid, [id], context={})[0]
248 for quant in self.browse(cr, uid, ids, context=context):
249 move_ids += [move.id for move in quant.history_ids]
251 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
254 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
255 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
256 is also set to 'assigned'
258 :param quants: list of tuple(quant browse record or None, qty to reserve). If None is given as first tuple element, the item will be ignored
259 :param move: browse record
260 :param link: browse record (stock.move.operation.link)
263 #split quants if needed
264 for quant, qty in quants:
267 self._quant_split(cr, uid, quant, qty, context=context)
268 toreserve.append(quant.id)
271 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id, 'link_move_operation_id': link and link.id or False}, context=context)
272 #check if move'state needs to be set as 'assigned'
274 if sum([q.qty for q in move.reserved_quant_ids]) == move.product_qty and move.state == 'confirmed':
275 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
277 def quants_move(self, cr, uid, quants, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
278 """Moves all given stock.quant in the destination location of the given move.
280 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
281 :param move: browse record (stock.move)
282 :param lot_id: ID of the lot that mus be set on the quants to move
283 :param owner_id: ID of the partner that must own the quants to move
284 :param src_package_id: ID of the package that contains the quants to move
285 :param dest_package_id: ID of the package that must be set on the moved quant
287 for quant, qty in quants:
289 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
290 quant = self._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, context=context)
291 self.move_single_quant_tuple(cr, uid, quant, qty, move, context=context)
293 def check_preferred_location(self, cr, uid, move, qty, context=None):
294 '''Checks the preferred location on the move, if any returned by a putaway strategy, and returns a list of
295 tuple(location, qty) where the quant have to be moved
297 :param move: browse record (stock.move)
299 :returns: list of tuple build as [(browe record (stock.move), float)]
303 for record in move.putaway_ids:
304 res.append((record.location_id, record.quantity))
306 return [(move.location_dest_id, qty)]
308 def move_single_quant(self, cr, uid, quant, location_to, qty, move, context=None):
309 '''Moves the given 'quant' in 'location_to' for the given 'qty', and logs the stock.move that triggered this move in the quant history.
310 If needed, the quant may be split if it's not totally moved.
312 :param quant: browse record (stock.quant)
313 :param location_to: browse record (stock.location)
315 :param move: browse record (stock.move)
317 new_quant = self._quant_split(cr, uid, quant, qty, context=context)
319 'location_id': location_to.id,
320 'history_ids': [(4, move.id)],
322 #if the quant we are moving had been split and was inside a package, it means we unpacked it
323 if new_quant and new_quant.package_id:
324 vals['package_id'] = False
325 self.write(cr, SUPERUSER_ID, [quant.id], vals, context=context)
329 def move_single_quant_tuple(self, cr, uid, quant, qty, move, context=None):
330 '''Effectively process the move of a tuple (quant record, qty to move). This may result in several quants moved
331 if the preferred locations on the move say so but by default it will only move the quant record given as argument
332 :param quant: browse record (stock.quant)
334 :param move: browse record (stock.move)
336 for location_to, qty in self.check_preferred_location(cr, uid, move, qty, context=context):
339 new_quant = self.move_single_quant(cr, uid, quant, location_to, qty, move, context=context)
340 self._quant_reconcile_negative(cr, uid, quant, context=context)
343 def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain=False, fallback_domain=False, restrict_lot_id=False, restrict_partner_id=False, context=None):
344 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
345 the choice on the quants that match the prefered_domain as well. But if the qty requested is not reached
346 it tries to find the remaining quantity by using the fallback_domain.
348 if prefered_domain and fallback_domain:
351 quants = self.quants_get(cr, uid, location, product, qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
356 quant_ids.append(quant[0].id)
359 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
361 #make sure the quants aren't found twice (if the prefered_domain and the fallback_domain aren't orthogonal
362 domain += [('id', 'not in', quant_ids)]
363 unprefered_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + fallback_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
364 for quant in unprefered_quants:
367 return self.quants_get(cr, uid, location, product, qty, domain=domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
369 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
371 Use the removal strategies of product to search for the correct quants
372 If you inherit, put the super at the end of your method.
374 :location: browse record of the parent location where the quants have to be found
375 :product: browse record of the product to find
376 :qty in UoM of product
379 domain = domain or [('qty', '>', 0.0)]
380 if restrict_partner_id:
381 domain += [('owner_id', '=', restrict_partner_id)]
383 domain += [('lot_id', '=', restrict_lot_id)]
385 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context) or 'fifo'
386 if removal_strategy == 'fifo':
387 result += self._quants_get_fifo(cr, uid, location, product, qty, domain, context=context)
388 elif removal_strategy == 'lifo':
389 result += self._quants_get_lifo(cr, uid, location, product, qty, domain, context=context)
391 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
394 def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, force_location=False, context=None):
395 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
399 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
400 location = force_location or move.location_dest_id
402 'product_id': move.product_id.id,
403 'location_id': location.id,
406 'history_ids': [(4, move.id)],
407 'in_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
408 'company_id': move.company_id.id,
410 'owner_id': owner_id,
411 'package_id': dest_package_id,
414 if move.location_id.usage == 'internal':
415 #if we were trying to move something from an internal location and reach here (quant creation),
416 #it means that a negative quant has to be created as well.
417 negative_vals = vals.copy()
418 negative_vals['location_id'] = move.location_id.id
419 negative_vals['qty'] = -qty
420 negative_vals['cost'] = price_unit
421 negative_vals['negative_dest_location_id'] = move.location_dest_id.id
422 negative_vals['package_id'] = src_package_id
423 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
424 vals.update({'propagated_from_id': negative_quant_id})
426 #create the quant as superuser, because we want to restrict the creation of quant manually: they should always use this method to create quants
427 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
428 return self.browse(cr, uid, quant_id, context=context)
430 def _quant_split(self, cr, uid, quant, qty, context=None):
431 context = context or {}
432 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
434 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
435 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
437 return self.browse(cr, uid, new_quant, context=context)
439 def _get_latest_move(self, cr, uid, quant, context=None):
441 for m in quant.history_ids:
442 if not move or m.date > move.date:
446 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
448 for move in solving_quant.history_ids:
449 path.append((4, move.id))
450 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
452 def _quant_reconcile_negative(self, cr, uid, quant, context=None):
454 When new quant arrive in a location, try to reconcile it with
455 negative quants. If it's possible, apply the cost of the new
456 quant to the conter-part of the negative quant.
458 if quant.location_id.usage != 'internal':
460 solving_quant = quant
461 dom = [('qty', '<', 0)]
462 dom += [('lot_id', '=', quant.lot_id and quant.lot_id.id or False)]
463 dom += [('owner_id', '=', quant.owner_id and quant.owner_id.id or False)]
464 dom += [('package_id', '=', quant.package_id and quant.package_id.id or False)]
465 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, [('qty', '<', '0')], context=context)
466 for quant_neg, qty in quants:
469 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
470 if not to_solve_quant_ids:
473 solved_quant_ids = []
474 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
477 solved_quant_ids.append(to_solve_quant.id)
478 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
479 solving_qty -= min(solving_qty, to_solve_quant.qty)
480 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
481 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
482 #if the reconciliation was not complete, we need to link together the remaining parts
483 if remaining_neg_quant:
484 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
485 if remaining_to_solve_quant_ids:
486 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
487 #delete the reconciled quants, as it is replaced by the solved quants
488 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
489 #price update + accounting entries adjustments
490 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
491 #merge history (and cost?)
492 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
493 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
494 solving_quant = remaining_solving_quant
496 def _price_update(self, cr, uid, ids, newprice, context=None):
497 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
499 def write(self, cr, uid, ids, vals, context=None):
500 #We want to trigger the move with nothing on reserved_quant_ids for the store of the remaining quantity
501 if 'reservation_id' in vals:
502 reservation_ids = self.browse(cr, uid, ids, context=context)
503 moves_to_warn = set()
504 for reser in reservation_ids:
505 if reser.reservation_id:
506 moves_to_warn.add(reser.reservation_id.id)
507 self.pool.get('stock.move').write(cr, uid, list(moves_to_warn), {'reserved_quant_ids': []}, context=context)
508 return super(stock_quant, self).write(cr, SUPERUSER_ID, ids, vals, context=context)
510 def quants_unreserve(self, cr, uid, move, context=None):
511 related_quants = [x.id for x in move.reserved_quant_ids]
512 return self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False, 'link_move_operation_id': False}, context=context)
514 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
515 ''' Implementation of removal strategies
516 If it can not reserve, it will return a tuple (None, qty)
518 domain += location and [('location_id', 'child_of', location.id)] or []
519 domain += [('product_id', '=', product.id)] + domain
523 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
525 res.append((None, quantity))
527 for quant in self.browse(cr, uid, quants, context=context):
528 if quantity >= abs(quant.qty):
529 res += [(quant, abs(quant.qty))]
530 quantity -= abs(quant.qty)
532 res += [(quant, quantity)]
538 def _quants_get_fifo(self, cr, uid, location, product, quantity, domain=[], context=None):
540 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
542 def _quants_get_lifo(self, cr, uid, location, product, quantity, domain=[], context=None):
543 order = 'in_date desc'
544 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
546 def _location_owner(self, cr, uid, quant, location, context=None):
547 ''' Return the company owning the location if any '''
548 return location and (location.usage == 'internal') and location.company_id or False
550 def _check_location(self, cr, uid, ids, context=None):
551 for record in self.browse(cr, uid, ids, context=context):
552 if record.location_id.usage == 'view':
553 raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.') % (record.product_id.name, record.location_id.name))
556 # FP Note: rehab this, with the auto creation algo
557 # def _check_tracking(self, cr, uid, ids, context=None):
558 # """ Checks if serial number is assigned to stock move or not.
559 # @return: True or False
561 # for move in self.browse(cr, uid, ids, context=context):
562 # if not move.lot_id and \
563 # (move.state == 'done' and \
565 # (move.product_id.track_production and move.location_id.usage == 'production') or \
566 # (move.product_id.track_production and move.location_dest_id.usage == 'production') or \
567 # (move.product_id.track_incoming and move.location_id.usage == 'supplier') or \
568 # (move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \
569 # (move.product_id.track_incoming and move.location_id.usage == 'inventory') \
575 (_check_location, 'You cannot move products to a location of the type view.', ['location_id'])
576 #(_check_tracking, 'You must assign a serial number for this product.', ['prodlot_id']),
580 #----------------------------------------------------------
582 #----------------------------------------------------------
584 class stock_picking(osv.osv):
585 _name = "stock.picking"
586 _inherit = ['mail.thread']
587 _description = "Picking List"
588 _order = "priority desc, date desc, id desc"
590 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
591 move_obj = self.pool.get("stock.move")
593 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
594 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
596 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
597 """ Finds minimum and maximum dates for picking.
598 @return: Dictionary of values
602 res[id] = {'min_date': False, 'max_date': False}
614 picking_id""", (tuple(ids),))
615 for pick, dt1, dt2 in cr.fetchall():
616 res[pick]['min_date'] = dt1
617 res[pick]['max_date'] = dt2
620 def create(self, cr, user, vals, context=None):
621 context = context or {}
622 if ('name' not in vals) or (vals.get('name') in ('/', False)):
623 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
624 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
625 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
626 return super(stock_picking, self).create(cr, user, vals, context)
628 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
629 '''The state of a picking depends on the state of its related stock.move
630 draft: the picking has no line or any one of the lines is draft
631 done, draft, cancel: all lines are done / draft / cancel
632 confirmed, auto, assigned depends on move_type (all at once or direct)
635 for pick in self.browse(cr, uid, ids, context=context):
636 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
637 res[pick.id] = 'draft'
639 if all([x.state == 'cancel' for x in pick.move_lines]):
640 res[pick.id] = 'cancel'
642 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
643 res[pick.id] = 'done'
646 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
647 order_inv = dict(zip(order.values(), order.keys()))
648 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
649 if pick.move_lines == 'one':
650 res[pick.id] = order_inv[min(lst)]
652 res[pick.id] = order_inv[max(lst)]
655 def _get_pickings(self, cr, uid, ids, context=None):
657 for move in self.browse(cr, uid, ids, context=context):
659 res.add(move.picking_id.id)
662 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
664 for pick in self.browse(cr, uid, ids, context=context):
666 if pick.pack_operation_ids:
670 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
672 for pick in self.browse(cr, uid, ids, context=context):
674 for move in pick.move_lines:
675 if move.reserved_quant_ids:
680 def action_assign_owner(self, cr, uid, ids, context=None):
681 for picking in self.browse(cr, uid, ids, context=context):
682 packop_ids = [op.id for op in picking.pack_operation_ids]
683 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
686 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
687 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
688 'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
689 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
690 'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="It specifies goods to be deliver partially or all at once"),
691 'state': fields.function(_state_get, type="selection", store={
692 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type', 'move_lines'], 20),
693 'stock.move': (_get_pickings, ['state', 'picking_id'], 20)}, selection=[
695 ('cancel', 'Cancelled'),
696 ('waiting', 'Waiting Another Operation'),
697 ('confirmed', 'Waiting Availability'),
698 ('assigned', 'Ready to Transfer'),
699 ('done', 'Transferred'),
700 ], string='Status', readonly=True, select=True, track_visibility='onchange', help="""
701 * Draft: not confirmed yet and will not be scheduled until confirmed\n
702 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
703 * Waiting Availability: still waiting for the availability of products\n
704 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
705 * Transferred: has been processed, can't be modified or cancelled anymore\n
706 * Cancelled: has been cancelled, can't be confirmed anymore"""
708 'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Priority', required=True),
709 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
710 store={'stock.move': (_get_pickings, ['state', 'date_expected'], 20)}, type='datetime', string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed"),
711 'max_date': fields.function(get_min_max_date, multi="min_max_date",
712 store={'stock.move': (_get_pickings, ['state', 'date_expected'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
713 'date': fields.datetime('Commitment Date', help="Date promised for the completion of the transfer order, usually set the time of the order and revised later on.", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
714 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
715 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
716 'quant_reserved_exist': fields.function(_get_quant_reserved_exist, type='boolean', string='Quant already reserved ?', help='technical field used to know if there is already at least one quant reserved on moves of a given picking'),
717 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
718 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
719 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', string='Related Packing Operations'),
720 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
721 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True),
723 'owner_id': fields.many2one('res.partner', 'Owner', help="Default Owner"),
724 # Used to search on pickings
725 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
726 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
727 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
728 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
730 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
731 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
736 'name': lambda self, cr, uid, context: '/',
739 'priority': '1', # normal
740 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
741 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
744 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
747 def copy(self, cr, uid, id, default=None, context=None):
750 default = default.copy()
751 picking_obj = self.browse(cr, uid, id, context=context)
752 if ('name' not in default) or (picking_obj.name == '/'):
753 default['name'] = '/'
754 if not default.get('backorder_id'):
755 default['backorder_id'] = False
756 default['pack_operation_ids'] = []
757 return super(stock_picking, self).copy(cr, uid, id, default, context)
759 def action_confirm(self, cr, uid, ids, context=None):
761 todo_force_assign = []
762 for picking in self.browse(cr, uid, ids, context=context):
763 if picking.picking_type_id.auto_force_assign:
764 todo_force_assign.append(picking.id)
765 for r in picking.move_lines:
766 if r.state == 'draft':
769 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
771 if todo_force_assign:
772 self.force_assign(cr, uid, todo_force_assign, context=context)
775 def action_assign(self, cr, uid, ids, context=None):
776 """ Check availability of picking moves.
777 This has the effect of changing the state and reserve quants on available moves, and may
778 also impact the state of the picking as it is computed based on move's states.
781 for pick in self.browse(cr, uid, ids, context=context):
782 if pick.state == 'draft':
783 self.action_confirm(cr, uid, [pick.id], context=context)
784 #skip the moves that don't need to be checked
785 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
787 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
788 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
791 def force_assign(self, cr, uid, ids, context=None):
792 """ Changes state of picking to available if moves are confirmed or waiting.
795 for pick in self.browse(cr, uid, ids, context=context):
796 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
797 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
800 def cancel_assign(self, cr, uid, ids, context=None):
801 """ Cancels picking and moves.
804 for pick in self.browse(cr, uid, ids, context=context):
805 move_ids = [x.id for x in pick.move_lines]
806 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids, context=context)
809 def action_cancel(self, cr, uid, ids, context=None):
810 for pick in self.browse(cr, uid, ids, context=context):
811 ids2 = [move.id for move in pick.move_lines]
812 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
815 def action_done(self, cr, uid, ids, context=None):
816 """Changes picking state to done by processing the Stock Moves of the Picking
818 Normally that happens when the button "Done" is pressed on a Picking view.
821 for pick in self.browse(cr, uid, ids, context=context):
823 for move in pick.move_lines:
824 if move.state == 'draft':
825 self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
828 elif move.state in ('assigned', 'confirmed'):
831 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
834 def unlink(self, cr, uid, ids, context=None):
835 #on picking deletion, cancel its move then unlink them too
836 move_obj = self.pool.get('stock.move')
837 context = context or {}
838 for pick in self.browse(cr, uid, ids, context=context):
839 move_ids = [move.id for move in pick.move_lines]
840 move_obj.action_cancel(cr, uid, move_ids, context=context)
841 move_obj.unlink(cr, uid, move_ids, context=context)
842 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
844 def write(self, cr, uid, ids, vals, context=None):
845 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
846 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
847 if 'move_lines' in vals or 'pack_operation_ids' in vals:
848 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
851 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
852 """ Move all non-done lines into a new backorder picking. If the key 'do_only_split' is given in the context, then move all lines not in context.get('split', []) instead of all non-done lines.
854 if not backorder_moves:
855 backorder_moves = picking.move_lines
856 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
857 if 'do_only_split' in context and context['do_only_split']:
858 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
860 if backorder_move_ids:
861 backorder_id = self.copy(cr, uid, picking.id, {
864 'pack_operation_ids': [],
865 'backorder_id': picking.id,
867 back_order_name = self.browse(cr, uid, backorder_id, context=context).name
868 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (back_order_name), context=context)
869 move_obj = self.pool.get("stock.move")
870 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
872 self.pool.get("stock.picking").action_confirm(cr, uid, [picking.id], context=context)
873 self.action_confirm(cr, uid, [backorder_id], context=context)
877 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
879 context = context or {}
880 pack_operation_obj = self.pool.get('stock.pack.operation')
881 pack_obj = self.pool.get("stock.quant.package")
882 quant_obj = self.pool.get("stock.quant")
883 for picking in self.browse(cr, uid, picking_ids, context=context):
884 for move in picking.move_lines:
885 if move.state != 'assigned':
887 #Check which of the reserved quants are entirely in packages (can be in separate method)
888 packages = list(set([x.package_id for x in move.reserved_quant_ids if x.package_id]))
890 for pack in packages:
895 quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
896 if all([x.reservation_id.id == move.id for x in quant_obj.browse(cr, uid, quants, context=context) if x.reservation_id]):
897 good_pack = test_pack.id
898 if test_pack.parent_id:
899 test_pack = test_pack.parent_id
905 done_packages.append(good_pack)
906 done_packages = list(set(done_packages))
908 #Create package operations
909 reserved = set([x.id for x in move.reserved_quant_ids])
910 remaining_qty = move.product_qty
911 for pack in pack_obj.browse(cr, uid, done_packages, context=context):
912 quantl = pack_obj.get_content(cr, uid, [pack.id], context=context)
913 for quant in quant_obj.browse(cr, uid, quantl, context=context):
914 remaining_qty -= quant.qty
915 quants = set(pack_obj.get_content(cr, uid, [pack.id], context=context))
917 pack_operation_obj.create(cr, uid, {
918 'picking_id': picking.id,
919 'package_id': pack.id,
923 yet_to_reserve = list(reserved)
924 #Create operations based on quants
925 for quant in quant_obj.browse(cr, uid, yet_to_reserve, context=context):
926 qty = min(quant.qty, move.product_qty)
928 pack_operation_obj.create(cr, uid, {
929 'picking_id': picking.id,
931 'product_id': quant.product_id.id,
932 'lot_id': quant.lot_id and quant.lot_id.id or False,
933 'product_uom_id': quant.product_id.uom_id.id,
934 'owner_id': quant.owner_id and quant.owner_id.id or False,
936 'package_id': quant.package_id and quant.package_id.id or False,
938 if remaining_qty > 0:
939 pack_operation_obj.create(cr, uid, {
940 'picking_id': picking.id,
941 'product_qty': remaining_qty,
942 'product_id': move.product_id.id,
943 'product_uom_id': move.product_id.uom_id.id,
944 'cost': move.product_id.standard_price,
947 def do_unreserve(self, cr, uid, picking_ids, context=None):
949 Will remove all quants for picking in picking_ids
951 moves_to_unreserve = []
952 for picking in self.browse(cr, uid, picking_ids, context=context):
953 moves_to_unreserve += [m.id for m in picking.move_lines]
954 if moves_to_unreserve:
955 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
957 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
958 def _create_link_for_product(product_id, qty):
960 for move in picking.move_lines:
961 if move.product_id.id == product_id:
962 qty_on_link = min(move.remaining_qty, qty_to_assign)
963 link_obj.create(cr, uid, {'move_id': move.id, 'operation_id': op.id, 'qty': qty_on_link}, context=context)
964 qty_to_assign -= qty_on_link
965 if qty_to_assign <= 0:
968 link_obj = self.pool.get('stock.move.operation.link')
969 uom_obj = self.pool.get('product.uom')
970 package_obj = self.pool.get('stock.quant.package')
971 for picking in self.browse(cr, uid, picking_ids, context=context):
972 for op in picking.pack_operation_ids:
973 to_unlink_ids = [x.id for x in op.linked_move_operation_ids]
975 link_obj.unlink(cr, uid, to_unlink_ids, context=context)
977 normalized_qty = uom_obj._compute_qty(cr, uid, op.product_uom_id.id, op.product_qty, op.product_id.uom_id.id)
978 _create_link_for_product(op.product_id.id, normalized_qty)
980 for product_id, qty in package_obj._get_all_products_quantities(cr, uid, op.package_id.id, context=context).items():
981 _create_link_for_product(product_id, qty)
983 def _create_extra_moves(self, cr, uid, picking, context=None):
984 '''This function creates move lines on a picking, at the time of do_transfer, based on
985 unexpected product transfers (or exceeding quantities) found in the pack operations.
987 move_obj = self.pool.get('stock.move')
988 operation_obj = self.pool.get('stock.pack.operation')
989 for op in picking.pack_operation_ids:
990 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
991 if remaining_qty > 0:
992 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
994 'picking_id': picking.id,
995 'location_id': picking.location_id.id,
996 'location_dest_id': picking.location_dest_id.id,
997 'product_id': product_id,
998 'product_uom': product.uom_id.id,
999 'product_uom_qty': remaining_qty,
1000 'name': _('Extra Move: ') + product.name,
1001 'state': 'confirmed',
1003 move_obj.create(cr, uid, vals, context=context)
1004 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1006 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1007 """ Unreserve quants then try to reassign quants."""
1008 stock_move_obj = self.pool.get('stock.move')
1010 self.do_unreserve(cr, uid, [picking.id], context=context)
1011 self.action_assign(cr, uid, [picking.id], context=context)
1013 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1014 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1016 def do_transfer(self, cr, uid, picking_ids, context=None):
1018 If no pack operation, we do simple action_done of the picking
1019 Otherwise, do the pack operations
1023 stock_move_obj = self.pool.get('stock.move')
1024 for picking in self.browse(cr, uid, picking_ids, context=context):
1025 if not picking.pack_operation_ids:
1026 self.action_done(cr, uid, [picking.id], context=context)
1029 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1030 #create extra moves in the picking (unexpected product moves coming from pack operations)
1031 self._create_extra_moves(cr, uid, picking, context=context)
1033 #split move lines eventually
1035 toassign_move_ids = []
1036 for move in picking.move_lines:
1037 if move.state == 'draft':
1038 toassign_move_ids.append(move.id)
1039 if move.remaining_qty == 0:
1040 if move.state in ('draft', 'assigned', 'confirmed'):
1041 todo_move_ids.append(move.id)
1042 elif move.remaining_qty > 0:
1043 new_move = stock_move_obj.split(cr, uid, move, move.remaining_qty, context=context)
1044 todo_move_ids.append(move.id)
1045 #Assign move as it was assigned before
1046 toassign_move_ids.append(new_move)
1048 #this should never happens
1050 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1051 if todo_move_ids and not context.get('do_only_split'):
1052 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1053 elif context.get('do_only_split'):
1054 context.update({'split': todo_move_ids})
1056 self._create_backorder(cr, uid, picking, context=context)
1057 if toassign_move_ids:
1058 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1061 def do_split(self, cr, uid, picking_ids, context=None):
1062 """ just split the picking (create a backorder) without making it 'done' """
1065 ctx = context.copy()
1066 ctx['do_only_split'] = True
1067 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1069 def get_next_picking_for_ui(self, cr, uid, context=None):
1070 """ returns the next pickings to process. Used in the barcode scanner UI"""
1073 domain = [('state', 'in', ('confirmed', 'assigned'))]
1074 if context.get('default_picking_type_id'):
1075 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1076 return self.search(cr, uid, domain, context=context)
1078 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1079 """ called when button 'done' in pused in the barcode scanner UI """
1080 self.do_transfer(cr, uid, [picking_id], context=context)
1081 #return id of next picking to work on
1082 return self.get_next_picking_for_ui(cr, uid, context=context)
1084 def action_pack(self, cr, uid, picking_ids, context=None):
1085 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1086 Used in the barcode scanner UI and the normal interface as well. """
1087 stock_operation_obj = self.pool.get('stock.pack.operation')
1088 package_obj = self.pool.get('stock.quant.package')
1089 for picking_id in picking_ids:
1090 operation_ids = stock_operation_obj.search(cr, uid, [('picking_id', '=', picking_id), ('result_package_id', '=', False)], context=context)
1092 package_id = package_obj.create(cr, uid, {}, context=context)
1093 stock_operation_obj.write(cr, uid, operation_ids, {'result_package_id': package_id}, context=context)
1096 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, context=None):
1097 return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id)], context=context)
1099 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, context=None):
1100 '''This function is called each time there barcode scanner reads an input'''
1101 lot_obj = self.pool.get('stock.production.lot')
1102 package_obj = self.pool.get('stock.quant.package')
1103 product_obj = self.pool.get('product.product')
1104 stock_operation_obj = self.pool.get('stock.pack.operation')
1105 #check if the barcode correspond to a product
1106 matching_product_ids = product_obj.search(cr, uid, [('ean13', '=', barcode_str)], context=context)
1107 if matching_product_ids:
1108 self.process_product_id_from_ui(cr, uid, picking_id, matching_product_ids[0], context=context)
1110 #check if the barcode correspond to a lot
1111 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1112 if matching_lot_ids:
1113 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1114 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], context=context)
1116 #check if the barcode correspond to a package
1117 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1118 if matching_package_ids:
1119 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], context=context)
1122 class stock_production_lot(osv.osv):
1123 _name = 'stock.production.lot'
1124 _inherit = ['mail.thread']
1125 _description = 'Lot/Serial'
1127 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1128 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1129 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1130 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants'),
1131 'create_date': fields.datetime('Creation Date'),
1134 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1135 'product_id': lambda x, y, z, c: c.get('product_id', False),
1137 _sql_constraints = [
1138 ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1142 # ----------------------------------------------------
1144 # ----------------------------------------------------
1146 class stock_move(osv.osv):
1147 _name = "stock.move"
1148 _description = "Stock Move"
1149 _order = 'date_expected desc, id'
1152 def get_price_unit(self, cr, uid, move, context=None):
1153 """ Returns the unit price to store on the quant """
1154 return move.price_unit or move.product_id.standard_price
1156 def name_get(self, cr, uid, ids, context=None):
1158 for line in self.browse(cr, uid, ids, context=context):
1159 name = line.location_id.name + ' > ' + line.location_dest_id.name
1160 if line.product_id.code:
1161 name = line.product_id.code + ': ' + name
1162 if line.picking_id.origin:
1163 name = line.picking_id.origin + '/ ' + name
1164 res.append((line.id, name))
1167 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1168 uom_obj = self.pool.get('product.uom')
1170 for m in self.browse(cr, uid, ids, context=context):
1171 res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False)
1174 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1175 uom_obj = self.pool.get('product.uom')
1177 for move in self.browse(cr, uid, ids, context=context):
1178 qty = move.product_qty
1179 for record in move.linked_move_operation_ids:
1181 #converting the remaining quantity in the move UoM
1182 res[move.id] = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1185 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1186 res = dict.fromkeys(ids, False)
1187 for move in self.browse(cr, uid, ids, context=context):
1188 if move.state == 'done':
1189 res[move.id] = [q.id for q in move.quant_ids]
1191 res[move.id] = [q.id for q in move.reserved_quant_ids]
1194 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1195 quant_obj = self.pool.get('stock.quant')
1196 res = dict.fromkeys(ids, False)
1197 for move in self.browse(cr, uid, ids, context=context):
1198 if move.state == 'done':
1199 res[move.id] = move.product_qty
1201 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1202 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1204 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1205 availability += quant.qty
1206 res[move.id] = min(move.product_qty, availability)
1209 def _get_move(self, cr, uid, ids, context=None):
1211 for quant in self.browse(cr, uid, ids, context=context):
1212 if quant.reservation_id:
1213 res.add(quant.reservation_id.id)
1217 'name': fields.char('Description', required=True, select=True),
1218 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1219 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1220 'date': fields.datetime('Date', required=True, select=True, help="Move date: scheduled date until move is done, then date of actual move processing", states={'done': [('readonly', True)]}),
1221 'date_expected': fields.datetime('Scheduled Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1222 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1223 # TODO: improve store to add dependency on product UoM
1224 'product_qty': fields.function(_quantity_normalize, type='float', store=True, string='Quantity',
1225 digits_compute=dp.get_precision('Product Unit of Measure'),
1226 help='Quantity in the default UoM of the product'),
1227 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1228 required=True, states={'done': [('readonly', True)]},
1229 help="This is the quantity of products from an inventory "
1230 "point of view. For moves in the state 'done', this is the "
1231 "quantity of products that were actually moved. For other "
1232 "moves, this is the quantity of product that is planned to "
1233 "be moved. Lowering this quantity does not generate a "
1234 "backorder. Changing this quantity on assigned moves affects "
1235 "the product reservation, and should be done with care."
1237 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1238 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1239 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1241 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1243 'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True, states={'done': [('readonly', True)]}, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."),
1244 'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True, states={'done': [('readonly', True)]}, select=True, help="Location where the system will stock the finished products."),
1246 # FP Note: should we remove this?
1247 'partner_id': fields.many2one('res.partner', 'Destination Address ', states={'done': [('readonly', True)]}, help="Optional address where goods are to be delivered, specifically used for allotment"),
1250 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1251 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1253 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1254 'picking_priority': fields.related('picking_id', 'priority', type='selection', selection=[('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Picking Priority'),
1255 'note': fields.text('Notes'),
1256 'state': fields.selection([('draft', 'New'),
1257 ('cancel', 'Cancelled'),
1258 ('waiting', 'Waiting Another Move'),
1259 ('confirmed', 'Waiting Availability'),
1260 ('assigned', 'Available'),
1262 ], 'Status', readonly=True, select=True,
1263 help= "* New: When the stock move is created and not yet confirmed.\n"\
1264 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1265 "* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to me manufactured...\n"\
1266 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1267 "* Done: When the shipment is processed, the state is \'Done\'."),
1269 'price_unit': fields.float('Unit Price', help="Technical field used to record the product cost set by the user during a picking confirmation (when average price costing method is used). Value given in company currency and in product uom."), # as it's a technical field, we intentionally don't provide the digits attribute
1271 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1272 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1273 'origin': fields.char("Source"),
1274 '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."),
1276 # used for colors in tree views:
1277 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1279 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1280 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1281 'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'move_id', string='Linked Operations', readonly=True, help='Operations that impact this move for the computation of the remaining quantities'),
1282 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1283 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1284 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1285 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1286 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1287 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1288 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1289 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1290 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'),
1291 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1292 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1293 'availability': fields.function(_get_product_availability, type='float', string='Availability'),
1294 'restrict_lot_id': fields.many2one('stock.production.lot', 'Lot', help="Technical field used to depict a restriction on the lot of quants to consider when marking this move as 'done'"),
1295 'restrict_partner_id': fields.many2one('res.partner', 'Owner ', help="Technical field used to depict a restriction on the ownership of quants to consider when marking this move as 'done'"),
1296 'putaway_ids': fields.one2many('stock.move.putaway', 'move_id', 'Put Away Suggestions'),
1297 'route_ids': fields.many2many('stock.location.route', 'stock_location_route_move', 'move_id', 'route_id', 'Destination route', help="Preferred route to be followed by the procurement order"),
1298 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', help="Technical field depicting the warehouse to consider for the route selection on the next procurement (if any)."),
1301 def _default_location_destination(self, cr, uid, context=None):
1302 context = context or {}
1303 if context.get('default_picking_type_id', False):
1304 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1305 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1308 def _default_location_source(self, cr, uid, context=None):
1309 context = context or {}
1310 if context.get('default_picking_type_id', False):
1311 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1312 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1315 def _default_destination_address(self, cr, uid, context=None):
1316 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1317 return user.company_id.partner_id.id
1320 'location_id': _default_location_source,
1321 'location_dest_id': _default_location_destination,
1322 'partner_id': _default_destination_address,
1326 'product_uom_qty': 1.0,
1328 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1329 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1330 'date_expected': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1331 'procure_method': 'make_to_stock',
1335 def _check_uom(self, cr, uid, ids, context=None):
1336 for move in self.browse(cr, uid, ids, context=context):
1337 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1343 'You try to move a product using a UoM that is not compatible with the UoM of the product moved. Please use an UoM in the same UoM category.',
1346 def copy_data(self, cr, uid, id, default=None, context=None):
1349 default = default.copy()
1350 default['move_orig_ids'] = []
1351 default['quant_ids'] = []
1352 default['reserved_quant_ids'] = []
1353 default['returned_move_ids'] = []
1354 default['linked_move_operation_ids'] = []
1355 default['origin_returned_move_id'] = False
1356 default['state'] = 'draft'
1357 return super(stock_move, self).copy_data(cr, uid, id, default, context)
1359 def do_unreserve(self, cr, uid, move_ids, context=None):
1361 quant_obj = self.pool.get("stock.quant")
1362 for move in self.browse(cr, uid, move_ids, context=context):
1363 quant_obj.quants_unreserve(cr, uid, move, context=context)
1365 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1366 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1367 group_id = move.group_id and move.group_id.id or False
1369 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1370 group_id = move.rule_id.group_id.id
1371 elif move.rule_id.group_propagation_option == 'none':
1374 'name': move.rule_id and move.rule_id.name or "/",
1376 'company_id': move.company_id and move.company_id.id or False,
1377 'date_planned': move.date,
1378 'product_id': move.product_id.id,
1379 'product_qty': move.product_qty,
1380 'product_uom': move.product_uom.id,
1381 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1382 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1383 'location_id': move.location_id.id,
1384 'move_dest_id': move.id,
1385 'group_id': group_id,
1386 'route_ids': [(4, x.id) for x in move.route_ids],
1387 'warehouse_id': move.warehouse_id and move.warehouse_id.id or False,
1390 def _push_apply(self, cr, uid, moves, context):
1391 push_obj = self.pool.get("stock.location.path")
1393 if not move.move_dest_id:
1394 routes = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1395 routes = routes or [x.id for x in move.route_ids]
1397 domain = [('route_id', 'in', routes), ('location_from_id', '=', move.location_dest_id.id)]
1398 if move.warehouse_id:
1399 domain += [('warehouse_id', '=', move.warehouse_id.id)]
1400 rules = push_obj.search(cr, uid, domain, context=context)
1402 rule = push_obj.browse(cr, uid, rules[0], context=context)
1403 push_obj._apply(cr, uid, rule, move, context=context)
1406 # Create the stock.move.putaway records
1407 def _putaway_apply(self, cr, uid, ids, context=None):
1408 moveputaway_obj = self.pool.get('stock.move.putaway')
1409 for move in self.browse(cr, uid, ids, context=context):
1410 putaway = self.pool.get('stock.location').get_putaway_strategy(cr, uid, move.location_dest_id, move.product_id, context=context)
1412 # Should call different methods here in later versions
1413 # TODO: take care of lots
1414 if putaway.method == 'fixed' and putaway.location_spec_id:
1415 moveputaway_obj.create(cr, SUPERUSER_ID, {'move_id': move.id,
1416 'location_id': putaway.location_spec_id.id,
1417 'quantity': move.product_qty}, context=context)
1420 def _create_procurement(self, cr, uid, move, context=None):
1421 """ This will create a procurement order """
1422 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1424 # Check that we do not modify a stock.move which is done
1425 def write(self, cr, uid, ids, vals, context=None):
1426 if isinstance(ids, (int, long)):
1428 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1429 for move in self.browse(cr, uid, ids, context=context):
1430 if move.state == 'done':
1431 if frozen_fields.intersection(vals):
1432 raise osv.except_osv(_('Operation Forbidden!'),
1433 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1434 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1436 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1437 """ On change of product quantity finds UoM and UoS quantities
1438 @param product_id: Product id
1439 @param product_qty: Changed Quantity of product
1440 @param product_uom: Unit of measure of product
1441 @param product_uos: Unit of sale of product
1442 @return: Dictionary of values
1445 'product_uos_qty': 0.00
1449 if (not product_id) or (product_qty <= 0.0):
1450 result['product_qty'] = 0.0
1451 return {'value': result}
1453 product_obj = self.pool.get('product.product')
1454 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1456 # Warn if the quantity was decreased
1458 for move in self.read(cr, uid, ids, ['product_qty']):
1459 if product_qty < move['product_qty']:
1461 'title': _('Information'),
1462 'message': _("By changing this quantity here, you accept the "
1463 "new quantity as complete: OpenERP will not "
1464 "automatically generate a back order.")})
1467 if product_uos and product_uom and (product_uom != product_uos):
1468 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1470 result['product_uos_qty'] = product_qty
1472 return {'value': result, 'warning': warning}
1474 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1475 product_uos, product_uom):
1476 """ On change of product quantity finds UoM and UoS quantities
1477 @param product_id: Product id
1478 @param product_uos_qty: Changed UoS Quantity of product
1479 @param product_uom: Unit of measure of product
1480 @param product_uos: Unit of sale of product
1481 @return: Dictionary of values
1484 'product_uom_qty': 0.00
1488 if (not product_id) or (product_uos_qty <= 0.0):
1489 result['product_uos_qty'] = 0.0
1490 return {'value': result}
1492 product_obj = self.pool.get('product.product')
1493 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1495 # Warn if the quantity was decreased
1496 for move in self.read(cr, uid, ids, ['product_uos_qty']):
1497 if product_uos_qty < move['product_uos_qty']:
1499 'title': _('Warning: No Back Order'),
1500 'message': _("By changing the quantity here, you accept the "
1501 "new quantity as complete: OpenERP will not "
1502 "automatically generate a Back Order.")})
1505 if product_uos and product_uom and (product_uom != product_uos):
1506 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1508 result['product_uom_qty'] = product_uos_qty
1509 return {'value': result, 'warning': warning}
1511 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1512 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1513 @param prod_id: Changed Product id
1514 @param loc_id: Source location id
1515 @param loc_dest_id: Destination location id
1516 @param partner_id: Address id of partner
1517 @return: Dictionary of values
1521 user = self.pool.get('res.users').browse(cr, uid, uid)
1522 lang = user and user.lang or False
1524 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1526 lang = addr_rec and addr_rec.lang or False
1527 ctx = {'lang': lang}
1529 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1530 uos_id = product.uos_id and product.uos_id.id or False
1532 'product_uom': product.uom_id.id,
1533 'product_uos': uos_id,
1534 'product_uom_qty': 1.00,
1535 'product_uos_qty': self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'],
1538 result['name'] = product.partner_ref
1540 result['location_id'] = loc_id
1542 result['location_dest_id'] = loc_dest_id
1543 return {'value': result}
1545 def _picking_assign(self, cr, uid, move, context=None):
1546 if move.picking_id or not move.picking_type_id:
1548 context = context or {}
1549 pick_obj = self.pool.get("stock.picking")
1551 group = move.group_id and move.group_id.id or False
1552 picks = pick_obj.search(cr, uid, [
1553 ('group_id', '=', group),
1554 ('location_id', '=', move.location_id.id),
1555 ('location_dest_id', '=', move.location_dest_id.id),
1556 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1561 'origin': move.origin,
1562 'company_id': move.company_id and move.company_id.id or False,
1563 'move_type': move.group_id and move.group_id.move_type or 'one',
1564 'partner_id': move.group_id and move.group_id.partner_id and move.group_id.partner_id.id or False,
1565 'date_done': move.date_expected,
1566 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1568 pick = pick_obj.create(cr, uid, values, context=context)
1569 move.write({'picking_id': pick})
1572 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1573 """ On change of Scheduled Date gives a Move date.
1574 @param date_expected: Scheduled Date
1575 @param date: Move Date
1578 if not date_expected:
1579 date_expected = time.strftime('%Y-%m-%d %H:%M:%S')
1580 return {'value': {'date': date_expected}}
1582 def action_confirm(self, cr, uid, ids, context=None):
1583 """ Confirms stock move or put it in waiting if it's linked to another move.
1584 @return: List of ids.
1590 for move in self.browse(cr, uid, ids, context=context):
1592 for m in move.move_orig_ids:
1593 if m.state not in ('done', 'cancel'):
1595 states[state].append(move.id)
1596 self._picking_assign(cr, uid, move, context=context)
1598 for state, write_ids in states.items():
1600 self.write(cr, uid, write_ids, {'state': state})
1601 if state == 'confirmed':
1602 for move in self.browse(cr, uid, write_ids, context=context):
1603 if move.procure_method == 'make_to_order':
1604 self._create_procurement(cr, uid, move, context=context)
1605 moves = self.browse(cr, uid, ids, context=context)
1606 self._push_apply(cr, uid, moves, context=context)
1609 def force_assign(self, cr, uid, ids, context=None):
1610 """ Changes the state to assigned.
1613 self.action_assign(cr, uid, ids, context=context)
1614 self.write(cr, uid, ids, {'state': 'assigned'})
1617 def cancel_assign(self, cr, uid, ids, context=None):
1618 """ Changes the state to confirmed.
1621 return self.write(cr, uid, ids, {'state': 'confirmed'})
1623 def action_assign(self, cr, uid, ids, context=None):
1624 """ Checks the product type and accordingly writes the state.
1625 @return: No. of moves done
1627 context = context or {}
1628 quant_obj = self.pool.get("stock.quant")
1630 for move in self.browse(cr, uid, ids, context=context):
1631 if move.state not in ('confirmed', 'waiting', 'assigned'):
1633 if move.product_id.type == 'consu':
1634 done.append(move.id)
1637 #build the prefered domain based on quants that moved in previous linked done move
1639 for m2 in move.move_orig_ids:
1640 for q in m2.quant_ids:
1641 prev_quant_ids.append(q.id)
1642 prefered_domain = prev_quant_ids and [('id', 'in', prev_quant_ids)] or []
1643 fallback_domain = prev_quant_ids and [('id', 'not in', prev_quant_ids)] or []
1644 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
1645 main_domain = [('reservation_id', '=', False), ('qty', '>', 0)]
1646 #first try to find quants based on specific domains given by linked operations
1647 for record in move.linked_move_operation_ids:
1648 domain = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1649 qty_already_assigned = sum([q.qty for q in record.reserved_quant_ids])
1650 qty = record.qty - qty_already_assigned
1651 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=domain, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
1652 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
1653 #then if the move isn't totally assigned, try to find quants without any specific domain
1654 if move.state != 'assigned':
1655 qty_already_assigned = sum([q.qty for q in move.reserved_quant_ids])
1656 qty = move.product_qty - qty_already_assigned
1657 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
1658 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
1660 self._putaway_apply(cr, uid, ids, context=context)
1662 def action_cancel(self, cr, uid, ids, context=None):
1663 """ Cancels the moves and if all moves are cancelled it cancels the picking.
1666 procurement_obj = self.pool.get('procurement.order')
1667 context = context or {}
1668 for move in self.browse(cr, uid, ids, context=context):
1669 if move.state == 'done':
1670 raise osv.except_osv(_('Operation Forbidden!'),
1671 _('You cannot cancel a stock move that has been set to \'Done\'.'))
1672 if move.reserved_quant_ids:
1673 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
1674 if context.get('cancel_procurement'):
1676 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
1677 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
1678 elif move.move_dest_id:
1679 #cancel chained moves
1681 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
1682 elif move.move_dest_id.state == 'waiting':
1683 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'})
1684 return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1686 def action_done(self, cr, uid, ids, context=None):
1687 """ Makes the move done and if all moves are done, it will finish the picking.
1688 It assumes that quants are already assigned to stock moves.
1689 Putaway strategies should be applied
1692 context = context or {}
1693 quant_obj = self.pool.get("stock.quant")
1694 pack_op_obj = self.pool.get("stock.pack.operation")
1695 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
1697 self.action_confirm(cr, uid, todo, context=context)
1700 procurement_ids = []
1701 for move in self.browse(cr, uid, ids, context=context):
1703 pickings.add(move.picking_id.id)
1704 qty = move.product_qty
1705 main_domain = [('qty', '>', 0)]
1706 prefered_domain = [('reservation_id', '=', move.id)]
1707 fallback_domain = [('reservation_id', '=', False)]
1708 #first, process the move per linked operation first because it may imply some specific domains to consider
1709 for record in move.linked_move_operation_ids:
1710 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1711 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, record.qty, domain=dom, prefered_domain=prefered_domain, fallback_domain=fallback_domain, context=context)
1713 if not record.operation_id.package_id:
1714 #if a package and a result_package is given, we don't enter here because it will be processed by process_packaging() later
1715 #but for operations having only result_package_id, we will create new quants in the final package directly
1716 package_id = record.operation_id.result_package_id.id or False
1717 quant_obj.quants_move(cr, uid, quants, move, lot_id=record.operation_id.lot_id.id, owner_id=record.operation_id.owner_id.id, src_package_id=record.operation_id.package_id.id, dest_package_id=package_id, context=context)
1719 pack_op_obj.process_packaging(cr, uid, record.operation_id, quants, context=context)
1721 #then if the total quantity processed this way isn't enough, process the remaining quantity without any specific domain
1723 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain=prefered_domain, fallback_domain=fallback_domain, context=context)
1724 quant_obj.quants_move(cr, uid, quants, move, context=context)
1725 #unreserve the quants and make them available for other operations/moves
1726 quant_obj.quants_unreserve(cr, uid, move, context=context)
1728 #Check moves that were pushed
1729 if move.move_dest_id.state in ('waiting', 'confirmed'):
1730 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
1731 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
1732 #If no other moves for the move that got pushed:
1733 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
1734 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
1735 if move.procurement_id:
1736 procurement_ids.append(move.procurement_id.id)
1737 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1738 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
1741 def unlink(self, cr, uid, ids, context=None):
1742 context = context or {}
1743 for move in self.browse(cr, uid, ids, context=context):
1744 if move.state not in ('draft', 'cancel'):
1745 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
1746 return super(stock_move, self).unlink(cr, uid, ids, context=context)
1748 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1749 """ Move the scrap/damaged product into scrap location
1750 @param cr: the database cursor
1751 @param uid: the user id
1752 @param ids: ids of stock move object to be scrapped
1753 @param quantity : specify scrap qty
1754 @param location_id : specify scrap location
1755 @param context: context arguments
1756 @return: Scraped lines
1758 #quantity should be given in MOVE UOM
1760 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
1762 for move in self.browse(cr, uid, ids, context=context):
1763 source_location = move.location_id
1764 if move.state == 'done':
1765 source_location = move.location_dest_id
1766 #Previously used to prevent scraping from virtual location but not necessary anymore
1767 #if source_location.usage != 'internal':
1768 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
1769 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
1770 move_qty = move.product_qty
1771 uos_qty = quantity / move_qty * move.product_uos_qty
1773 'location_id': source_location.id,
1774 'product_uom_qty': quantity,
1775 'product_uos_qty': uos_qty,
1776 'state': move.state,
1778 'location_dest_id': location_id,
1779 #TODO lot_id is now on quant and not on move, need to do something for this
1780 #'lot_id': move.lot_id.id,
1782 new_move = self.copy(cr, uid, move.id, default_val)
1785 product_obj = self.pool.get('product.product')
1786 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
1788 uom = product.uom_id.name if product.uom_id else ''
1789 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
1790 move.picking_id.message_post(body=message)
1792 self.action_done(cr, uid, res, context=context)
1795 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
1796 """ Consumed product with specific quatity from specific source location
1797 @param cr: the database cursor
1798 @param uid: the user id
1799 @param ids: ids of stock move object to be consumed
1800 @param quantity : specify consume quantity
1801 @param location_id : specify source location
1802 @param context: context arguments
1803 @return: Consumed lines
1805 #quantity should be given in MOVE UOM
1809 raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
1811 for move in self.browse(cr, uid, ids, context=context):
1812 move_qty = move.product_qty
1814 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
1815 quantity_rest = move.product_qty
1816 quantity_rest -= quantity
1817 uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
1818 if quantity_rest <= 0:
1821 quantity = move.product_qty
1823 uos_qty = quantity / move_qty * move.product_uos_qty
1824 if quantity_rest > 0:
1826 'product_uom_qty': quantity,
1827 'product_uos_qty': uos_qty,
1828 'state': move.state,
1829 'location_id': location_id or move.location_id.id,
1831 current_move = self.copy(cr, uid, move.id, default_val)
1832 res += [current_move]
1834 update_val['product_uom_qty'] = quantity_rest
1835 update_val['product_uos_qty'] = uos_qty_rest
1836 self.write(cr, uid, [move.id], update_val)
1839 quantity_rest = quantity
1840 uos_qty_rest = uos_qty
1843 'product_uom_qty' : quantity_rest,
1844 'product_uos_qty' : uos_qty_rest,
1845 'location_id': location_id or move.location_id.id,
1847 self.write(cr, uid, [move.id], update_val)
1849 self.action_done(cr, uid, res, context=context)
1852 def split(self, cr, uid, move, qty, context=None):
1853 """ Splits qty from move move into a new move """
1854 if move.product_qty == qty:
1856 if (move.product_qty < qty) or (qty == 0):
1859 uom_obj = self.pool.get('product.uom')
1860 context = context or {}
1862 uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1863 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
1865 if move.state in ('done', 'cancel'):
1866 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
1869 'product_uom_qty': uom_qty,
1870 'product_uos_qty': uos_qty,
1871 'state': move.state,
1872 'move_dest_id': False,
1873 'reserved_quant_ids': []
1875 new_move = self.copy(cr, uid, move.id, defaults)
1877 self.write(cr, uid, [move.id], {
1878 'product_uom_qty': move.product_uom_qty - uom_qty,
1879 'product_uos_qty': move.product_uos_qty - uos_qty,
1880 #'reserved_quant_ids': [(6,0,[])] SHOULD NOT CHANGE as it has been reserved already
1883 if move.move_dest_id and move.propagate:
1884 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
1885 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
1887 self.action_confirm(cr, uid, [new_move], context=context)
1890 class stock_inventory(osv.osv):
1891 _name = "stock.inventory"
1892 _description = "Inventory"
1894 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
1896 for inv in self.browse(cr, uid, ids, context=context):
1902 def _get_available_filters(self, cr, uid, context=None):
1904 This function will return the list of filter allowed according to the options checked
1905 in 'Settings\Warehouse'.
1907 :rtype: list of tuple
1909 #default available choices
1910 res_filter = [('none', ' All products of a whole location'), ('product', 'One product only')]
1911 settings_obj = self.pool.get('stock.config.settings')
1912 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1913 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
1917 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1918 if stock_settings.group_stock_tracking_owner:
1919 res_filter.append(('owner', _('One owner only')))
1920 res_filter.append(('product_owner', _('One product for a specific owner')))
1921 if stock_settings.group_stock_production_lot:
1922 res_filter.append(('lot', _('One Lot/Serial Number')))
1923 if stock_settings.group_stock_tracking_lot:
1924 res_filter.append(('pack', _('A Pack')))
1928 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
1929 'date': fields.datetime('Inventory Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Create Date."),
1930 'date_done': fields.datetime('Date done', help="Inventory Validation Date."),
1931 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
1932 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves."),
1933 'state': fields.selection([('draft', 'Draft'), ('cancel', 'Cancelled'), ('confirm', 'In Progress'), ('done', 'Validated')], 'Status', readonly=True, select=True),
1934 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
1935 'location_id': fields.many2one('stock.location', 'Location', required=True),
1936 'product_id': fields.many2one('product.product', 'Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
1937 'package_id': fields.many2one('stock.quant.package', 'Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."),
1938 'partner_id': fields.many2one('res.partner', 'Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
1939 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number."),
1940 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
1941 'filter': fields.selection(_get_available_filters, 'Selection Filter'),
1944 def _default_stock_location(self, cr, uid, context=None):
1946 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
1947 return warehouse.lot_stock_id.id
1952 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1954 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
1955 'location_id': _default_stock_location,
1958 def set_checked_qty(self, cr, uid, ids, context=None):
1959 inventory = self.browse(cr, uid, ids[0], context=context)
1960 line_ids = [line.id for line in inventory.line_ids]
1961 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
1964 def copy(self, cr, uid, id, default=None, context=None):
1967 default = default.copy()
1968 default.update({'move_ids': [], 'date_done': False})
1969 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
1971 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
1972 """ Creates a stock move from an inventory line
1973 @param inventory_line:
1977 return self.pool.get('stock.move').create(cr, uid, move_vals)
1979 def action_done(self, cr, uid, ids, context=None):
1980 """ Finish the inventory
1985 move_obj = self.pool.get('stock.move')
1986 for inv in self.browse(cr, uid, ids, context=context):
1987 if not inv.move_ids:
1988 self.action_check(cr, uid, [inv.id], context=context)
1990 #the action_done on stock_move has to be done in 2 steps:
1991 #first, we start moving the products from stock to inventory loss
1992 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage == 'internal'], context=context)
1993 #then, we move from inventory loss. This 2 steps process is needed because some moved quant may need to be put again in stock
1994 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage != 'internal'], context=context)
1995 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
1998 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
1999 stock_move_obj = self.pool.get('stock.move')
2000 product_obj = self.pool.get('product.product')
2001 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2003 'name': _('INV:') + (inventory.name or ''),
2004 'product_id': todo_line['product_id'],
2005 'product_uom': todo_line['product_uom_id'],
2006 'date': inventory.date,
2007 'company_id': inventory.company_id.id,
2008 'inventory_id': inventory.id,
2009 'state': 'assigned',
2010 'restrict_lot_id': todo_line.get('prod_lot_id'),
2011 'restrict_partner_id': todo_line.get('partner_id'),
2014 if todo_line['product_qty'] < 0:
2015 #found more than expected
2016 vals['location_id'] = inventory_location_id
2017 vals['location_dest_id'] = todo_line['location_id']
2018 vals['product_uom_qty'] = -todo_line['product_qty']
2020 #found less than expected
2021 vals['location_id'] = todo_line['location_id']
2022 vals['location_dest_id'] = inventory_location_id
2023 vals['product_uom_qty'] = todo_line['product_qty']
2024 return stock_move_obj.create(cr, uid, vals, context=context)
2026 def action_check(self, cr, uid, ids, context=None):
2027 """ Checks the inventory and computes the stock move to do
2030 inventory_line_obj = self.pool.get('stock.inventory.line')
2031 stock_move_obj = self.pool.get('stock.move')
2032 for inventory in self.browse(cr, uid, ids, context=context):
2033 #first remove the existing stock moves linked to this inventory
2034 move_ids = [move.id for move in inventory.move_ids]
2035 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2036 #compute what should be in the inventory lines
2037 theorical_lines = self._get_inventory_lines(cr, uid, inventory, context=context)
2038 for line in inventory.line_ids:
2039 #compare the inventory lines to the theorical ones and store the diff in theorical_lines
2040 inventory_line_obj._resolve_inventory_line(cr, uid, line, theorical_lines, context=context)
2041 #each theorical_lines where product_qty is not 0 is a difference for which we need to create a stock move
2042 for todo_line in theorical_lines:
2043 if todo_line['product_qty'] != 0:
2044 self._create_stock_move(cr, uid, inventory, todo_line, context=context)
2046 def action_cancel_draft(self, cr, uid, ids, context=None):
2047 """ Cancels the stock move and change inventory state to draft.
2050 for inv in self.browse(cr, uid, ids, context=context):
2051 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2052 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2055 def action_cancel_inventory(self, cr, uid, ids, context=None):
2057 self.action_cancel_draft(cr, uid, ids, context=context)
2059 def prepare_inventory(self, cr, uid, ids, context=None):
2060 inventory_line_obj = self.pool.get('stock.inventory.line')
2061 for inventory in self.browse(cr, uid, ids, context=context):
2062 #clean the existing inventory lines before redoing an inventory proposal
2063 line_ids = [line.id for line in inventory.line_ids]
2064 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2065 #compute the inventory lines and create them
2066 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2067 for product_line in vals:
2068 inventory_line_obj.create(cr, uid, product_line, context=context)
2069 return self.write(cr, uid, ids, {'state': 'confirm'})
2071 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2072 location_obj = self.pool.get('stock.location')
2073 product_obj = self.pool.get('product.product')
2074 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2075 domain = ' location_id in %s'
2076 args = (tuple(location_ids),)
2077 if inventory.partner_id:
2078 domain += ' and owner_id = %s'
2079 args += (inventory.partner_id.id,)
2080 if inventory.lot_id:
2081 domain += ' and lot_id = %s'
2082 args += (inventory.lot_id.id,)
2083 if inventory.product_id:
2084 domain += 'and product_id = %s'
2085 args += (inventory.product_id.id,)
2086 if inventory.package_id:
2087 domain += ' and package_id = %s'
2088 args += (inventory.package_id.id,)
2090 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2091 FROM stock_quant WHERE''' + domain + '''
2092 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2095 for product_line in cr.dictfetchall():
2096 #replace the None the dictionary by False, because falsy values are tested later on
2097 for key, value in product_line.items():
2099 product_line[key] = False
2100 product_line['inventory_id'] = inventory.id
2101 product_line['th_qty'] = product_line['product_qty']
2102 if product_line['product_id']:
2103 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2104 product_line['product_uom_id'] = product.uom_id.id
2105 vals.append(product_line)
2108 class stock_inventory_line(osv.osv):
2109 _name = "stock.inventory.line"
2110 _description = "Inventory Line"
2111 _rec_name = "inventory_id"
2113 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2114 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2115 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2116 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2117 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2118 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2119 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2120 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2121 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2122 'th_qty': fields.float('Theoretical Quantity', readonly=True),
2123 'partner_id': fields.many2one('res.partner', 'Owner'),
2130 def _resolve_inventory_line(self, cr, uid, inventory_line, theorical_lines, context=None):
2131 #TODO : package_id management !
2133 uom_obj = self.pool.get('product.uom')
2134 for th_line in theorical_lines:
2135 #We try to match the inventory line with a theorical line with same product, lot, location and owner
2136 if th_line['location_id'] == inventory_line.location_id.id and th_line['product_id'] == inventory_line.product_id.id and th_line['prod_lot_id'] == inventory_line.prod_lot_id.id and th_line['partner_id'] == inventory_line.partner_id.id:
2137 uom_reference = inventory_line.product_id.uom_id
2138 real_qty = uom_obj._compute_qty_obj(cr, uid, inventory_line.product_uom_id, inventory_line.product_qty, uom_reference)
2139 th_line['product_qty'] -= real_qty
2142 #if it was still not found, we add it to the theorical lines so that it will create a stock move for it
2145 'inventory_id': inventory_line.inventory_id.id,
2146 'location_id': inventory_line.location_id.id,
2147 'product_id': inventory_line.product_id.id,
2148 'product_uom_id': inventory_line.product_id.uom_id.id,
2149 'product_qty': -inventory_line.product_qty,
2150 'prod_lot_id': inventory_line.prod_lot_id.id,
2151 'partner_id': inventory_line.partner_id.id,
2153 theorical_lines.append(vals)
2155 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, owner_id=False, lot_id=False, package_id=False, context=None):
2156 """ Changes UoM and name if product_id changes.
2157 @param location_id: Location id
2158 @param product: Changed product_id
2159 @param uom: UoM product
2160 @return: Dictionary of changed values
2162 context = context or {}
2164 return {'value': {'product_qty': 0.0, 'product_uom_id': False}}
2165 uom_obj = self.pool.get('product.uom')
2166 ctx = context.copy()
2167 ctx['location'] = location_id
2168 ctx['lot_id'] = lot_id
2169 ctx['owner_id'] = owner_id
2170 ctx['package_id'] = package_id
2171 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
2172 th_qty = obj_product.qty_available
2173 if uom and uom != obj_product.uom_id.id:
2174 uom_record = uom_obj.browse(cr, uid, uom, context=context)
2175 th_qty = uom_obj._compute_qty_obj(cr, uid, obj_product.uom_id, th_qty, uom_record)
2176 return {'value': {'th_qty': th_qty, 'product_uom_id': uom or obj_product.uom_id.id}}
2179 #----------------------------------------------------------
2181 #----------------------------------------------------------
2182 class stock_warehouse(osv.osv):
2183 _name = "stock.warehouse"
2184 _description = "Warehouse"
2187 'name': fields.char('Name', size=128, required=True, select=True),
2188 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2189 'partner_id': fields.many2one('res.partner', 'Address'),
2190 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2191 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2192 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2193 'route_ids': fields.many2many('stock.location.route', 'stock_route_warehouse', 'warehouse_id', 'route_id', 'Routes', domain="[('warehouse_selectable', '=', True)]", help='Defaults routes through the warehouse'),
2194 'reception_steps': fields.selection([
2195 ('one_step', 'Receive goods directly in stock (1 step)'),
2196 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2197 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', required=True),
2198 'delivery_steps': fields.selection([
2199 ('ship_only', 'Ship directly from stock (Ship only)'),
2200 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2201 ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings', required=True),
2202 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2203 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2204 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2205 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2206 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2207 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2208 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2209 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2210 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2211 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2212 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2213 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2214 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2215 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2216 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2217 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes'),
2218 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse'),
2221 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2222 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2223 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2224 resupply_wh_ids.add(default_resupply_wh_id)
2225 resupply_wh_ids = list(resupply_wh_ids)
2226 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2228 def _get_inter_wh_location(self, cr, uid, warehouse, context=None):
2229 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2230 data_obj = self.pool.get('ir.model.data')
2232 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2234 inter_wh_loc = False
2237 def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None):
2238 return self.pool.get('product.product').search(cr, uid, [], context=context)
2240 def _assign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2241 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2242 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2244 def _unassign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2245 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2246 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(3, inter_wh_route_id)]}, context=context)
2248 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2250 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2251 'warehouse_selectable': False,
2252 'product_selectable': True,
2253 'product_categ_selectable': True,
2254 'supplied_wh_id': warehouse.id,
2255 'supplier_wh_id': wh.id,
2258 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2259 location_obj = self.pool.get('stock.location')
2260 route_obj = self.pool.get('stock.location.route')
2261 pull_obj = self.pool.get('procurement.rule')
2262 #create route selectable on the product to resupply the warehouse from another one
2263 inter_wh_location_id = self._get_inter_wh_location(cr, uid, warehouse, context=context)
2264 if inter_wh_location_id:
2265 input_loc = warehouse.wh_input_stock_loc_id
2266 if warehouse.reception_steps == 'one_step':
2267 input_loc = warehouse.lot_stock_id
2268 inter_wh_location = location_obj.browse(cr, uid, inter_wh_location_id, context=context)
2269 for wh in supplier_warehouses:
2270 output_loc = wh.wh_output_stock_loc_id
2271 if wh.delivery_steps == 'ship_only':
2272 output_loc = wh.lot_stock_id
2273 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2274 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2275 values = [(output_loc, inter_wh_location, wh.out_type_id.id, wh), (inter_wh_location, input_loc, warehouse.in_type_id.id, warehouse)]
2276 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2277 for pull_rule in pull_rules_list:
2278 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2279 #if the warehouse is also set as default resupply method, assign this route automatically to all product
2280 if default_resupply_wh and default_resupply_wh.id == wh.id:
2281 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2282 #finally, save the route on the warehouse
2283 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2285 def _default_stock_id(self, cr, uid, context=None):
2286 #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2288 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2289 return warehouse.lot_stock_id.id
2294 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2295 'lot_stock_id': _default_stock_id,
2296 'reception_steps': 'one_step',
2297 'delivery_steps': 'ship_only',
2299 _sql_constraints = [
2300 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2301 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2302 ('default_resupply_wh_diff', 'check (id != default_resupply_wh_id)', 'The default resupply warehouse should be different that the warehouse itself!'),
2305 def _get_partner_locations(self, cr, uid, ids, context=None):
2306 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2307 data_obj = self.pool.get('ir.model.data')
2308 location_obj = self.pool.get('stock.location')
2310 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2311 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2313 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2314 customer_loc = customer_loc and customer_loc[0] or False
2315 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2316 supplier_loc = supplier_loc and supplier_loc[0] or False
2317 if not (customer_loc and supplier_loc):
2318 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2319 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2321 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2322 location_obj = self.pool.get('stock.location')
2324 new_reception_step = new_reception_step or warehouse.reception_steps
2325 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2326 if warehouse.reception_steps != new_reception_step:
2327 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2328 if new_reception_step != 'one_step':
2329 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2330 if new_reception_step == 'three_steps':
2331 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2333 if warehouse.delivery_steps != new_delivery_step:
2334 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2335 if new_delivery_step != 'ship_only':
2336 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2337 if new_delivery_step == 'pick_pack_ship':
2338 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2341 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2343 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2344 'product_categ_selectable': True,
2345 'product_selectable': False,
2349 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2350 pull_rules_list = []
2351 for from_loc, dest_loc, pick_type_id, warehouse in values:
2352 pull_rules_list.append({
2353 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2354 'location_src_id': from_loc.id,
2355 'location_id': dest_loc.id,
2356 'route_id': new_route_id,
2358 'picking_type_id': pick_type_id,
2359 'procure_method': 'make_to_order',
2360 'warehouse_id': supplied_warehouse.id,
2361 'propagate_warehouse_id': warehouse.id,
2363 return pull_rules_list
2365 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2367 push_rules_list = []
2368 pull_rules_list = []
2369 for from_loc, dest_loc, pick_type_id in values:
2370 push_rules_list.append({
2371 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2372 'location_from_id': from_loc.id,
2373 'location_dest_id': dest_loc.id,
2374 'route_id': new_route_id,
2376 'picking_type_id': pick_type_id,
2378 'warehouse_id': warehouse.id,
2380 pull_rules_list.append({
2381 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2382 'location_src_id': from_loc.id,
2383 'location_id': dest_loc.id,
2384 'route_id': new_route_id,
2386 'picking_type_id': pick_type_id,
2387 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2389 'warehouse_id': warehouse.id,
2392 return push_rules_list, pull_rules_list
2394 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2395 route_obj = self.pool.get('stock.location.route')
2396 data_obj = self.pool.get('ir.model.data')
2398 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2400 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('MTO'))], context=context)
2401 mto_route_id = mto_route_id and mto_route_id[0] or False
2402 if not mto_route_id:
2403 raise osv.except_osv(_('Error!'), _('Can\'t find any generic MTO route.'))
2405 from_loc, dest_loc, pick_type_id = values[0]
2407 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2408 'location_src_id': from_loc.id,
2409 'location_id': dest_loc.id,
2410 'route_id': mto_route_id,
2412 'picking_type_id': pick_type_id,
2413 'procure_method': 'make_to_order',
2415 'warehouse_id': warehouse.id,
2418 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2420 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2421 'warehouse_selectable': False,
2422 'product_selectable': True,
2423 'product_categ_selectable': True,
2424 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
2428 def create_routes(self, cr, uid, ids, warehouse, context=None):
2430 route_obj = self.pool.get('stock.location.route')
2431 pull_obj = self.pool.get('procurement.rule')
2432 push_obj = self.pool.get('stock.location.path')
2433 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2434 #create reception route and rules
2435 route_name, values = routes_dict[warehouse.reception_steps]
2436 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2437 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
2438 wh_route_ids.append((4, reception_route_id))
2439 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
2440 #create the push/pull rules
2441 for push_rule in push_rules_list:
2442 push_obj.create(cr, uid, vals=push_rule, context=context)
2443 for pull_rule in pull_rules_list:
2444 #all pull rules in reception route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
2445 pull_rule['procure_method'] = 'make_to_order'
2446 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2448 #create MTS route and pull rules for delivery a specific route MTO to be set on the product
2449 route_name, values = routes_dict[warehouse.delivery_steps]
2450 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2451 #create the route and its pull rules
2452 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
2453 wh_route_ids.append((4, delivery_route_id))
2454 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
2455 for pull_rule in pull_rules_list:
2456 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2457 #create MTO pull rule and link it to the generic MTO route
2458 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2459 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
2461 #create a route for cross dock operations, that can be set on products and product categories
2462 route_name, values = routes_dict['crossdock']
2463 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
2464 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
2465 wh_route_ids.append((4, crossdock_route_id))
2466 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step', values, crossdock_route_id, context=context)
2467 for pull_rule in pull_rules_list:
2468 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2470 #create route selectable on the product to resupply the warehouse from another one
2471 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
2473 #return routes and mto pull rule to store on the warehouse
2475 'route_ids': wh_route_ids,
2476 'mto_pull_id': mto_pull_id,
2477 'reception_route_id': reception_route_id,
2478 'delivery_route_id': delivery_route_id,
2479 'crossdock_route_id': crossdock_route_id,
2482 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2483 picking_type_obj = self.pool.get('stock.picking.type')
2484 pull_obj = self.pool.get('procurement.rule')
2485 push_obj = self.pool.get('stock.location.path')
2486 route_obj = self.pool.get('stock.location.route')
2487 new_reception_step = new_reception_step or warehouse.reception_steps
2488 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2490 #change the default source and destination location and (de)activate picking types
2491 input_loc = warehouse.wh_input_stock_loc_id
2492 if new_reception_step == 'one_step':
2493 input_loc = warehouse.lot_stock_id
2494 output_loc = warehouse.wh_output_stock_loc_id
2495 if new_delivery_step == 'ship_only':
2496 output_loc = warehouse.lot_stock_id
2497 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
2498 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
2499 picking_type_obj.write(cr, uid, warehouse.int_type_id.id, {'active': new_reception_step != 'one_step'}, context=context)
2500 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
2501 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
2503 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2504 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
2505 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
2506 route_name, values = routes_dict[new_delivery_step]
2507 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2508 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
2509 #create the pull rules
2510 for pull_rule in pull_rules_list:
2511 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2513 #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
2514 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
2515 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
2516 route_name, values = routes_dict[new_reception_step]
2517 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2518 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
2519 #create the push/pull rules
2520 for push_rule in push_rules_list:
2521 push_obj.create(cr, uid, vals=push_rule, context=context)
2522 for pull_rule in pull_rules_list:
2523 #all pull rules in reception route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
2524 pull_rule['procure_method'] = 'make_to_order'
2525 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2527 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
2530 dummy, values = routes_dict[new_delivery_step]
2531 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2532 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
2535 def create(self, cr, uid, vals, context=None):
2540 data_obj = self.pool.get('ir.model.data')
2541 seq_obj = self.pool.get('ir.sequence')
2542 picking_type_obj = self.pool.get('stock.picking.type')
2543 location_obj = self.pool.get('stock.location')
2545 #create view location for warehouse
2546 wh_loc_id = location_obj.create(cr, uid, {
2547 'name': _(vals.get('name')),
2549 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
2551 vals['view_location_id'] = wh_loc_id
2552 #create all location
2553 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
2554 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
2555 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
2556 context_with_inactive = context.copy()
2557 context_with_inactive['active_test'] = False
2559 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
2560 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
2561 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
2562 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
2563 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
2565 for values in sub_locations:
2566 location_id = location_obj.create(cr, uid, {
2567 'name': values['name'],
2568 'usage': 'internal',
2569 'location_id': wh_loc_id,
2570 'active': values['active'],
2571 }, context=context_with_inactive)
2572 vals[values['field']] = location_id
2574 #create new sequences
2575 in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence in'), 'prefix': vals.get('code', '') + '\IN\\', 'padding': 5}, context=context)
2576 out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence out'), 'prefix': vals.get('code', '') + '\OUT\\', 'padding': 5}, context=context)
2577 pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence packing'), 'prefix': vals.get('code', '') + '\PACK\\', 'padding': 5}, context=context)
2578 pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence picking'), 'prefix': vals.get('code', '') + '\PICK\\', 'padding': 5}, context=context)
2579 int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence internal'), 'prefix': vals.get('code', '') + '\INT\\', 'padding': 5}, context=context)
2582 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
2584 warehouse = self.browse(cr, uid, new_id, context=context)
2585 wh_stock_loc = warehouse.lot_stock_id
2586 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
2587 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
2588 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
2590 #fetch customer and supplier locations, for references
2591 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context)
2593 #create in, out, internal picking types for warehouse
2594 input_loc = wh_input_stock_loc
2595 if warehouse.reception_steps == 'one_step':
2596 input_loc = wh_stock_loc
2597 output_loc = wh_output_stock_loc
2598 if warehouse.delivery_steps == 'ship_only':
2599 output_loc = wh_stock_loc
2601 #choose the next available color for the picking types of this warehouse
2602 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
2603 not_used_colors = list(set(range(0, 9)) - set([x['color'] for x in all_used_colors]))
2606 color = not_used_colors[0]
2608 in_type_id = picking_type_obj.create(cr, uid, vals={
2609 'name': _('Receptions'),
2610 'warehouse_id': new_id,
2612 'auto_force_assign': True,
2613 'sequence_id': in_seq_id,
2614 'default_location_src_id': supplier_loc.id,
2615 'default_location_dest_id': input_loc.id,
2616 'color': color}, context=context)
2617 out_type_id = picking_type_obj.create(cr, uid, vals={
2618 'name': _('Delivery Orders'),
2619 'warehouse_id': new_id,
2621 'sequence_id': out_seq_id,
2623 'default_location_src_id': output_loc.id,
2624 'default_location_dest_id': customer_loc.id,
2625 'color': color}, context=context)
2626 int_type_id = picking_type_obj.create(cr, uid, vals={
2627 'name': _('Internal Transfers'),
2628 'warehouse_id': new_id,
2630 'sequence_id': int_seq_id,
2631 'default_location_src_id': wh_stock_loc.id,
2632 'default_location_dest_id': wh_stock_loc.id,
2633 'active': reception_steps != 'one_step',
2635 'color': color}, context=context)
2636 pack_type_id = picking_type_obj.create(cr, uid, vals={
2638 'warehouse_id': new_id,
2640 'sequence_id': pack_seq_id,
2641 'default_location_src_id': wh_pack_stock_loc.id,
2642 'default_location_dest_id': output_loc.id,
2643 'active': delivery_steps == 'pick_pack_ship',
2645 'color': color}, context=context)
2646 pick_type_id = picking_type_obj.create(cr, uid, vals={
2648 'warehouse_id': new_id,
2650 'sequence_id': pick_seq_id,
2651 'default_location_src_id': wh_stock_loc.id,
2652 'default_location_dest_id': wh_pack_stock_loc.id,
2653 'active': delivery_steps != 'ship_only',
2655 'color': color}, context=context)
2657 #write picking types on WH
2659 'in_type_id': in_type_id,
2660 'out_type_id': out_type_id,
2661 'pack_type_id': pack_type_id,
2662 'pick_type_id': pick_type_id,
2663 'int_type_id': int_type_id,
2665 super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context)
2668 #create routes and push/pull rules
2669 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
2670 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
2673 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
2674 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
2676 def _format_routename(self, cr, uid, obj, name, context=None):
2677 return obj.name + ': ' + name
2679 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
2680 #fetch customer and supplier locations, for references
2681 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
2684 'one_step': (_('Reception in 1 step'), []),
2685 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
2686 'three_steps': (_('Reception in 3 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_qc_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_qc_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
2687 'crossdock': (_('Cross-Dock'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
2688 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
2689 'pick_ship': (_('Pick + Ship'), [(warehouse.lot_stock_id, warehouse.wh_output_stock_loc_id, warehouse.pick_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
2690 'pick_pack_ship': (_('Pick + Pack + Ship'), [(warehouse.lot_stock_id, warehouse.wh_pack_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_pack_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.pack_type_id.id), (warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id.id)]),
2693 def _handle_renaming(self, cr, uid, warehouse, name, context=None):
2694 location_obj = self.pool.get('stock.location')
2695 route_obj = self.pool.get('stock.location.route')
2696 pull_obj = self.pool.get('procurement.rule')
2697 push_obj = self.pool.get('stock.location.path')
2699 location_id = warehouse.lot_stock_id.location_id.id
2700 location_obj.write(cr, uid, location_id, {'name': name}, context=context)
2701 #rename route and push-pull rules
2702 for route in warehouse.route_ids:
2703 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
2704 for pull in route.pull_ids:
2705 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2706 for push in route.push_ids:
2707 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2708 #change the mto pull rule name
2709 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
2711 def write(self, cr, uid, ids, vals, context=None):
2714 if isinstance(ids, (int, long)):
2716 seq_obj = self.pool.get('ir.sequence')
2717 route_obj = self.pool.get('stock.location.route')
2718 warehouse_obj = self.pool.get('stock.warehouse')
2720 context_with_inactive = context.copy()
2721 context_with_inactive['active_test'] = False
2722 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
2723 #first of all, check if we need to delete and recreate route
2724 if vals.get('reception_steps') or vals.get('delivery_steps'):
2725 #activate and deactivate location according to reception and delivery option
2726 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
2727 # switch between route
2728 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
2729 if vals.get('code') or vals.get('name'):
2730 name = warehouse.name
2732 if vals.get('name'):
2733 name = vals.get('name')
2734 self._handle_renaming(cr, uid, warehouse, name, context=context_with_inactive)
2735 seq_obj.write(cr, uid, warehouse.in_type_id.sequence_id.id, {'name': name + _(' Sequence in'), 'prefix': vals.get('code', warehouse.code) + '\IN\\'}, context=context)
2736 seq_obj.write(cr, uid, warehouse.out_type_id.sequence_id.id, {'name': name + _(' Sequence out'), 'prefix': vals.get('code', warehouse.code) + '\OUT\\'}, context=context)
2737 seq_obj.write(cr, uid, warehouse.pack_type_id.sequence_id.id, {'name': name + _(' Sequence packing'), 'prefix': vals.get('code', warehouse.code) + '\PACK\\'}, context=context)
2738 seq_obj.write(cr, uid, warehouse.pick_type_id.sequence_id.id, {'name': name + _(' Sequence picking'), 'prefix': vals.get('code', warehouse.code) + '\PICK\\'}, context=context)
2739 seq_obj.write(cr, uid, warehouse.int_type_id.sequence_id.id, {'name': name + _(' Sequence internal'), 'prefix': vals.get('code', warehouse.code) + '\INT\\'}, context=context)
2740 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
2741 for cmd in vals.get('resupply_wh_ids'):
2743 new_ids = set(cmd[2])
2744 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
2745 to_add_wh_ids = new_ids - old_ids
2747 supplier_warehouses = warehouse_obj.browse(cr, uid, list(to_add_wh_ids), context=context)
2748 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
2749 to_remove_wh_ids = old_ids - new_ids
2750 if to_remove_wh_ids:
2751 to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', 'in', list(to_remove_wh_ids))], context=context)
2752 if to_remove_route_ids:
2753 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
2757 if 'default_resupply_wh_id' in vals:
2758 if warehouse.default_resupply_wh_id:
2759 #remove the existing resupplying route on all products
2760 to_remove_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', warehouse.default_resupply_wh_id.id)], context=context)
2761 for inter_wh_route_id in to_remove_route_ids:
2762 self._unassign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2763 if vals.get('default_resupply_wh_id'):
2764 #assign the new resupplying route on all products
2765 to_assign_route_ids = route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id), ('supplier_wh_id', '=', vals.get('default_resupply_wh_id'))], context=context)
2766 for inter_wh_route_id in to_assign_route_ids:
2767 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2769 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
2771 def unlink(self, cr, uid, ids, context=None):
2772 #TODO try to delete location and route and if not possible, put them in inactive
2773 return super(stock_warehouse, self).unlink(cr, uid, ids, context=context)
2775 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
2776 all_routes = [route.id for route in warehouse.route_ids]
2777 all_routes += [warehouse.mto_pull_id.route_id.id]
2780 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
2782 for wh in self.browse(cr, uid, ids, context=context):
2783 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
2785 domain = [('id', 'in', all_routes)]
2787 'name': _('Warehouse\'s Routes'),
2789 'res_model': 'stock.location.route',
2790 'type': 'ir.actions.act_window',
2792 'view_mode': 'tree,form',
2793 'view_type': 'form',
2797 class stock_location_path(osv.osv):
2798 _name = "stock.location.path"
2799 _description = "Pushed Flows"
2802 def _get_route(self, cr, uid, ids, context=None):
2803 #WARNING TODO route_id is not required, so a field related seems a bad idea >-<
2809 context_with_inactive = context.copy()
2810 context_with_inactive['active_test'] = False
2811 for route in self.pool.get('stock.location.route').browse(cr, uid, ids, context=context_with_inactive):
2812 for push_rule in route.push_ids:
2813 result[push_rule.id] = True
2814 return result.keys()
2817 'name': fields.char('Operation Name', size=64, required=True),
2818 'company_id': fields.many2one('res.company', 'Company'),
2819 'route_id': fields.many2one('stock.location.route', 'Route'),
2820 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
2821 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
2822 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
2823 'invoice_state': fields.selection([
2824 ("invoiced", "Invoiced"),
2825 ("2binvoiced", "To Be Invoiced"),
2826 ("none", "Not Applicable")], "Invoice Status",
2828 'picking_type_id': fields.many2one('stock.picking.type', 'Type of the new Operation', required=True, help="This is the picking type associated with the different pickings"),
2829 'auto': fields.selection(
2830 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
2832 required=True, select=1,
2833 help="This is used to define paths the product has to follow within the location tree.\n" \
2834 "The 'Automatic Move' value will create a stock move after the current one that will be "\
2835 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
2836 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
2838 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when the previous move is cancelled or split, the move generated by this move will too'),
2839 'active': fields.related('route_id', 'active', type='boolean', string='Active', store={
2840 'stock.location.route': (_get_route, ['active'], 20),
2841 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 20),},
2842 help="If the active field is set to False, it will allow you to hide the rule without removing it." ),
2843 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
2848 'invoice_state': 'none',
2849 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
2853 def _apply(self, cr, uid, rule, move, context=None):
2854 move_obj = self.pool.get('stock.move')
2855 newdate = (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta.relativedelta(days=rule.delay or 0)).strftime('%Y-%m-%d')
2856 if rule.auto=='transparent':
2857 move_obj.write(cr, uid, [move.id], {
2859 'location_dest_id': rule.location_dest_id.id
2861 if rule.location_dest_id.id<>move.location_dest_id.id:
2862 move_obj._push_apply(self, cr, uid, move.id, context)
2865 move_id = move_obj.copy(cr, uid, move.id, {
2866 'location_id': move.location_dest_id.id,
2867 'location_dest_id': rule.location_dest_id.id,
2868 'date': datetime.now().strftime('%Y-%m-%d'),
2869 'company_id': rule.company_id and rule.company_id.id or False,
2870 'date_expected': newdate,
2871 'picking_id': False,
2872 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
2874 'propagate': rule.propagate,
2875 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
2877 move_obj.write(cr, uid, [move.id], {
2878 'move_dest_id': move_id,
2880 move_obj.action_confirm(cr, uid, [move_id], context=None)
2883 class stock_move_putaway(osv.osv):
2884 _name = 'stock.move.putaway'
2885 _description = 'Proposed Destination'
2887 'move_id': fields.many2one('stock.move', required=True),
2888 'location_id': fields.many2one('stock.location', 'Location', required=True),
2889 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
2890 'quantity': fields.float('Quantity', required=True),
2895 # -------------------------
2896 # Packaging related stuff
2897 # -------------------------
2899 from openerp.report import report_sxw
2900 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
2902 class stock_package(osv.osv):
2904 These are the packages, containing quants and/or other packages
2906 _name = "stock.quant.package"
2907 _description = "Physical Packages"
2908 _parent_name = "parent_id"
2909 _parent_store = True
2910 _parent_order = 'name'
2911 _order = 'parent_left'
2913 def name_get(self, cr, uid, ids, context=None):
2914 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
2917 def _complete_name(self, cr, uid, ids, name, args, context=None):
2918 """ Forms complete name of location from parent location to child location.
2919 @return: Dictionary of values
2922 for m in self.browse(cr, uid, ids, context=context):
2924 parent = m.parent_id
2926 res[m.id] = parent.name + ' / ' + res[m.id]
2927 parent = parent.parent_id
2930 def _get_packages(self, cr, uid, ids, context=None):
2931 """Returns packages from quants for store"""
2933 for quant in self.browse(cr, uid, ids, context=context):
2934 if quant.package_id:
2935 res.add(quant.package_id.id)
2938 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
2940 for pack in self.browse(cr, uid, ids, context=context):
2943 res.add(pack.parent_id.id)
2946 # TODO: Problem when package is empty!
2948 def _get_package_info(self, cr, uid, ids, name, args, context=None):
2949 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
2950 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id})
2951 for pack in self.browse(cr, uid, ids, context=context):
2953 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
2954 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
2955 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
2956 elif pack.children_ids:
2957 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
2958 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
2959 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
2963 'name': fields.char('Package Reference', size=64, select=True),
2964 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
2965 'parent_left': fields.integer('Left Parent', select=1),
2966 'parent_right': fields.integer('Right Parent', select=1),
2967 'packaging_id': fields.many2one('product.packaging', 'Type of Packaging'),
2968 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
2970 'stock.quant': (_get_packages, ['location_id'], 10),
2971 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
2973 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content'),
2974 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict'),
2975 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages'),
2976 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
2978 'stock.quant': (_get_packages, ['company_id'], 10),
2979 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
2981 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
2983 'stock.quant': (_get_packages, ['owner_id'], 10),
2984 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
2988 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
2990 def _check_location(self, cr, uid, ids, context=None):
2991 '''checks that all quants in a package are stored in the same location'''
2992 quant_obj = self.pool.get('stock.quant')
2993 for pack in self.browse(cr, uid, ids, context=context):
2995 while parent.parent_id:
2996 parent = parent.parent_id
2997 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
2998 quants = quant_obj.browse(cr, uid, quant_ids, context=context)
2999 location_id = quants and quants[0].location_id.id or False
3000 if not all([quant.location_id.id == location_id for quant in quants]):
3005 (_check_location, 'Everything inside a package should be in the same location', ['location_id']),
3008 def action_print(self, cr, uid, ids, context=None):
3012 'ids': context.get('active_id') and [context.get('active_id')] or ids,
3013 'model': 'stock.quant.package',
3014 'form': self.read(cr, uid, ids)[0]
3017 'type': 'ir.actions.report.xml',
3018 'report_name': 'stock.quant.package.barcode',
3022 def unpack(self, cr, uid, ids, context=None):
3023 quant_obj = self.pool.get('stock.quant')
3024 for package in self.browse(cr, uid, ids, context=context):
3025 quant_ids = [quant.id for quant in package.quant_ids]
3026 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3027 children_package_ids = [child_package.id for child_package in package.children_ids]
3028 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3029 #delete current package since it contains nothing anymore
3030 self.unlink(cr, uid, ids, context=context)
3031 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3033 def get_content(self, cr, uid, ids, context=None):
3034 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3035 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3037 def get_content_package(self, cr, uid, ids, context=None):
3038 quants_ids = self.get_content(cr, uid, ids, context=context)
3039 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3040 res['domain'] = [('id', 'in', quants_ids)]
3043 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3044 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3045 quant_obj = self.pool.get('stock.quant')
3046 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3048 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3049 if quant.product_id.id == product_id:
3053 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3054 '''This function computes the different product quantities for the given package
3056 quant_obj = self.pool.get('stock.quant')
3058 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3059 if quant.product_id.id not in res:
3060 res[quant.product_id.id] = 0
3061 res[quant.product_id.id] += quant.qty
3064 class stock_pack_operation(osv.osv):
3065 _name = "stock.pack.operation"
3066 _description = "Packing Operation"
3068 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3069 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3070 #if the operation doesn't concern a package, it's not relevant to call this function
3071 if not operation.package_id or operation.product_id:
3072 return {operation.product_id.id: operation.remaining_qty}
3073 #get the total of products the package contains
3074 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3075 #reduce by the quantities linked to a move
3076 for record in operation.linked_move_operation_ids:
3077 if record.move_id.product_id.id not in res:
3078 res[record.move_id.product_id.id] = 0
3079 res[record.move_id.product_id.id] -= record.qty
3082 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3083 uom_obj = self.pool.get('product.uom')
3085 for ops in self.browse(cr, uid, ids, context=context):
3088 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3089 #should use _get_remaining_prod_quantities instead
3091 elif ops.product_id:
3092 qty = ops.product_qty
3093 if ops.product_uom_id:
3094 qty = uom_obj._compute_qty(cr, uid, ops.product_uom_id.id, ops.product_qty, ops.product_id.uom_id.id)
3095 for record in ops.linked_move_operation_ids:
3097 #converting the remaining quantity in the pack operation UoM
3098 if ops.product_uom_id:
3099 qty = uom_obj._compute_qty(cr, uid, ops.product_id.uom_id.id, qty, ops.product_uom_id.id)
3103 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3104 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3105 if product_id and not product_uom_id:
3106 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3107 res['value']['product_uom_id'] = product.uom_id.id
3110 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3112 uom_obj = self.pool.get('product.uom')
3114 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3115 product_uom_id = product_uom_id or product.uom_id.id
3116 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3117 if selected_uom.category_id.id != product.uom_id.category_id.id:
3119 'title': _('Warning: wrong UoM!'),
3120 'message': _('The selected UoM for product %s is not compatible with the UoM set on the product form. \nPlease choose an UoM within the same UoM category.') % (product.name)
3122 if product_qty and 'warning' not in res:
3123 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3124 if rounded_qty != product_qty:
3126 'title': _('Warning: wrong quantity!'),
3127 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3132 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3133 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3134 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3135 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3136 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2
3137 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3138 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3139 'date': fields.datetime('Date', required=True),
3140 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3141 #'update_cost': fields.boolean('Need cost update'),
3142 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3143 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3144 'linked_move_operation_ids': fields.one2many('stock.move.operation.link', 'operation_id', string='Linked Moves', readonly=True, help='Moves impacted by this operation for the computation of the remaining quantities'),
3145 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3149 'date': fields.date.context_today,
3152 def process_packaging(self, cr, uid, operation, quants, context=None):
3153 ''' Process the packaging of a given operation, after the quants have been moved. If there was not enough quants found
3154 a quant already has been with the good package information so we don't consider that case in this method'''
3155 quant_obj = self.pool.get("stock.quant")
3156 pack_obj = self.pool.get("stock.quant.package")
3157 for quant, qty in quants:
3159 if operation.product_id:
3160 #if a product + a package information is given, we consider that we took a part of an existing package (unpacking)
3161 quant_obj.write(cr, uid, quant.id, {'package_id': operation.result_package_id.id}, context=context)
3162 elif operation.package_id and operation.result_package_id:
3163 #move the whole pack into the final package if any
3164 pack_obj.write(cr, uid, [operation.package_id.id], {'parent_id': operation.result_package_id.id}, context=context)
3169 #TODO: this function can be refactored
3170 def _search_and_increment(self, cr, uid, picking_id, domain, context=None):
3171 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3173 :param domain: list of tuple directly reusable as a domain
3174 context can receive a key 'current_package_id' with the package to consider for this operation
3177 previously: returns the update to do in stock.move one2many field of picking (adapt remaining quantities) and to the list of package in the classic one2many syntax
3178 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3179 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3180 (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
3185 #if current_package_id is given in the context, we increase the number of items in this package
3186 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3187 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3188 if existing_operation_ids:
3189 #existing operation found for the given domain and picking => increment its quantity
3190 operation_id = existing_operation_ids[0]
3191 qty = self.browse(cr, uid, operation_id, context=context).product_qty + 1
3192 self.write(cr, uid, operation_id, {'product_qty': qty}, context=context)
3194 #no existing operation found for the given domain and picking => create a new one
3196 'picking_id': picking_id,
3200 var_name, dummy, value = key
3202 if var_name == 'product_id':
3203 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3204 update_dict = {var_name: value}
3206 update_dict['product_uom_id'] = uom_id
3207 values.update(update_dict)
3208 operation_id = self.create(cr, uid, values, context=context)
3212 class stock_move_operation_link(osv.osv):
3214 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3216 _name = "stock.move.operation.link"
3217 _description = "Link between stock moves and pack operations"
3220 'qty': fields.float('Quantity', help="Quantity of products to consider when talking about the contribution of this pack operation towards the remaining quantity of the move (and inverse). Given in the product main uom."),
3221 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3222 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3223 'reserved_quant_ids': fields.one2many('stock.quant', 'link_move_operation_id', 'Reserved quants'),
3226 def get_specific_domain(self, cr, uid, record, context=None):
3227 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3228 having the record given as parameter making the link between the stock move and a pack operation'''
3229 package_obj = self.pool.get('stock.quant.package')
3231 op = record.operation_id
3234 domain.append(('id', 'in', package_obj.get_content(cr, uid, [op.package_id.id], context=context)))
3236 domain.append(('lot_id', '=', op.lot_id.id))
3238 domain.append(('owner_id', '=', op.owner_id.id))
3240 domain.append(('owner_id', '=', False))
3243 class stock_warehouse_orderpoint(osv.osv):
3245 Defines Minimum stock rules.
3247 _name = "stock.warehouse.orderpoint"
3248 _description = "Minimum Inventory Rule"
3250 def get_draft_procurements(self, cr, uid, ids, context=None):
3254 if not isinstance(ids, list):
3256 procurement_obj = self.pool.get('procurement.order')
3257 for orderpoint in self.browse(cr, uid, ids, context=context):
3258 procurement_ids = procurement_obj.search(cr, uid, [('state', 'not in', ('cancel', 'done')), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)], context=context)
3259 return list(set(procurement_ids))
3261 def _check_product_uom(self, cr, uid, ids, context=None):
3263 Check if the UoM has the same category as the product standard UoM
3268 for rule in self.browse(cr, uid, ids, context=context):
3269 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3274 def action_view_proc_to_process(self, cr, uid, ids, context=None):
3275 act_obj = self.pool.get('ir.actions.act_window')
3276 mod_obj = self.pool.get('ir.model.data')
3277 draft_ids = self.get_draft_procurements(cr, uid, ids, context=context)
3278 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3282 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3283 result['domain'] = "[('id', 'in', [" + ','.join(map(str, draft_ids)) + "])]"
3287 'name': fields.char('Name', size=32, required=True),
3288 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3289 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3290 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3291 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3292 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '!=', 'service')]),
3293 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
3294 'product_min_qty': fields.float('Minimum Quantity', required=True,
3295 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
3296 "a procurement to bring the forecasted quantity to the Max Quantity."),
3297 'product_max_qty': fields.float('Maximum Quantity', required=True,
3298 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
3299 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
3300 'qty_multiple': fields.integer('Qty Multiple', required=True,
3301 help="The procurement quantity will be rounded up to this multiple."),
3302 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
3303 'company_id': fields.many2one('res.company', 'Company', required=True)
3306 'active': lambda *a: 1,
3307 'logic': lambda *a: 'max',
3308 'qty_multiple': lambda *a: 1,
3309 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3310 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
3311 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
3313 _sql_constraints = [
3314 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
3317 (_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']),
3320 def default_get(self, cr, uid, fields, context=None):
3321 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
3322 # default 'warehouse_id' and 'location_id'
3323 if 'warehouse_id' not in res:
3324 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
3325 res['warehouse_id'] = warehouse.id
3326 if 'location_id' not in res:
3327 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
3328 res['location_id'] = warehouse.lot_stock_id.id
3331 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
3332 """ Finds location id for changed warehouse.
3333 @param warehouse_id: Changed id of warehouse.
3334 @return: Dictionary of values.
3337 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
3338 v = {'location_id': w.lot_stock_id.id}
3342 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
3343 """ Finds UoM for changed product.
3344 @param product_id: Changed id of product.
3345 @return: Dictionary of values.
3348 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3349 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
3350 v = {'product_uom': prod.uom_id.id}
3351 return {'value': v, 'domain': d}
3352 return {'domain': {'product_uom': []}}
3354 def copy(self, cr, uid, id, default=None, context=None):
3358 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3360 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
3363 class stock_picking_type(osv.osv):
3364 _name = "stock.picking.type"
3365 _description = "The picking type determines the picking view"
3367 def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
3368 """ Generic method to generate data for bar chart values using SparklineBarWidget.
3369 This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
3371 :param obj: the target model (i.e. crm_lead)
3372 :param domain: the domain applied to the read_group
3373 :param list read_fields: the list of fields to read in the read_group
3374 :param str value_field: the field used to compute the value of the bar slice
3375 :param str groupby_field: the fields used to group
3377 :return list section_result: a list of dicts: [
3378 { 'value': (int) bar_column_value,
3379 'tootip': (str) bar_column_tooltip,
3383 month_begin = date.today().replace(day=1)
3386 'tooltip': (month_begin + relativedelta.relativedelta(months=-i)).strftime('%B'),
3387 } for i in range(10, -1, -1)]
3388 group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
3389 for group in group_obj:
3390 group_begin_date = datetime.strptime(group['__domain'][0][2], tools.DEFAULT_SERVER_DATE_FORMAT)
3391 month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
3392 section_result[10 - (month_delta.months + 1)] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
3393 return section_result
3395 def _get_picking_data(self, cr, uid, ids, field_name, arg, context=None):
3396 obj = self.pool.get('stock.picking')
3397 res = dict.fromkeys(ids, False)
3398 month_begin = date.today().replace(day=1)
3399 groupby_begin = (month_begin + relativedelta.relativedelta(months=-4)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
3400 groupby_end = (month_begin + relativedelta.relativedelta(months=3)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
3403 ('picking_type_id', '=', id),
3404 ('state', 'not in', ['done', 'cancel']),
3405 ('date', '>=', groupby_begin),
3406 ('date', '<', groupby_end),
3408 res[id] = self.__get_bar_values(cr, uid, obj, created_domain, ['date'], 'picking_type_id_count', 'date', context=context)
3411 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
3412 obj = self.pool.get('stock.picking')
3414 'count_picking_draft': [('state', '=', 'draft')],
3415 'count_picking_waiting': [('state','=','confirmed')],
3416 'count_picking_ready': [('state','=','assigned')],
3417 'count_picking': [('state','in',('assigned','waiting','confirmed'))],
3418 'count_picking_late': [('min_date','<', time.strftime('%Y-%m-%d %H:%M:%S')), ('state','in',('assigned','waiting','confirmed'))],
3419 'count_picking_backorders': [('backorder_id','<>', False), ('state','!=','done')],
3422 for field in domains:
3423 data = obj.read_group(cr, uid, domains[field] +
3424 [('state', 'not in',('done','cancel')), ('picking_type_id', 'in', ids)],
3425 ['picking_type_id'], ['picking_type_id'], context=context)
3426 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
3428 result.setdefault(tid, {})[field] = count.get(tid, 0)
3430 if result[tid]['count_picking']:
3431 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] *100 / result[tid]['count_picking']
3432 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] *100 / (result[tid]['count_picking'] + result[tid]['count_picking_draft'])
3434 result[tid]['rate_picking_late'] = 0
3435 result[tid]['rate_picking_backorders'] = 0
3438 #TODO: not returning valus in required format to show in sparkline library,just added latest_picking_waiting need to add proper logic.
3439 def _get_picking_history(self, cr, uid, ids, field_names, arg, context=None):
3440 obj = self.pool.get('stock.picking')
3444 'latest_picking_late': [],
3445 'latest_picking_backorders': [],
3446 'latest_picking_waiting': []
3449 pick_ids = obj.search(cr, uid, [('state', '=','done'), ('picking_type_id','=',type_id)], limit=12, order="date desc", context=context)
3450 for pick in obj.browse(cr, uid, pick_ids, context=context):
3451 result[type_id]['latest_picking_late'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3452 result[type_id]['latest_picking_backorders'] = bool(pick.backorder_id)
3453 result[type_id]['latest_picking_waiting'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3456 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
3457 if not picking_code:
3460 obj_data = self.pool.get('ir.model.data')
3461 stock_loc = obj_data.get_object_reference(cr, uid, 'stock','stock_location_stock')[1]
3464 'default_location_src_id': stock_loc,
3465 'default_location_dest_id': stock_loc,
3467 if picking_code == 'incoming':
3468 result['default_location_src_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_suppliers')[1]
3469 return {'value': result}
3470 if picking_code == 'outgoing':
3471 result['default_location_dest_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_customers')[1]
3472 return {'value': result}
3474 return {'value': result}
3476 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
3477 return dict(self.name_get(cr, uid, ids, context=context))
3479 def name_get(self, cr, uid, ids, context=None):
3480 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
3483 if not isinstance(ids, list):
3488 for record in self.browse(cr, uid, ids, context=context):
3490 if record.warehouse_id:
3491 name = record.warehouse_id.name + ': ' +name
3492 if context.get('special_shortened_wh_name'):
3493 if record.warehouse_id:
3494 name = record.warehouse_id.name
3496 name = _('Customer') + ' (' + record.name + ')'
3497 res.append((record.id, name))
3500 def _default_warehouse(self, cr, uid, context=None):
3501 user = self.pool.get('res.users').browse(cr, uid, uid, context)
3502 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
3503 return res and res[0] or False
3506 'name': fields.char('Name', translate=True, required=True),
3507 'complete_name': fields.function(_get_name, type='char', string='Name'),
3508 'pack': fields.boolean('Prefill Pack Operations', help='This picking type needs packing interface'),
3509 'auto_force_assign': fields.boolean('Automatic Availability', help='This picking type does\'t need to check for the availability in source location.'),
3510 'color': fields.integer('Color'),
3511 'delivery': fields.boolean('Print delivery'),
3512 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
3513 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
3514 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
3515 #TODO: change field name to "code" as it's not a many2one anymore
3516 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Picking type code', required=True),
3517 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
3518 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
3519 'active': fields.boolean('Active'),
3521 # Statistics for the kanban view
3522 'weekly_picking': fields.function(_get_picking_data,
3524 string='Scheduled pickings per week'),
3526 'count_picking_draft': fields.function(_get_picking_count,
3527 type='integer', multi='_get_picking_count'),
3528 'count_picking_ready': fields.function(_get_picking_count,
3529 type='integer', multi='_get_picking_count'),
3530 'count_picking': fields.function(_get_picking_count,
3531 type='integer', multi='_get_picking_count'),
3532 'count_picking_waiting': fields.function(_get_picking_count,
3533 type='integer', multi='_get_picking_count'),
3534 'count_picking_late': fields.function(_get_picking_count,
3535 type='integer', multi='_get_picking_count'),
3536 'count_picking_backorders': fields.function(_get_picking_count,
3537 type='integer', multi='_get_picking_count'),
3539 'rate_picking_late': fields.function(_get_picking_count,
3540 type='integer', multi='_get_picking_count'),
3541 'rate_picking_backorders': fields.function(_get_picking_count,
3542 type='integer', multi='_get_picking_count'),
3544 'latest_picking_late': fields.function(_get_picking_history,
3545 type='string', multi='_get_picking_history'),
3546 'latest_picking_backorders': fields.function(_get_picking_history,
3547 type='string', multi='_get_picking_history'),
3548 'latest_picking_waiting': fields.function(_get_picking_history,
3549 type='string', multi='_get_picking_history'),
3553 'warehouse_id': _default_warehouse,
3558 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: