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.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
30 from openerp import SUPERUSER_ID, api
31 import openerp.addons.decimal_precision as dp
32 from openerp.addons.procurement import procurement
36 _logger = logging.getLogger(__name__)
37 #----------------------------------------------------------
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41 _name = "stock.incoterms"
42 _description = "Incoterms"
44 'name': fields.char('Name', 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 _location_owner(self, cr, uid, location, context=None):
66 ''' Return the company owning the location if any '''
67 return location and (location.usage == 'internal') and location.company_id or False
69 def _complete_name(self, cr, uid, ids, name, args, context=None):
70 """ Forms complete name of location from parent location to child location.
71 @return: Dictionary of values
74 for m in self.browse(cr, uid, ids, context=context):
76 parent = m.location_id
78 res[m.id] = parent.name + ' / ' + res[m.id]
79 parent = parent.location_id
82 def _get_sublocations(self, cr, uid, ids, context=None):
83 """ return all sublocations of the given stock locations (included) """
86 context_with_inactive = context.copy()
87 context_with_inactive['active_test'] = False
88 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
90 def _name_get(self, cr, uid, location, context=None):
92 while location.location_id and location.usage != 'view':
93 location = location.location_id
94 name = location.name + '/' + name
97 def name_get(self, cr, uid, ids, context=None):
99 for location in self.browse(cr, uid, ids, context=context):
100 res.append((location.id, self._name_get(cr, uid, location, context=context)))
104 'name': fields.char('Location Name', required=True, translate=True),
105 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
106 'usage': fields.selection([
107 ('supplier', 'Supplier Location'),
109 ('internal', 'Internal Location'),
110 ('customer', 'Customer Location'),
111 ('inventory', 'Inventory'),
112 ('procurement', 'Procurement'),
113 ('production', 'Production'),
114 ('transit', 'Transit Location')],
115 'Location Type', required=True,
116 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
117 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
118 \n* Internal Location: Physical locations inside your own warehouses,
119 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
120 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
121 \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.
122 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
123 \n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations
125 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
126 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
127 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
128 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
130 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
132 'comment': fields.text('Additional Information'),
133 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
134 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
135 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
137 'parent_left': fields.integer('Left Parent', select=1),
138 'parent_right': fields.integer('Right Parent', select=1),
140 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
141 'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
142 'removal_strategy_id': fields.many2one('product.removal', 'Removal Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to take the products from, which lot etc. for this location. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
143 'putaway_strategy_id': fields.many2one('product.putaway', 'Put Away Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to store the products. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
144 'loc_barcode': fields.char('Location Barcode'),
149 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
153 'scrap_location': False,
155 _sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')]
157 def create(self, cr, uid, default, context=None):
158 if not default.get('loc_barcode', False):
159 default.update({'loc_barcode': default.get('complete_name', False)})
160 return super(stock_location, self).create(cr, uid, default, context=context)
162 def get_putaway_strategy(self, cr, uid, location, product, context=None):
163 ''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.'''
164 putaway_obj = self.pool.get('product.putaway')
167 if loc.putaway_strategy_id:
168 res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context)
171 loc = loc.location_id
173 def _default_removal_strategy(self, cr, uid, context=None):
176 def get_removal_strategy(self, cr, uid, location, product, context=None):
177 ''' Returns the removal strategy to consider for the given product and location.
178 :param location: browse record (stock.location)
179 :param product: browse record (product.product)
182 if product.categ_id.removal_strategy_id:
183 return product.categ_id.removal_strategy_id.method
186 if loc.removal_strategy_id:
187 return loc.removal_strategy_id.method
188 loc = loc.location_id
189 return self._default_removal_strategy(cr, uid, context=context)
192 def get_warehouse(self, cr, uid, location, context=None):
194 Returns warehouse id of warehouse that contains location
195 :param location: browse record (stock.location)
197 wh_obj = self.pool.get("stock.warehouse")
198 whs = wh_obj.search(cr, uid, [('view_location_id.parent_left', '<=', location.parent_left),
199 ('view_location_id.parent_right', '>=', location.parent_left)], context=context)
200 return whs and whs[0] or False
202 #----------------------------------------------------------
204 #----------------------------------------------------------
206 class stock_location_route(osv.osv):
207 _name = 'stock.location.route'
208 _description = "Inventory Routes"
212 'name': fields.char('Route Name', required=True),
213 'sequence': fields.integer('Sequence'),
214 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules', copy=True),
215 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
216 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules', copy=True),
217 'product_selectable': fields.boolean('Applicable on Product'),
218 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
219 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
220 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
221 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
222 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
226 'sequence': lambda self, cr, uid, ctx: 0,
228 'product_selectable': True,
229 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
232 def write(self, cr, uid, ids, vals, context=None):
233 '''when a route is deactivated, deactivate also its pull and push rules'''
234 if isinstance(ids, (int, long)):
236 res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context)
240 for route in self.browse(cr, uid, ids, context=context):
242 push_ids += [r.id for r in route.push_ids if r.active != vals['active']]
244 pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']]
246 self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context)
248 self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context)
251 #----------------------------------------------------------
253 #----------------------------------------------------------
255 class stock_quant(osv.osv):
257 Quants are the smallest unit of stock physical instances
259 _name = "stock.quant"
260 _description = "Quants"
262 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
263 """ Forms complete name of location from parent location to child location.
264 @return: Dictionary of values
267 for q in self.browse(cr, uid, ids, context=context):
269 res[q.id] = q.product_id.code or ''
271 res[q.id] = q.lot_id.name
272 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
275 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
276 context = dict(context or {})
278 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
279 for quant in self.browse(cr, uid, ids, context=context):
280 context.pop('force_company', None)
281 if quant.company_id.id != uid_company_id:
282 #if the company of the quant is different than the current user company, force the company in the context
283 #then re-do a browse to read the property fields for the good company.
284 context['force_company'] = quant.company_id.id
285 quant = self.browse(cr, uid, quant.id, context=context)
286 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
289 def _get_inventory_value(self, cr, uid, quant, context=None):
290 return quant.product_id.standard_price * quant.qty
293 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
294 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict", readonly=True, select=True),
295 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict", readonly=True, select=True),
296 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product", readonly=True, select=True),
297 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant", readonly=True, select=True),
298 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', readonly=True, store=True),
299 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for", readonly=True, select=True),
300 'lot_id': fields.many2one('stock.production.lot', 'Lot', readonly=True, select=True),
301 'cost': fields.float('Unit Cost'),
302 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant", readonly=True, select=True),
304 'create_date': fields.datetime('Creation Date', readonly=True),
305 'in_date': fields.datetime('Incoming Date', readonly=True, select=True),
307 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
308 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True, readonly=True, select=True),
309 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
311 # Used for negative quants to reconcile after compensated by a new positive one
312 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from', readonly=True, select=True),
313 'negative_move_id': fields.many2one('stock.move', 'Move Negative Quant', help='If this is a negative quant, this will be the move that caused this negative quant.', readonly=True),
314 'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", readonly=True,
315 help="Technical field used to record the destination location of a move that created a negative quant"),
319 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
322 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
323 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
324 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
325 if 'inventory_value' in fields:
327 if '__domain' in line:
328 lines = self.search(cr, uid, line['__domain'], context=context)
330 for line2 in self.browse(cr, uid, lines, context=context):
331 inv_value += line2.inventory_value
332 line['inventory_value'] = inv_value
335 def action_view_quant_history(self, cr, uid, ids, context=None):
337 This function returns an action that display the history of the quant, which
338 mean all the stock moves that lead to this quant creation with this quant quantity.
340 mod_obj = self.pool.get('ir.model.data')
341 act_obj = self.pool.get('ir.actions.act_window')
343 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
344 id = result and result[1] or False
345 result = act_obj.read(cr, uid, [id], context={})[0]
348 for quant in self.browse(cr, uid, ids, context=context):
349 move_ids += [move.id for move in quant.history_ids]
351 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
354 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
355 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
356 is also set to 'assigned'
358 :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. Negative quants should not be received as argument
359 :param move: browse record
360 :param link: browse record (stock.move.operation.link)
363 reserved_availability = move.reserved_availability
364 #split quants if needed
365 for quant, qty in quants:
366 if qty <= 0.0 or (quant and quant.qty <= 0.0):
367 raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
370 self._quant_split(cr, uid, quant, qty, context=context)
371 toreserve.append(quant.id)
372 reserved_availability += quant.qty
375 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
376 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
378 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
379 #check if move'state needs to be set as 'assigned'
380 if reserved_availability == move.product_qty and move.state in ('confirmed', 'waiting'):
381 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
382 elif reserved_availability > 0 and not move.partially_available:
383 self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
385 def quants_move(self, cr, uid, quants, move, location_to, location_from=False, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
386 """Moves all given stock.quant in the given destination location.
387 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
388 :param move: browse record (stock.move)
389 :param location_to: browse record (stock.location) depicting where the quants have to be moved
390 :param location_from: optional browse record (stock.location) explaining where the quant has to be taken (may differ from the move source location in case a removal strategy applied). This parameter is only used to pass to _quant_create if a negative quant must be created
391 :param lot_id: ID of the lot that must be set on the quants to move
392 :param owner_id: ID of the partner that must own the quants to move
393 :param src_package_id: ID of the package that contains the quants to move
394 :param dest_package_id: ID of the package that must be set on the moved quant
396 quants_reconcile = []
398 self._check_location(cr, uid, location_to, context=context)
399 for quant, qty in quants:
401 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
402 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, force_location_from=location_from, force_location_to=location_to, context=context)
404 self._quant_split(cr, uid, quant, qty, context=context)
406 to_move_quants.append(quant)
407 quants_reconcile.append(quant)
409 to_recompute_move_ids = [x.reservation_id.id for x in to_move_quants if x.reservation_id and x.reservation_id.id != move.id]
410 self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
411 self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context)
412 if location_to.usage == 'internal':
413 if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context):
414 for quant in quants_reconcile:
416 self._quant_reconcile_negative(cr, uid, quant, move, context=context)
418 def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
419 vals = {'location_id': location_dest_id.id,
420 'history_ids': [(4, move.id)],
421 'package_id': dest_package_id}
422 self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
424 def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain_list=[], restrict_lot_id=False, restrict_partner_id=False, context=None):
425 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
426 the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached
427 it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on).
428 Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal
432 quants = [(None, qty)]
433 #don't look for quants in location that are of type production, supplier or inventory.
434 if location.usage in ['inventory', 'production', 'supplier']:
437 if not prefered_domain_list:
438 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)
439 for prefered_domain in prefered_domain_list:
441 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
443 tmp_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
444 for quant in tmp_quants:
450 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
452 Use the removal strategies of product to search for the correct quants
453 If you inherit, put the super at the end of your method.
455 :location: browse record of the parent location where the quants have to be found
456 :product: browse record of the product to find
457 :qty in UoM of product
460 domain = domain or [('qty', '>', 0.0)]
461 if restrict_partner_id:
462 domain += [('owner_id', '=', restrict_partner_id)]
464 domain += [('lot_id', '=', restrict_lot_id)]
466 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context)
467 result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context)
470 def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None):
471 if removal_strategy == 'fifo':
472 order = 'in_date, id'
473 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
474 elif removal_strategy == 'lifo':
475 order = 'in_date desc, id desc'
476 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
477 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
479 def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False,
480 force_location_from=False, force_location_to=False, context=None):
481 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
485 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
486 location = force_location_to or move.location_dest_id
488 'product_id': move.product_id.id,
489 'location_id': location.id,
492 'history_ids': [(4, move.id)],
493 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
494 'company_id': move.company_id.id,
496 'owner_id': owner_id,
497 'package_id': dest_package_id,
500 if move.location_id.usage == 'internal':
501 #if we were trying to move something from an internal location and reach here (quant creation),
502 #it means that a negative quant has to be created as well.
503 negative_vals = vals.copy()
504 negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id
505 negative_vals['qty'] = -qty
506 negative_vals['cost'] = price_unit
507 negative_vals['negative_move_id'] = move.id
508 negative_vals['package_id'] = src_package_id
509 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
510 vals.update({'propagated_from_id': negative_quant_id})
512 #create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants
513 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
514 return self.browse(cr, uid, quant_id, context=context)
516 def _quant_split(self, cr, uid, quant, qty, context=None):
517 context = context or {}
518 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
520 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
521 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
523 return self.browse(cr, uid, new_quant, context=context)
525 def _get_latest_move(self, cr, uid, quant, context=None):
527 for m in quant.history_ids:
528 if not move or m.date > move.date:
532 @api.cr_uid_ids_context
533 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
535 for move in solving_quant.history_ids:
536 path.append((4, move.id))
537 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
539 def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
541 When new quant arrive in a location, try to reconcile it with
542 negative quants. If it's possible, apply the cost of the new
543 quant to the conter-part of the negative quant.
545 solving_quant = quant
546 dom = [('qty', '<', 0)]
548 dom += [('lot_id', '=', quant.lot_id.id)]
549 dom += [('owner_id', '=', quant.owner_id.id)]
550 dom += [('package_id', '=', quant.package_id.id)]
551 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
552 for quant_neg, qty in quants:
555 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
556 if not to_solve_quant_ids:
559 solved_quant_ids = []
560 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
563 solved_quant_ids.append(to_solve_quant.id)
564 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
565 solving_qty -= min(solving_qty, to_solve_quant.qty)
566 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
567 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
568 #if the reconciliation was not complete, we need to link together the remaining parts
569 if remaining_neg_quant:
570 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
571 if remaining_to_solve_quant_ids:
572 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
573 #delete the reconciled quants, as it is replaced by the solved quants
574 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
575 #price update + accounting entries adjustments
576 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
577 #merge history (and cost?)
578 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
579 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
580 solving_quant = remaining_solving_quant
582 def _price_update(self, cr, uid, ids, newprice, context=None):
583 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
585 def quants_unreserve(self, cr, uid, move, context=None):
586 related_quants = [x.id for x in move.reserved_quant_ids]
588 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
590 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
591 if move.partially_available:
592 self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
593 self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
595 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
596 ''' Implementation of removal strategies
597 If it can not reserve, it will return a tuple (None, qty)
601 domain += location and [('location_id', 'child_of', location.id)] or []
602 domain += [('product_id', '=', product.id)]
603 if context.get('force_company'):
604 domain += [('company_id', '=', context.get('force_company'))]
606 domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
610 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
612 res.append((None, quantity))
614 for quant in self.browse(cr, uid, quants, context=context):
615 if quantity >= abs(quant.qty):
616 res += [(quant, abs(quant.qty))]
617 quantity -= abs(quant.qty)
619 res += [(quant, quantity)]
625 def _check_location(self, cr, uid, location, context=None):
626 if location.usage == 'view':
627 raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
630 #----------------------------------------------------------
632 #----------------------------------------------------------
634 class stock_picking(osv.osv):
635 _name = "stock.picking"
636 _inherit = ['mail.thread']
637 _description = "Picking List"
638 _order = "priority desc, date asc, id desc"
640 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
641 move_obj = self.pool.get("stock.move")
643 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
644 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
646 def _set_priority(self, cr, uid, id, field, value, arg, context=None):
647 move_obj = self.pool.get("stock.move")
649 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
650 move_obj.write(cr, uid, move_ids, {'priority': value}, context=context)
652 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
653 """ Finds minimum and maximum dates for picking.
654 @return: Dictionary of values
658 res[id] = {'min_date': False, 'max_date': False, 'priority': '1'}
671 picking_id""", (tuple(ids),))
672 for pick, dt1, dt2, prio in cr.fetchall():
673 res[pick]['min_date'] = dt1
674 res[pick]['max_date'] = dt2
675 res[pick]['priority'] = prio
678 def create(self, cr, user, vals, context=None):
679 context = context or {}
680 if ('name' not in vals) or (vals.get('name') in ('/', False)):
681 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
682 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
683 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
684 return super(stock_picking, self).create(cr, user, vals, context)
686 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
687 '''The state of a picking depends on the state of its related stock.move
688 draft: the picking has no line or any one of the lines is draft
689 done, draft, cancel: all lines are done / draft / cancel
690 confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial)
693 for pick in self.browse(cr, uid, ids, context=context):
694 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
695 res[pick.id] = 'draft'
697 if all([x.state == 'cancel' for x in pick.move_lines]):
698 res[pick.id] = 'cancel'
700 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
701 res[pick.id] = 'done'
704 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
705 order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
706 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
707 if pick.move_type == 'one':
708 res[pick.id] = order_inv[min(lst)]
710 #we are in the case of partial delivery, so if all move are assigned, picking
711 #should be assign too, else if one of the move is assigned, or partially available, picking should be
712 #in partially available state, otherwise, picking is in waiting or confirmed state
713 res[pick.id] = order_inv[max(lst)]
714 if not all(x == 2 for x in lst):
715 if any(x == 2 for x in lst):
716 res[pick.id] = 'partially_available'
718 #if all moves aren't assigned, check if we have one product partially available
719 for move in pick.move_lines:
720 if move.partially_available:
721 res[pick.id] = 'partially_available'
725 def _get_pickings(self, cr, uid, ids, context=None):
727 for move in self.browse(cr, uid, ids, context=context):
729 res.add(move.picking_id.id)
732 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
734 for pick in self.browse(cr, uid, ids, context=context):
736 if pick.pack_operation_ids:
740 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
742 for pick in self.browse(cr, uid, ids, context=context):
744 for move in pick.move_lines:
745 if move.reserved_quant_ids:
750 def check_group_lot(self, cr, uid, context=None):
751 """ This function will return true if we have the setting to use lots activated. """
752 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot')
754 def check_group_pack(self, cr, uid, context=None):
755 """ This function will return true if we have the setting to use package activated. """
756 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot')
758 def action_assign_owner(self, cr, uid, ids, context=None):
759 for picking in self.browse(cr, uid, ids, context=context):
760 packop_ids = [op.id for op in picking.pack_operation_ids]
761 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
764 'name': fields.char('Reference', select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
765 'origin': fields.char('Source Document', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
766 '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, copy=False),
767 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
768 '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"),
769 'state': fields.function(_state_get, type="selection", copy=False,
771 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
772 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)},
775 ('cancel', 'Cancelled'),
776 ('waiting', 'Waiting Another Operation'),
777 ('confirmed', 'Waiting Availability'),
778 ('partially_available', 'Partially Available'),
779 ('assigned', 'Ready to Transfer'),
780 ('done', 'Transferred'),
781 ], string='Status', readonly=True, select=True, track_visibility='onchange',
783 * Draft: not confirmed yet and will not be scheduled until confirmed\n
784 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
785 * Waiting Availability: still waiting for the availability of products\n
786 * Partially Available: some products are available and reserved\n
787 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
788 * Transferred: has been processed, can't be modified or cancelled anymore\n
789 * Cancelled: has been cancelled, can't be confirmed anymore"""
791 'priority': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_priority, type='selection', selection=procurement.PROCUREMENT_PRIORITIES, string='Priority',
792 store={'stock.move': (_get_pickings, ['priority', 'picking_id'], 20)}, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, select=1, help="Priority for this picking. Setting manually a value here would set it as priority for all the moves",
793 track_visibility='onchange', required=True),
794 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
795 store={'stock.move': (_get_pickings, ['date_expected', 'picking_id'], 20)}, type='datetime', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.", track_visibility='onchange'),
796 'max_date': fields.function(get_min_max_date, multi="min_max_date",
797 store={'stock.move': (_get_pickings, ['date_expected', 'picking_id'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
798 'date': fields.datetime('Creation Date', help="Creation Date, usually the time of the order", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, track_visibility='onchange'),
799 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
800 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=True),
801 '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'),
802 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
803 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
804 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
805 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
806 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
807 'picking_type_code': fields.related('picking_type_id', 'code', type='char', string='Picking Type Code', help="Technical field used to display the correct label on print button in the picking view"),
809 'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
810 # Used to search on pickings
811 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
812 'recompute_pack_op': fields.boolean('Recompute pack operation?', help='True if reserved quants changed, which mean we might need to recompute the package operations', copy=False),
813 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
814 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
815 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
817 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
818 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
825 'move_type': 'direct',
826 'priority': '1', # normal
827 'date': fields.datetime.now,
828 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c),
829 'recompute_pack_op': True,
832 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
835 def do_print_picking(self, cr, uid, ids, context=None):
836 '''This function prints the picking list'''
837 context = dict(context or {}, active_ids=ids)
838 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
841 def action_confirm(self, cr, uid, ids, context=None):
843 todo_force_assign = []
844 for picking in self.browse(cr, uid, ids, context=context):
845 if picking.location_id.usage in ('supplier', 'inventory', 'production'):
846 todo_force_assign.append(picking.id)
847 for r in picking.move_lines:
848 if r.state == 'draft':
851 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
853 if todo_force_assign:
854 self.force_assign(cr, uid, todo_force_assign, context=context)
857 def action_assign(self, cr, uid, ids, context=None):
858 """ Check availability of picking moves.
859 This has the effect of changing the state and reserve quants on available moves, and may
860 also impact the state of the picking as it is computed based on move's states.
863 for pick in self.browse(cr, uid, ids, context=context):
864 if pick.state == 'draft':
865 self.action_confirm(cr, uid, [pick.id], context=context)
867 #skip the moves that don't need to be checked
868 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
870 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
871 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
874 def force_assign(self, cr, uid, ids, context=None):
875 """ Changes state of picking to available if moves are confirmed or waiting.
878 for pick in self.browse(cr, uid, ids, context=context):
879 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
880 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
881 #pack_operation might have changed and need to be recomputed
882 self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context)
885 def action_cancel(self, cr, uid, ids, context=None):
886 for pick in self.browse(cr, uid, ids, context=context):
887 ids2 = [move.id for move in pick.move_lines]
888 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
891 def action_done(self, cr, uid, ids, context=None):
892 """Changes picking state to done by processing the Stock Moves of the Picking
894 Normally that happens when the button "Done" is pressed on a Picking view.
897 for pick in self.browse(cr, uid, ids, context=context):
899 for move in pick.move_lines:
900 if move.state == 'draft':
901 todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
902 elif move.state in ('assigned', 'confirmed'):
905 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
908 def unlink(self, cr, uid, ids, context=None):
909 #on picking deletion, cancel its move then unlink them too
910 move_obj = self.pool.get('stock.move')
911 context = context or {}
912 for pick in self.browse(cr, uid, ids, context=context):
913 move_ids = [move.id for move in pick.move_lines]
914 move_obj.action_cancel(cr, uid, move_ids, context=context)
915 move_obj.unlink(cr, uid, move_ids, context=context)
916 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
918 def write(self, cr, uid, ids, vals, context=None):
919 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
920 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
921 if 'move_lines' in vals or 'pack_operation_ids' in vals:
922 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
925 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
926 """ 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.
928 if not backorder_moves:
929 backorder_moves = picking.move_lines
930 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
931 if 'do_only_split' in context and context['do_only_split']:
932 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
934 if backorder_move_ids:
935 backorder_id = self.copy(cr, uid, picking.id, {
938 'pack_operation_ids': [],
939 'backorder_id': picking.id,
941 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (picking.name), context=context)
942 move_obj = self.pool.get("stock.move")
943 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
945 self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
946 self.action_confirm(cr, uid, [backorder_id], context=context)
950 @api.cr_uid_ids_context
951 def recheck_availability(self, cr, uid, picking_ids, context=None):
952 self.action_assign(cr, uid, picking_ids, context=context)
953 self.do_prepare_partial(cr, uid, picking_ids, context=context)
955 def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
956 """This method searches for the higher level packages that can be moved as a single operation, given a list of quants
957 to move and their suggested destination, and returns the list of matching packages.
959 # Try to find as much as possible top-level packages that can be moved
960 pack_obj = self.pool.get("stock.quant.package")
961 quant_obj = self.pool.get("stock.quant")
962 top_lvl_packages = set()
963 quants_to_compare = quants_suggested_locations.keys()
964 for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
968 pack_destination = False
970 pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
972 for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
973 # If the quant is not in the quants to compare and not in the common location
974 if not quant in quants_to_compare:
978 #if putaway strat apply, the destination location of each quant may be different (and thus the package should not be taken as a single operation)
979 if not pack_destination:
980 pack_destination = quants_suggested_locations[quant]
981 elif pack_destination != quants_suggested_locations[quant]:
985 good_pack = test_pack
986 if test_pack.parent_id:
987 test_pack = test_pack.parent_id
989 #stop the loop when there's no parent package anymore
992 #stop the loop when the package test_pack is not totally reserved for moves of this picking
993 #(some quants may be reserved for other picking or not reserved at all)
996 top_lvl_packages.add(good_pack)
997 return list(top_lvl_packages)
999 def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
1000 """ returns a list of dict, ready to be used in create() of stock.pack.operation.
1002 :param picking: browse record (stock.picking)
1003 :param quants: browse record list (stock.quant). List of quants associated to the picking
1004 :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
1006 def _picking_putaway_apply(product):
1008 # Search putaway strategy
1009 if product_putaway_strats.get(product.id):
1010 location = product_putaway_strats[product.id]
1012 location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
1013 product_putaway_strats[product.id] = location
1014 return location or picking.location_dest_id.id
1016 pack_obj = self.pool.get("stock.quant.package")
1017 quant_obj = self.pool.get("stock.quant")
1020 #for each quant of the picking, find the suggested location
1021 quants_suggested_locations = {}
1022 product_putaway_strats = {}
1023 for quant in quants:
1026 suggested_location_id = _picking_putaway_apply(quant.product_id)
1027 quants_suggested_locations[quant] = suggested_location_id
1029 #find the packages we can movei as a whole
1030 top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
1031 # and then create pack operations for the top-level packages found
1032 for pack in top_lvl_packages:
1033 pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
1034 pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
1036 'picking_id': picking.id,
1037 'package_id': pack.id,
1039 'location_id': pack.location_id.id,
1040 'location_dest_id': quants_suggested_locations[pack_quants[0]],
1042 #remove the quants inside the package so that they are excluded from the rest of the computation
1043 for quant in pack_quants:
1044 del quants_suggested_locations[quant]
1046 # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
1047 for quant, dest_location_id in quants_suggested_locations.items():
1048 key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
1049 if qtys_grouped.get(key):
1050 qtys_grouped[key] += quant.qty
1052 qtys_grouped[key] = quant.qty
1054 # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
1055 for product, qty in forced_qties.items():
1058 suggested_location_id = _picking_putaway_apply(product)
1059 key = (product.id, False, False, False, picking.location_id.id, suggested_location_id)
1060 if qtys_grouped.get(key):
1061 qtys_grouped[key] += qty
1063 qtys_grouped[key] = qty
1065 # Create the necessary operations for the grouped quants and remaining qtys
1066 for key, qty in qtys_grouped.items():
1068 'picking_id': picking.id,
1070 'product_id': key[0],
1071 'package_id': key[1],
1074 'location_id': key[4],
1075 'location_dest_id': key[5],
1076 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id,
1080 @api.cr_uid_ids_context
1081 def open_barcode_interface(self, cr, uid, picking_ids, context=None):
1082 final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0])
1083 return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
1085 @api.cr_uid_ids_context
1086 def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
1087 self.do_prepare_partial(cr, uid, picking_ids, context=context)
1088 return self.open_barcode_interface(cr, uid, picking_ids, context=context)
1090 @api.cr_uid_ids_context
1091 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
1092 context = context or {}
1093 pack_operation_obj = self.pool.get('stock.pack.operation')
1094 #used to avoid recomputing the remaining quantities at each new pack operation created
1095 ctx = context.copy()
1096 ctx['no_recompute'] = True
1098 #get list of existing operations and delete them
1099 existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
1100 if existing_package_ids:
1101 pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
1102 for picking in self.browse(cr, uid, picking_ids, context=context):
1103 forced_qties = {} # Quantity remaining after calculating reserved quants
1105 #Calculate packages, reserved quants, qtys of this picking's moves
1106 for move in picking.move_lines:
1107 if move.state not in ('assigned', 'confirmed'):
1109 move_quants = move.reserved_quant_ids
1110 picking_quants += move_quants
1111 forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
1112 #if we used force_assign() on the move, or if the move is incomming, forced_qty > 0
1114 if forced_qties.get(move.product_id):
1115 forced_qties[move.product_id] += forced_qty
1117 forced_qties[move.product_id] = forced_qty
1118 for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
1119 pack_operation_obj.create(cr, uid, vals, context=ctx)
1120 #recompute the remaining quantities all at once
1121 self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
1122 self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context)
1124 @api.cr_uid_ids_context
1125 def do_unreserve(self, cr, uid, picking_ids, context=None):
1127 Will remove all quants for picking in picking_ids
1129 moves_to_unreserve = []
1130 pack_line_to_unreserve = []
1131 for picking in self.browse(cr, uid, picking_ids, context=context):
1132 moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
1133 pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
1134 if moves_to_unreserve:
1135 if pack_line_to_unreserve:
1136 self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
1137 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
1139 def recompute_remaining_qty(self, cr, uid, picking, context=None):
1140 def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
1141 move_dict = prod2move_ids[product_id][index]
1142 qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
1143 self.pool.get('stock.move.operation.link').create(cr, uid, {'move_id': move_dict['move'].id, 'operation_id': operation_id, 'qty': qty_on_link, 'reserved_quant_id': quant_id}, context=context)
1144 if move_dict['remaining_qty'] == qty_on_link:
1145 prod2move_ids[product_id].pop(index)
1147 move_dict['remaining_qty'] -= qty_on_link
1150 def _create_link_for_quant(operation_id, quant, qty):
1151 """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
1152 if not quant.reservation_id.id:
1153 return _create_link_for_product(operation_id, quant.product_id.id, qty)
1155 for i in range(0, len(prod2move_ids[quant.product_id.id])):
1156 if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
1158 qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
1162 def _create_link_for_product(operation_id, product_id, qty):
1163 '''method that creates the link between a given operation and move(s) of given product, for the given quantity.
1164 Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
1166 if prod2move_ids.get(product_id):
1167 while prod2move_ids[product_id] and qty_to_assign > 0:
1168 qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
1169 qty_to_assign -= qty_on_link
1170 return qty_to_assign == 0
1172 uom_obj = self.pool.get('product.uom')
1173 package_obj = self.pool.get('stock.quant.package')
1174 quant_obj = self.pool.get('stock.quant')
1175 quants_in_package_done = set()
1178 #make a dictionary giving for each product, the moves and related quantity that can be used in operation links
1179 for move in picking.move_lines:
1180 if not prod2move_ids.get(move.product_id.id):
1181 prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
1183 prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
1185 need_rereserve = False
1186 #sort the operations in order to give higher priority to those with a package, then a serial number
1187 operations = picking.pack_operation_ids
1188 operations = sorted(operations, key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
1189 #delete existing operations to start again from scratch
1190 cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),))
1192 #1) first, try to create links when quants can be identified without any doubt
1193 for ops in operations:
1194 #for each operation, create the links with the stock move by seeking on the matching reserved quants,
1195 #and deffer the operation if there is some ambiguity on the move to select
1196 if ops.package_id and not ops.product_id:
1198 quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
1199 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1200 remaining_qty_on_quant = quant.qty
1201 if quant.reservation_id:
1202 #avoid quants being counted twice
1203 quants_in_package_done.add(quant.id)
1204 qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
1205 remaining_qty_on_quant -= qty_on_link
1206 if remaining_qty_on_quant:
1207 still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
1208 need_rereserve = True
1209 elif ops.product_id.id:
1210 #Check moves with same product
1211 qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
1212 for move_dict in prod2move_ids.get(ops.product_id.id, []):
1213 move = move_dict['move']
1214 for quant in move.reserved_quant_ids:
1215 if not qty_to_assign > 0:
1217 if quant.id in quants_in_package_done:
1220 #check if the quant is matching the operation details
1222 flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id])], context=context)) or False
1224 flag = not quant.package_id.id
1225 flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
1226 flag = flag and (ops.owner_id.id == quant.owner_id.id)
1228 max_qty_on_link = min(quant.qty, qty_to_assign)
1229 qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
1230 qty_to_assign -= qty_on_link
1231 if qty_to_assign > 0:
1232 #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
1233 #all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
1234 still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
1235 need_rereserve = True
1237 #2) then, process the remaining part
1238 all_op_processed = True
1239 for ops, product_id, remaining_qty in still_to_do:
1240 all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty)
1241 return (need_rereserve, all_op_processed)
1243 def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
1244 need_rereserve = False
1245 all_op_processed = True
1246 if picking.pack_operation_ids:
1247 need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
1248 return need_rereserve, all_op_processed
1250 @api.cr_uid_ids_context
1251 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
1252 for picking in self.browse(cr, uid, picking_ids, context=context):
1253 if picking.pack_operation_ids:
1254 self.recompute_remaining_qty(cr, uid, picking, context=context)
1256 def _create_extra_moves(self, cr, uid, picking, context=None):
1257 '''This function creates move lines on a picking, at the time of do_transfer, based on
1258 unexpected product transfers (or exceeding quantities) found in the pack operations.
1260 move_obj = self.pool.get('stock.move')
1261 operation_obj = self.pool.get('stock.pack.operation')
1263 for op in picking.pack_operation_ids:
1264 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1265 if remaining_qty > 0:
1266 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1268 'picking_id': picking.id,
1269 'location_id': picking.location_id.id,
1270 'location_dest_id': picking.location_dest_id.id,
1271 'product_id': product_id,
1272 'product_uom': product.uom_id.id,
1273 'product_uom_qty': remaining_qty,
1274 'name': _('Extra Move: ') + product.name,
1277 moves.append(move_obj.create(cr, uid, vals, context=context))
1279 move_obj.action_confirm(cr, uid, moves, context=context)
1282 def rereserve_pick(self, cr, uid, ids, context=None):
1284 This can be used to provide a button that rereserves taking into account the existing pack operations
1286 for pick in self.browse(cr, uid, ids, context=context):
1287 self.rereserve_quants(cr, uid, pick, move_ids = [x.id for x in pick.move_lines], context=context)
1289 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1290 """ Unreserve quants then try to reassign quants."""
1291 stock_move_obj = self.pool.get('stock.move')
1293 self.do_unreserve(cr, uid, [picking.id], context=context)
1294 self.action_assign(cr, uid, [picking.id], context=context)
1296 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1297 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1299 @api.cr_uid_ids_context
1300 def do_enter_transfer_details(self, cr, uid, picking, context=None):
1305 'active_model': self._name,
1306 'active_ids': picking,
1307 'active_id': len(picking) and picking[0] or False
1310 created_id = self.pool['stock.transfer_details'].create(cr, uid, {'picking_id': len(picking) and picking[0] or False}, context)
1311 return self.pool['stock.transfer_details'].wizard_view(cr, uid, created_id, context)
1314 @api.cr_uid_ids_context
1315 def do_transfer(self, cr, uid, picking_ids, context=None):
1317 If no pack operation, we do simple action_done of the picking
1318 Otherwise, do the pack operations
1322 stock_move_obj = self.pool.get('stock.move')
1323 for picking in self.browse(cr, uid, picking_ids, context=context):
1324 if not picking.pack_operation_ids:
1325 self.action_done(cr, uid, [picking.id], context=context)
1328 need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
1329 #create extra moves in the picking (unexpected product moves coming from pack operations)
1331 if not all_op_processed:
1332 todo_move_ids += self._create_extra_moves(cr, uid, picking, context=context)
1335 #split move lines eventually
1337 toassign_move_ids = []
1338 for move in picking.move_lines:
1339 remaining_qty = move.remaining_qty
1340 if move.state in ('done', 'cancel'):
1341 #ignore stock moves cancelled or already done
1343 elif move.state == 'draft':
1344 toassign_move_ids.append(move.id)
1345 if remaining_qty == 0:
1346 if move.state in ('draft', 'assigned', 'confirmed'):
1347 todo_move_ids.append(move.id)
1348 elif remaining_qty > 0 and remaining_qty < move.product_qty:
1349 new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
1350 todo_move_ids.append(move.id)
1351 #Assign move as it was assigned before
1352 toassign_move_ids.append(new_move)
1353 if need_rereserve or not all_op_processed:
1354 if not picking.location_id.usage in ("supplier", "production", "inventory"):
1355 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1356 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1357 if todo_move_ids and not context.get('do_only_split'):
1358 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1359 elif context.get('do_only_split'):
1360 context = dict(context, split=todo_move_ids)
1362 self._create_backorder(cr, uid, picking, context=context)
1363 if toassign_move_ids:
1364 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1367 @api.cr_uid_ids_context
1368 def do_split(self, cr, uid, picking_ids, context=None):
1369 """ just split the picking (create a backorder) without making it 'done' """
1372 ctx = context.copy()
1373 ctx['do_only_split'] = True
1374 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1376 def get_next_picking_for_ui(self, cr, uid, context=None):
1377 """ returns the next pickings to process. Used in the barcode scanner UI"""
1380 domain = [('state', 'in', ('assigned', 'partially_available'))]
1381 if context.get('default_picking_type_id'):
1382 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1383 return self.search(cr, uid, domain, context=context)
1385 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1386 """ called when button 'done' is pushed in the barcode scanner UI """
1387 #write qty_done into field product_qty for every package_operation before doing the transfer
1388 pack_op_obj = self.pool.get('stock.pack.operation')
1389 for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
1390 pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
1391 self.do_transfer(cr, uid, [picking_id], context=context)
1392 #return id of next picking to work on
1393 return self.get_next_picking_for_ui(cr, uid, context=context)
1395 @api.cr_uid_ids_context
1396 def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
1397 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1398 Used in the barcode scanner UI and the normal interface as well.
1399 operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
1400 if operation_filter_ids == None:
1401 operation_filter_ids = []
1402 stock_operation_obj = self.pool.get('stock.pack.operation')
1403 package_obj = self.pool.get('stock.quant.package')
1404 stock_move_obj = self.pool.get('stock.move')
1405 for picking_id in picking_ids:
1406 operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
1407 if operation_filter_ids != []:
1408 operation_search_domain.append(('id', 'in', operation_filter_ids))
1409 operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
1410 pack_operation_ids = []
1412 for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
1413 #If we haven't done all qty in operation, we have to split into 2 operation
1415 if (operation.qty_done < operation.product_qty):
1416 new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
1417 stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0, 'lot_id': False}, context=context)
1418 op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
1419 pack_operation_ids.append(op.id)
1420 if op.product_id and op.location_id and op.location_dest_id:
1421 stock_move_obj.check_tracking_product(cr, uid, op.product_id, op.lot_id.id, op.location_id, op.location_dest_id, context=context)
1422 package_id = package_obj.create(cr, uid, {}, context=context)
1423 stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
1426 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
1427 return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id),('id', '=', op_id)], increment=increment, context=context)
1429 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
1430 '''This function is called each time there barcode scanner reads an input'''
1431 lot_obj = self.pool.get('stock.production.lot')
1432 package_obj = self.pool.get('stock.quant.package')
1433 product_obj = self.pool.get('product.product')
1434 stock_operation_obj = self.pool.get('stock.pack.operation')
1435 stock_location_obj = self.pool.get('stock.location')
1436 answer = {'filter_loc': False, 'operation_id': False}
1437 #check if the barcode correspond to a location
1438 matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context)
1439 if matching_location_ids:
1440 #if we have a location, return immediatly with the location name
1441 location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
1442 answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
1443 answer['filter_loc_id'] = matching_location_ids[0]
1445 #check if the barcode correspond to a product
1446 matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context)
1447 if matching_product_ids:
1448 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1449 answer['operation_id'] = op_id
1451 #check if the barcode correspond to a lot
1452 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1453 if matching_lot_ids:
1454 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1455 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1456 answer['operation_id'] = op_id
1458 #check if the barcode correspond to a package
1459 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1460 if matching_package_ids:
1461 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1462 answer['operation_id'] = op_id
1467 class stock_production_lot(osv.osv):
1468 _name = 'stock.production.lot'
1469 _inherit = ['mail.thread']
1470 _description = 'Lot/Serial'
1472 'name': fields.char('Serial Number', required=True, help="Unique Serial Number"),
1473 'ref': fields.char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's serial number"),
1474 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1475 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
1476 'create_date': fields.datetime('Creation Date'),
1479 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1480 'product_id': lambda x, y, z, c: c.get('product_id', False),
1482 _sql_constraints = [
1483 ('name_ref_uniq', 'unique (name, ref, product_id)', 'The combination of serial number, internal reference and product must be unique !'),
1486 def action_traceability(self, cr, uid, ids, context=None):
1487 """ It traces the information of lots
1488 @param self: The object pointer.
1489 @param cr: A database cursor
1490 @param uid: ID of the user currently logged in
1491 @param ids: List of IDs selected
1492 @param context: A standard dictionary
1493 @return: A dictionary of values
1495 quant_obj = self.pool.get("stock.quant")
1496 quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1498 for quant in quant_obj.browse(cr, uid, quants, context=context):
1499 moves |= {move.id for move in quant.history_ids}
1502 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
1503 'name': _('Traceability'),
1504 'view_mode': 'tree,form',
1505 'view_type': 'form',
1506 'context': {'tree_view_ref': 'stock.view_move_tree'},
1507 'res_model': 'stock.move',
1508 'type': 'ir.actions.act_window',
1513 # ----------------------------------------------------
1515 # ----------------------------------------------------
1517 class stock_move(osv.osv):
1518 _name = "stock.move"
1519 _description = "Stock Move"
1520 _order = 'date_expected desc, id'
1523 def get_price_unit(self, cr, uid, move, context=None):
1524 """ Returns the unit price to store on the quant """
1525 return move.price_unit or move.product_id.standard_price
1527 def name_get(self, cr, uid, ids, context=None):
1529 for line in self.browse(cr, uid, ids, context=context):
1530 name = line.location_id.name + ' > ' + line.location_dest_id.name
1531 if line.product_id.code:
1532 name = line.product_id.code + ': ' + name
1533 if line.picking_id.origin:
1534 name = line.picking_id.origin + '/ ' + name
1535 res.append((line.id, name))
1538 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1539 uom_obj = self.pool.get('product.uom')
1541 for m in self.browse(cr, uid, ids, context=context):
1542 res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False, context=context)
1545 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1546 uom_obj = self.pool.get('product.uom')
1548 for move in self.browse(cr, uid, ids, context=context):
1549 qty = move.product_qty
1550 for record in move.linked_move_operation_ids:
1552 #converting the remaining quantity in the move UoM
1553 res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context)
1556 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1557 res = dict.fromkeys(ids, False)
1558 for move in self.browse(cr, uid, ids, context=context):
1559 if move.state == 'done':
1560 res[move.id] = [q.lot_id.id for q in move.quant_ids if q.lot_id]
1562 res[move.id] = [q.lot_id.id for q in move.reserved_quant_ids if q.lot_id]
1565 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1566 quant_obj = self.pool.get('stock.quant')
1567 res = dict.fromkeys(ids, False)
1568 for move in self.browse(cr, uid, ids, context=context):
1569 if move.state == 'done':
1570 res[move.id] = move.product_qty
1572 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1573 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1575 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1576 availability += quant.qty
1577 res[move.id] = min(move.product_qty, availability)
1580 def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
1581 settings_obj = self.pool.get('stock.config.settings')
1582 uom_obj = self.pool.get('product.uom')
1583 res = dict.fromkeys(ids, '')
1584 for move in self.browse(cr, uid, ids, context=context):
1585 if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
1586 res[move.id] = '' # 'not applicable' or 'n/a' could work too
1588 total_available = min(move.product_qty, move.reserved_availability + move.availability)
1589 total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
1590 info = str(total_available)
1591 #look in the settings if we need to display the UoM name or not
1592 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1594 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1595 if stock_settings.group_uom:
1596 info += ' ' + move.product_uom.name
1597 if move.reserved_availability:
1598 if move.reserved_availability != total_available:
1599 #some of the available quantity is assigned and some are available but not reserved
1600 reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
1601 info += _(' (%s reserved)') % str(reserved_available)
1603 #all available quantity is assigned
1604 info += _(' (reserved)')
1608 def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
1609 res = dict.fromkeys(ids, 0)
1610 for move in self.browse(cr, uid, ids, context=context):
1611 res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
1614 def _get_move(self, cr, uid, ids, context=None):
1616 for quant in self.browse(cr, uid, ids, context=context):
1617 if quant.reservation_id:
1618 res.add(quant.reservation_id.id)
1621 def _get_move_ids(self, cr, uid, ids, context=None):
1623 for picking in self.browse(cr, uid, ids, context=context):
1624 res += [x.id for x in picking.move_lines]
1627 def _get_moves_from_prod(self, cr, uid, ids, context=None):
1629 return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context)
1632 def _set_product_qty(self, cr, uid, id, field, value, arg, context=None):
1633 """ The meaning of product_qty field changed lately and is now a functional field computing the quantity
1634 in the default product UoM. This code has been added to raise an error if a write is made given a value
1635 for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
1638 raise osv.except_osv(_('Programming Error!'), _('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.'))
1641 'name': fields.char('Description', required=True, select=True),
1642 'priority': fields.selection(procurement.PROCUREMENT_PRIORITIES, 'Priority'),
1643 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1644 '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)]}),
1645 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1646 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1647 'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, _type='float', store={
1648 'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_id', 'product_uom_qty', 'product_uom'], 20),
1649 'product.product': (_get_moves_from_prod, ['uom_id'], 20),
1650 }, string='Quantity',
1651 digits_compute=dp.get_precision('Product Unit of Measure'),
1652 help='Quantity in the default UoM of the product'),
1653 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1654 required=True, states={'done': [('readonly', True)]},
1655 help="This is the quantity of products from an inventory "
1656 "point of view. For moves in the state 'done', this is the "
1657 "quantity of products that were actually moved. For other "
1658 "moves, this is the quantity of product that is planned to "
1659 "be moved. Lowering this quantity does not generate a "
1660 "backorder. Changing this quantity on assigned moves affects "
1661 "the product reservation, and should be done with care."
1663 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1664 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1665 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1667 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1669 '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."),
1670 '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."),
1672 '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"),
1675 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True, copy=False),
1676 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1678 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1679 'note': fields.text('Notes'),
1680 'state': fields.selection([('draft', 'New'),
1681 ('cancel', 'Cancelled'),
1682 ('waiting', 'Waiting Another Move'),
1683 ('confirmed', 'Waiting Availability'),
1684 ('assigned', 'Available'),
1686 ], 'Status', readonly=True, select=True, copy=False,
1687 help= "* New: When the stock move is created and not yet confirmed.\n"\
1688 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1689 "* 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"\
1690 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1691 "* Done: When the shipment is processed, the state is \'Done\'."),
1692 'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved", copy=False),
1693 'price_unit': fields.float('Unit Price', help="Technical field used to record the product cost set by the user during a picking confirmation (when costing method used is 'average price' or 'real'). Value given in company currency and in product uom."), # as it's a technical field, we intentionally don't provide the digits attribute
1695 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1696 'split_from': fields.many2one('stock.move', string="Move Split From", help="Technical field used to track the origin of a split move, which can be useful in case of debug", copy=False),
1697 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1698 'origin': fields.char("Source"),
1699 'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True,
1700 help="""By default, the system will take from the stock in the source location and passively wait for availability. The other possibility allows you to directly create a procurement on the source location (and thus ignore its current stock) to gather products. If we want to chain moves and have this one to wait for the previous, this second option should be chosen."""),
1702 # used for colors in tree views:
1703 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1705 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1706 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1707 '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'),
1708 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1709 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1710 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1711 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1712 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1713 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1714 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1715 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1716 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1717 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.production.lot', string='Lots'),
1718 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move', copy=False),
1719 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1720 'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
1721 'availability': fields.function(_get_product_availability, type='float', string='Quantity Available', readonly=True, help='Quantity in stock that can still be reserved for this move'),
1722 'string_availability_info': fields.function(_get_string_qty_information, type='text', string='Availability', readonly=True, help='Show various information on stock availability for this move'),
1723 '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'"),
1724 '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'"),
1725 '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"),
1726 '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)."),
1729 def _default_location_destination(self, cr, uid, context=None):
1730 context = context or {}
1731 if context.get('default_picking_type_id', False):
1732 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1733 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1736 def _default_location_source(self, cr, uid, context=None):
1737 context = context or {}
1738 if context.get('default_picking_type_id', False):
1739 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1740 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1743 def _default_destination_address(self, cr, uid, context=None):
1744 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1745 return user.company_id.partner_id.id
1748 'location_id': _default_location_source,
1749 'location_dest_id': _default_location_destination,
1750 'partner_id': _default_destination_address,
1753 'product_uom_qty': 1.0,
1755 'date': fields.datetime.now,
1756 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1757 'date_expected': fields.datetime.now,
1758 'procure_method': 'make_to_stock',
1760 'partially_available': False,
1763 def _check_uom(self, cr, uid, ids, context=None):
1764 for move in self.browse(cr, uid, ids, context=context):
1765 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1771 '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.',
1775 @api.cr_uid_ids_context
1776 def do_unreserve(self, cr, uid, move_ids, context=None):
1777 quant_obj = self.pool.get("stock.quant")
1778 for move in self.browse(cr, uid, move_ids, context=context):
1779 if move.state in ('done', 'cancel'):
1780 raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
1781 quant_obj.quants_unreserve(cr, uid, move, context=context)
1782 if self.find_move_ancestors(cr, uid, move, context=context):
1783 self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context)
1785 self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
1787 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1788 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1789 group_id = move.group_id and move.group_id.id or False
1791 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1792 group_id = move.rule_id.group_id.id
1793 elif move.rule_id.group_propagation_option == 'none':
1796 'name': move.rule_id and move.rule_id.name or "/",
1798 'company_id': move.company_id and move.company_id.id or False,
1799 'date_planned': move.date,
1800 'product_id': move.product_id.id,
1801 'product_qty': move.product_qty,
1802 'product_uom': move.product_uom.id,
1803 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1804 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1805 'location_id': move.location_id.id,
1806 'move_dest_id': move.id,
1807 'group_id': group_id,
1808 'route_ids': [(4, x.id) for x in move.route_ids],
1809 'warehouse_id': move.warehouse_id.id or (move.picking_type_id and move.picking_type_id.warehouse_id.id or False),
1810 'priority': move.priority,
1813 def _push_apply(self, cr, uid, moves, context=None):
1814 push_obj = self.pool.get("stock.location.path")
1816 #1) if the move is already chained, there is no need to check push rules
1817 #2) if the move is a returned move, we don't want to check push rules, as returning a returned move is the only decent way
1818 # to receive goods without triggering the push rules again (which would duplicate chained operations)
1819 if not move.move_dest_id and not move.origin_returned_move_id:
1820 domain = [('location_from_id', '=', move.location_dest_id.id)]
1821 #priority goes to the route defined on the product and product category
1822 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1823 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1825 #then we search on the warehouse if a rule can apply
1827 if move.warehouse_id:
1828 wh_route_ids = [x.id for x in move.warehouse_id.route_ids]
1829 elif move.picking_type_id and move.picking_type_id.warehouse_id:
1830 wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids]
1832 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context)
1834 #if no specialized push rule has been found yet, we try to find a general one (without route)
1835 rules = push_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)
1837 rule = push_obj.browse(cr, uid, rules[0], context=context)
1838 push_obj._apply(cr, uid, rule, move, context=context)
1841 def _create_procurement(self, cr, uid, move, context=None):
1842 """ This will create a procurement order """
1843 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1845 def write(self, cr, uid, ids, vals, context=None):
1848 if isinstance(ids, (int, long)):
1850 # Check that we do not modify a stock.move which is done
1851 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1852 for move in self.browse(cr, uid, ids, context=context):
1853 if move.state == 'done':
1854 if frozen_fields.intersection(vals):
1855 raise osv.except_osv(_('Operation Forbidden!'),
1856 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1857 propagated_changes_dict = {}
1858 #propagation of quantity change
1859 if vals.get('product_uom_qty'):
1860 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1861 if vals.get('product_uom_id'):
1862 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1863 #propagation of expected date:
1864 propagated_date_field = False
1865 if vals.get('date_expected'):
1866 #propagate any manual change of the expected date
1867 propagated_date_field = 'date_expected'
1868 elif (vals.get('state', '') == 'done' and vals.get('date')):
1869 #propagate also any delta observed when setting the move as done
1870 propagated_date_field = 'date'
1872 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1873 #any propagation is (maybe) needed
1874 for move in self.browse(cr, uid, ids, context=context):
1875 if move.move_dest_id and move.propagate:
1876 if 'date_expected' in propagated_changes_dict:
1877 propagated_changes_dict.pop('date_expected')
1878 if propagated_date_field:
1879 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1880 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1881 delta = new_date - current_date
1882 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1883 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1884 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1885 propagated_changes_dict['date_expected'] = new_move_date
1886 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1887 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1888 if propagated_changes_dict:
1889 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1890 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1892 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1893 """ On change of product quantity finds UoM and UoS quantities
1894 @param product_id: Product id
1895 @param product_qty: Changed Quantity of product
1896 @param product_uom: Unit of measure of product
1897 @param product_uos: Unit of sale of product
1898 @return: Dictionary of values
1901 'product_uos_qty': 0.00
1905 if (not product_id) or (product_qty <= 0.0):
1906 result['product_qty'] = 0.0
1907 return {'value': result}
1909 product_obj = self.pool.get('product.product')
1910 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1912 # Warn if the quantity was decreased
1914 for move in self.read(cr, uid, ids, ['product_qty']):
1915 if product_qty < move['product_qty']:
1917 'title': _('Information'),
1918 'message': _("By changing this quantity here, you accept the "
1919 "new quantity as complete: Odoo will not "
1920 "automatically generate a back order.")})
1923 if product_uos and product_uom and (product_uom != product_uos):
1924 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1926 result['product_uos_qty'] = product_qty
1928 return {'value': result, 'warning': warning}
1930 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1931 product_uos, product_uom):
1932 """ On change of product quantity finds UoM and UoS quantities
1933 @param product_id: Product id
1934 @param product_uos_qty: Changed UoS Quantity of product
1935 @param product_uom: Unit of measure of product
1936 @param product_uos: Unit of sale of product
1937 @return: Dictionary of values
1940 'product_uom_qty': 0.00
1943 if (not product_id) or (product_uos_qty <= 0.0):
1944 result['product_uos_qty'] = 0.0
1945 return {'value': result}
1947 product_obj = self.pool.get('product.product')
1948 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1950 # No warning if the quantity was decreased to avoid double warnings:
1951 # The clients should call onchange_quantity too anyway
1953 if product_uos and product_uom and (product_uom != product_uos):
1954 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1956 result['product_uom_qty'] = product_uos_qty
1957 return {'value': result}
1959 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1960 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1961 @param prod_id: Changed Product id
1962 @param loc_id: Source location id
1963 @param loc_dest_id: Destination location id
1964 @param partner_id: Address id of partner
1965 @return: Dictionary of values
1969 user = self.pool.get('res.users').browse(cr, uid, uid)
1970 lang = user and user.lang or False
1972 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1974 lang = addr_rec and addr_rec.lang or False
1975 ctx = {'lang': lang}
1977 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1978 uos_id = product.uos_id and product.uos_id.id or False
1980 'name': product.partner_ref,
1981 'product_uom': product.uom_id.id,
1982 'product_uos': uos_id,
1983 'product_uom_qty': 1.00,
1984 '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'],
1987 result['location_id'] = loc_id
1989 result['location_dest_id'] = loc_dest_id
1990 return {'value': result}
1992 @api.cr_uid_ids_context
1993 def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
1994 """Assign a picking on the given move_ids, which is a list of move supposed to share the same procurement_group, location_from and location_to
1995 (and company). Those attributes are also given as parameters.
1997 pick_obj = self.pool.get("stock.picking")
1998 picks = pick_obj.search(cr, uid, [
1999 ('group_id', '=', procurement_group),
2000 ('location_id', '=', location_from),
2001 ('location_dest_id', '=', location_to),
2002 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
2006 move = self.browse(cr, uid, move_ids, context=context)[0]
2008 'origin': move.origin,
2009 'company_id': move.company_id and move.company_id.id or False,
2010 'move_type': move.group_id and move.group_id.move_type or 'direct',
2011 'partner_id': move.partner_id.id or False,
2012 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
2014 pick = pick_obj.create(cr, uid, values, context=context)
2015 return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
2017 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
2018 """ On change of Scheduled Date gives a Move date.
2019 @param date_expected: Scheduled Date
2020 @param date: Move Date
2023 if not date_expected:
2024 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
2025 return {'value': {'date': date_expected}}
2027 def attribute_price(self, cr, uid, move, context=None):
2029 Attribute price to move, important in inter-company moves or receipts with only one partner
2031 if not move.price_unit:
2032 price = move.product_id.standard_price
2033 self.write(cr, uid, [move.id], {'price_unit': price})
2035 def action_confirm(self, cr, uid, ids, context=None):
2036 """ Confirms stock move or put it in waiting if it's linked to another move.
2037 @return: List of ids.
2039 if isinstance(ids, (int, long)):
2046 for move in self.browse(cr, uid, ids, context=context):
2047 self.attribute_price(cr, uid, move, context=context)
2049 #if the move is preceeded, then it's waiting (if preceeding move is done, then action_assign has been called already and its state is already available)
2050 if move.move_orig_ids:
2052 #if the move is split and some of the ancestor was preceeded, then it's waiting as well
2053 elif move.split_from:
2054 move2 = move.split_from
2055 while move2 and state != 'waiting':
2056 if move2.move_orig_ids:
2058 move2 = move2.split_from
2059 states[state].append(move.id)
2061 if not move.picking_id and move.picking_type_id:
2062 key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
2063 if key not in to_assign:
2065 to_assign[key].append(move.id)
2067 for move in self.browse(cr, uid, states['confirmed'], context=context):
2068 if move.procure_method == 'make_to_order':
2069 self._create_procurement(cr, uid, move, context=context)
2070 states['waiting'].append(move.id)
2071 states['confirmed'].remove(move.id)
2073 for state, write_ids in states.items():
2075 self.write(cr, uid, write_ids, {'state': state})
2076 #assign picking in batch for all confirmed move that share the same details
2077 for key, move_ids in to_assign.items():
2078 procurement_group, location_from, location_to = key
2079 self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
2080 moves = self.browse(cr, uid, ids, context=context)
2081 self._push_apply(cr, uid, moves, context=context)
2084 def force_assign(self, cr, uid, ids, context=None):
2085 """ Changes the state to assigned.
2088 return self.write(cr, uid, ids, {'state': 'assigned'}, context=context)
2090 def check_tracking_product(self, cr, uid, product, lot_id, location, location_dest, context=None):
2092 if product.track_all and not location_dest.usage == 'inventory':
2094 elif product.track_incoming and location.usage in ('supplier', 'transit', 'inventory') and location_dest.usage == 'internal':
2096 elif product.track_outgoing and location_dest.usage in ('customer', 'transit') and location.usage == 'internal':
2098 if check and not lot_id:
2099 raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (product.name))
2102 def check_tracking(self, cr, uid, move, lot_id, context=None):
2103 """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
2105 self.check_tracking_product(cr, uid, move.product_id, lot_id, move.location_id, move.location_dest_id, context=context)
2108 def action_assign(self, cr, uid, ids, context=None):
2109 """ Checks the product type and accordingly writes the state.
2111 context = context or {}
2112 quant_obj = self.pool.get("stock.quant")
2113 to_assign_moves = []
2117 for move in self.browse(cr, uid, ids, context=context):
2118 if move.state not in ('confirmed', 'waiting', 'assigned'):
2120 if move.location_id.usage in ('supplier', 'inventory', 'production'):
2121 to_assign_moves.append(move.id)
2122 #in case the move is returned, we want to try to find quants before forcing the assignment
2123 if not move.origin_returned_move_id:
2125 if move.product_id.type == 'consu':
2126 to_assign_moves.append(move.id)
2129 todo_moves.append(move)
2131 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
2132 main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
2134 #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
2135 ancestors = self.find_move_ancestors(cr, uid, move, context=context)
2136 if move.state == 'waiting' and not ancestors:
2137 #if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock
2138 main_domain[move.id] += [('id', '=', False)]
2140 main_domain[move.id] += [('history_ids', 'in', ancestors)]
2142 #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
2143 if move.origin_returned_move_id:
2144 main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
2145 for link in move.linked_move_operation_ids:
2146 operations.add(link.operation_id)
2147 # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
2148 operations = list(operations)
2149 operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
2150 for ops in operations:
2151 #first try to find quants based on specific domains given by linked operations
2152 for record in ops.linked_move_operation_ids:
2153 move = record.move_id
2154 if move.id in main_domain:
2155 domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2158 quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, qty, domain=domain, prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2159 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
2160 for move in todo_moves:
2161 if move.linked_move_operation_ids:
2164 #then if the move isn't totally assigned, try to find quants without any specific domain
2165 if move.state != 'assigned':
2166 qty_already_assigned = move.reserved_availability
2167 qty = move.product_qty - qty_already_assigned
2168 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain[move.id], prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2169 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
2171 #force assignation of consumable products and incoming from supplier/inventory/production
2173 self.force_assign(cr, uid, to_assign_moves, context=context)
2175 def action_cancel(self, cr, uid, ids, context=None):
2176 """ Cancels the moves and if all moves are cancelled it cancels the picking.
2179 procurement_obj = self.pool.get('procurement.order')
2180 context = context or {}
2182 for move in self.browse(cr, uid, ids, context=context):
2183 if move.state == 'done':
2184 raise osv.except_osv(_('Operation Forbidden!'),
2185 _('You cannot cancel a stock move that has been set to \'Done\'.'))
2186 if move.reserved_quant_ids:
2187 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
2188 if context.get('cancel_procurement'):
2190 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
2191 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
2193 if move.move_dest_id:
2195 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
2196 elif move.move_dest_id.state == 'waiting':
2197 #If waiting, the chain will be broken and we are not sure if we can still wait for it (=> could take from stock instead)
2198 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2199 if move.procurement_id:
2200 # Does the same as procurement check, only eliminating a refresh
2201 procs_to_check.append(move.procurement_id.id)
2203 res = self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2205 procurement_obj.check(cr, uid, procs_to_check, context=context)
2208 def _check_package_from_moves(self, cr, uid, ids, context=None):
2209 pack_obj = self.pool.get("stock.quant.package")
2211 for move in self.browse(cr, uid, ids, context=context):
2212 packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0])
2213 return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
2215 def find_move_ancestors(self, cr, uid, move, context=None):
2216 '''Find the first level ancestors of given move '''
2220 ancestors += [x.id for x in move2.move_orig_ids]
2221 #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
2222 move2 = not move2.move_orig_ids and move2.split_from or False
2225 @api.cr_uid_ids_context
2226 def recalculate_move_state(self, cr, uid, move_ids, context=None):
2227 '''Recompute the state of moves given because their reserved quants were used to fulfill another operation'''
2228 for move in self.browse(cr, uid, move_ids, context=context):
2230 reserved_quant_ids = move.reserved_quant_ids
2231 if len(reserved_quant_ids) > 0 and not move.partially_available:
2232 vals['partially_available'] = True
2233 if len(reserved_quant_ids) == 0 and move.partially_available:
2234 vals['partially_available'] = False
2235 if move.state == 'assigned':
2236 if self.find_move_ancestors(cr, uid, move, context=context):
2237 vals['state'] = 'waiting'
2239 vals['state'] = 'confirmed'
2241 self.write(cr, uid, [move.id], vals, context=context)
2243 def action_done(self, cr, uid, ids, context=None):
2244 """ Process completly the moves given as ids and if all moves are done, it will finish the picking.
2246 context = context or {}
2247 picking_obj = self.pool.get("stock.picking")
2248 quant_obj = self.pool.get("stock.quant")
2249 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
2251 ids = self.action_confirm(cr, uid, todo, context=context)
2253 procurement_ids = []
2254 #Search operations that are linked to the moves
2257 for move in self.browse(cr, uid, ids, context=context):
2258 move_qty[move.id] = move.product_qty
2259 for link in move.linked_move_operation_ids:
2260 operations.add(link.operation_id)
2262 #Sort operations according to entire packages first, then package + lot, package only, lot only
2263 operations = list(operations)
2264 operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
2266 for ops in operations:
2268 pickings.add(ops.picking_id.id)
2269 main_domain = [('qty', '>', 0)]
2270 for record in ops.linked_move_operation_ids:
2271 move = record.move_id
2272 self.check_tracking(cr, uid, move, not ops.product_id and ops.package_id.id or ops.lot_id.id, context=context)
2273 prefered_domain = [('reservation_id', '=', move.id)]
2274 fallback_domain = [('reservation_id', '=', False)]
2275 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2276 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2277 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2278 quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, record.qty, domain=dom, prefered_domain_list=prefered_domain_list,
2279 restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2280 if ops.result_package_id.id:
2281 #if a result package is given, all quants go there
2282 quant_dest_package_id = ops.result_package_id.id
2283 elif ops.product_id and ops.package_id:
2284 #if a package and a product is given, we will remove quants from the pack.
2285 quant_dest_package_id = False
2287 #otherwise we keep the current pack of the quant, which may mean None
2288 quant_dest_package_id = ops.package_id.id
2289 quant_obj.quants_move(cr, uid, quants, move, ops.location_dest_id, location_from=ops.location_id, lot_id=ops.lot_id.id, owner_id=ops.owner_id.id, src_package_id=ops.package_id.id, dest_package_id=quant_dest_package_id, context=context)
2290 # Handle pack in pack
2291 if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
2292 self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
2293 move_qty[move.id] -= record.qty
2294 #Check for remaining qtys and unreserve/check move_dest_id in
2295 for move in self.browse(cr, uid, ids, context=context):
2296 if move_qty[move.id] > 0: # (=In case no pack operations in picking)
2297 main_domain = [('qty', '>', 0)]
2298 prefered_domain = [('reservation_id', '=', move.id)]
2299 fallback_domain = [('reservation_id', '=', False)]
2300 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2301 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2302 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
2303 qty = move_qty[move.id]
2304 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain_list=prefered_domain_list, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2305 quant_obj.quants_move(cr, uid, quants, move, move.location_dest_id, lot_id=move.restrict_lot_id.id, owner_id=move.restrict_partner_id.id, context=context)
2306 #unreserve the quants and make them available for other operations/moves
2307 quant_obj.quants_unreserve(cr, uid, move, context=context)
2309 #Check moves that were pushed
2310 if move.move_dest_id.state in ('waiting', 'confirmed'):
2311 # FIXME is opw 607970 still present with new WMS?
2312 # (see commits 1ef2c181033bd200906fb1e5ce35e234bf566ac6
2313 # and 41c5ceb8ebb95c1b4e98d8dd1f12b8e547a24b1d)
2314 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
2315 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
2316 #If no other moves for the move that got pushed:
2317 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
2318 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
2319 if move.procurement_id:
2320 procurement_ids.append(move.procurement_id.id)
2322 # Check the packages have been placed in the correct locations
2323 self._check_package_from_moves(cr, uid, ids, context=context)
2324 #set the move as done
2325 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2326 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
2327 #check picking state to set the date_done is needed
2329 for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
2330 if picking.state == 'done' and not picking.date_done:
2331 done_picking.append(picking.id)
2333 picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2336 def unlink(self, cr, uid, ids, context=None):
2337 context = context or {}
2338 for move in self.browse(cr, uid, ids, context=context):
2339 if move.state not in ('draft', 'cancel'):
2340 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2341 return super(stock_move, self).unlink(cr, uid, ids, context=context)
2343 def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
2344 """ Move the scrap/damaged product into scrap location
2345 @param cr: the database cursor
2346 @param uid: the user id
2347 @param ids: ids of stock move object to be scrapped
2348 @param quantity : specify scrap qty
2349 @param location_id : specify scrap location
2350 @param context: context arguments
2351 @return: Scraped lines
2353 #quantity should be given in MOVE UOM
2355 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2357 for move in self.browse(cr, uid, ids, context=context):
2358 source_location = move.location_id
2359 if move.state == 'done':
2360 source_location = move.location_dest_id
2361 #Previously used to prevent scraping from virtual location but not necessary anymore
2362 #if source_location.usage != 'internal':
2363 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2364 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2365 move_qty = move.product_qty
2366 uos_qty = quantity / move_qty * move.product_uos_qty
2368 'location_id': source_location.id,
2369 'product_uom_qty': quantity,
2370 'product_uos_qty': uos_qty,
2371 'state': move.state,
2373 'location_dest_id': location_id,
2374 'restrict_lot_id': restrict_lot_id,
2375 'restrict_partner_id': restrict_partner_id,
2377 new_move = self.copy(cr, uid, move.id, default_val)
2380 product_obj = self.pool.get('product.product')
2381 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2383 uom = product.uom_id.name if product.uom_id else ''
2384 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2385 move.picking_id.message_post(body=message)
2387 self.action_done(cr, uid, res, context=context)
2390 def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
2391 """ Splits qty from move move into a new move
2392 :param move: browse record
2393 :param qty: float. quantity to split (given in product UoM)
2394 :param restrict_lot_id: optional production lot that can be given in order to force the new move to restrict its choice of quants to this lot.
2395 :param restrict_partner_id: optional partner that can be given in order to force the new move to restrict its choice of quants to the ones belonging to this partner.
2396 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
2398 returns the ID of the backorder move created
2400 if move.state in ('done', 'cancel'):
2401 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
2402 if move.state == 'draft':
2403 #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
2404 #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
2405 raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
2407 if move.product_qty <= qty or qty == 0:
2410 uom_obj = self.pool.get('product.uom')
2411 context = context or {}
2413 uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom)
2414 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
2417 'product_uom_qty': uom_qty,
2418 'product_uos_qty': uos_qty,
2419 'procure_method': 'make_to_stock',
2420 'restrict_lot_id': restrict_lot_id,
2421 'restrict_partner_id': restrict_partner_id,
2422 'split_from': move.id,
2423 'procurement_id': move.procurement_id.id,
2424 'move_dest_id': move.move_dest_id.id,
2426 if context.get('source_location_id'):
2427 defaults['location_id'] = context['source_location_id']
2428 new_move = self.copy(cr, uid, move.id, defaults)
2430 ctx = context.copy()
2431 ctx['do_not_propagate'] = True
2432 self.write(cr, uid, [move.id], {
2433 'product_uom_qty': move.product_uom_qty - uom_qty,
2434 'product_uos_qty': move.product_uos_qty - uos_qty,
2437 if move.move_dest_id and move.propagate and move.move_dest_id.state not in ('done', 'cancel'):
2438 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2439 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2440 #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
2441 #thus the result of action_confirm should always be a list of 1 element length)
2442 return self.action_confirm(cr, uid, [new_move], context=context)[0]
2445 def get_code_from_locs(self, cr, uid, move, context=None):
2447 Returns the code the picking type should have. This can easily be used
2448 to check if a move is internal or not
2451 src_loc = move.location_id
2452 dest_loc = move.location_dest_id
2453 if src_loc.usage == 'internal' and dest_loc.usage != 'internal':
2455 if src_loc.usage != 'internal' and dest_loc.usage == 'internal':
2460 class stock_inventory(osv.osv):
2461 _name = "stock.inventory"
2462 _description = "Inventory"
2464 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2466 for inv in self.browse(cr, uid, ids, context=context):
2472 def _get_available_filters(self, cr, uid, context=None):
2474 This function will return the list of filter allowed according to the options checked
2475 in 'Settings\Warehouse'.
2477 :rtype: list of tuple
2479 #default available choices
2480 res_filter = [('none', _('All products')), ('product', _('One product only'))]
2481 settings_obj = self.pool.get('stock.config.settings')
2482 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2483 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2487 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2488 if stock_settings.group_stock_tracking_owner:
2489 res_filter.append(('owner', _('One owner only')))
2490 res_filter.append(('product_owner', _('One product for a specific owner')))
2491 if stock_settings.group_stock_tracking_lot:
2492 res_filter.append(('lot', _('One Lot/Serial Number')))
2493 if stock_settings.group_stock_packaging:
2494 res_filter.append(('pack', _('A Pack')))
2497 def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
2499 for inv in self.browse(cr, uid, ids, context=context):
2500 res[inv.id] = sum([x.product_qty for x in inv.line_ids])
2503 INVENTORY_STATE_SELECTION = [
2505 ('cancel', 'Cancelled'),
2506 ('confirm', 'In Progress'),
2507 ('done', 'Validated'),
2511 'name': fields.char('Inventory Reference', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2512 'date': fields.datetime('Inventory Date', required=True, readonly=True, help="The date that will be used for the stock level check of the products and the validation of the stock move related to this inventory."),
2513 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines.", copy=True),
2514 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
2515 'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True, copy=False),
2516 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2517 'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2518 'product_id': fields.many2one('product.product', 'Inventoried Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2519 'package_id': fields.many2one('stock.quant.package', 'Inventoried Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."),
2520 'partner_id': fields.many2one('res.partner', 'Inventoried Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2521 'lot_id': fields.many2one('stock.production.lot', 'Inventoried Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number.", copy=False),
2522 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2523 'filter': fields.selection(_get_available_filters, 'Selection Filter', required=True),
2524 'total_qty': fields.function(_get_total_qty, type="float"),
2527 def _default_stock_location(self, cr, uid, context=None):
2529 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2530 return warehouse.lot_stock_id.id
2535 'date': fields.datetime.now,
2537 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2538 'location_id': _default_stock_location,
2542 def reset_real_qty(self, cr, uid, ids, context=None):
2543 inventory = self.browse(cr, uid, ids[0], context=context)
2544 line_ids = [line.id for line in inventory.line_ids]
2545 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2548 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2549 """ Creates a stock move from an inventory line
2550 @param inventory_line:
2554 return self.pool.get('stock.move').create(cr, uid, move_vals)
2556 def action_done(self, cr, uid, ids, context=None):
2557 """ Finish the inventory
2560 for inv in self.browse(cr, uid, ids, context=context):
2561 for inventory_line in inv.line_ids:
2562 if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty:
2563 raise osv.except_osv(_('Warning'), _('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty)))
2564 self.action_check(cr, uid, [inv.id], context=context)
2566 self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
2567 self.post_inventory(cr, uid, inv, context=context)
2570 def post_inventory(self, cr, uid, inv, context=None):
2571 #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
2572 #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
2573 #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
2574 move_obj = self.pool.get('stock.move')
2575 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2577 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2578 stock_move_obj = self.pool.get('stock.move')
2579 product_obj = self.pool.get('product.product')
2580 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2582 'name': _('INV:') + (inventory.name or ''),
2583 'product_id': todo_line['product_id'],
2584 'product_uom': todo_line['product_uom_id'],
2585 'date': inventory.date,
2586 'company_id': inventory.company_id.id,
2587 'inventory_id': inventory.id,
2588 'state': 'assigned',
2589 'restrict_lot_id': todo_line.get('prod_lot_id'),
2590 'restrict_partner_id': todo_line.get('partner_id'),
2593 if todo_line['product_qty'] < 0:
2594 #found more than expected
2595 vals['location_id'] = inventory_location_id
2596 vals['location_dest_id'] = todo_line['location_id']
2597 vals['product_uom_qty'] = -todo_line['product_qty']
2599 #found less than expected
2600 vals['location_id'] = todo_line['location_id']
2601 vals['location_dest_id'] = inventory_location_id
2602 vals['product_uom_qty'] = todo_line['product_qty']
2603 return stock_move_obj.create(cr, uid, vals, context=context)
2605 def action_check(self, cr, uid, ids, context=None):
2606 """ Checks the inventory and computes the stock move to do
2609 inventory_line_obj = self.pool.get('stock.inventory.line')
2610 stock_move_obj = self.pool.get('stock.move')
2611 for inventory in self.browse(cr, uid, ids, context=context):
2612 #first remove the existing stock moves linked to this inventory
2613 move_ids = [move.id for move in inventory.move_ids]
2614 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2615 for line in inventory.line_ids:
2616 #compare the checked quantities on inventory lines to the theorical one
2617 inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context)
2619 def action_cancel_draft(self, cr, uid, ids, context=None):
2620 """ Cancels the stock move and change inventory state to draft.
2623 for inv in self.browse(cr, uid, ids, context=context):
2624 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2625 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2628 def action_cancel_inventory(self, cr, uid, ids, context=None):
2629 self.action_cancel_draft(cr, uid, ids, context=context)
2631 def prepare_inventory(self, cr, uid, ids, context=None):
2632 inventory_line_obj = self.pool.get('stock.inventory.line')
2633 for inventory in self.browse(cr, uid, ids, context=context):
2634 #clean the existing inventory lines before redoing an inventory proposal
2635 line_ids = [line.id for line in inventory.line_ids]
2636 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2637 #compute the inventory lines and create them
2638 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2639 for product_line in vals:
2640 inventory_line_obj.create(cr, uid, product_line, context=context)
2641 return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
2643 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2644 location_obj = self.pool.get('stock.location')
2645 product_obj = self.pool.get('product.product')
2646 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2647 domain = ' location_id in %s'
2648 args = (tuple(location_ids),)
2649 if inventory.partner_id:
2650 domain += ' and owner_id = %s'
2651 args += (inventory.partner_id.id,)
2652 if inventory.lot_id:
2653 domain += ' and lot_id = %s'
2654 args += (inventory.lot_id.id,)
2655 if inventory.product_id:
2656 domain += ' and product_id = %s'
2657 args += (inventory.product_id.id,)
2658 if inventory.package_id:
2659 domain += ' and package_id = %s'
2660 args += (inventory.package_id.id,)
2663 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2664 FROM stock_quant WHERE''' + domain + '''
2665 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2668 for product_line in cr.dictfetchall():
2669 #replace the None the dictionary by False, because falsy values are tested later on
2670 for key, value in product_line.items():
2672 product_line[key] = False
2673 product_line['inventory_id'] = inventory.id
2674 product_line['theoretical_qty'] = product_line['product_qty']
2675 if product_line['product_id']:
2676 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2677 product_line['product_uom_id'] = product.uom_id.id
2678 vals.append(product_line)
2682 class stock_inventory_line(osv.osv):
2683 _name = "stock.inventory.line"
2684 _description = "Inventory Line"
2685 _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2687 def _get_product_name_change(self, cr, uid, ids, context=None):
2688 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2690 def _get_location_change(self, cr, uid, ids, context=None):
2691 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2693 def _get_prodlot_change(self, cr, uid, ids, context=None):
2694 return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2697 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2698 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2699 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2700 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2701 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2702 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2703 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2704 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2705 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2706 'theoretical_qty': fields.float('Theoretical Quantity', readonly=True),
2707 'partner_id': fields.many2one('res.partner', 'Owner'),
2708 'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
2709 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2710 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2711 'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
2712 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2713 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2714 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
2715 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2716 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2717 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
2718 'stock.production.lot': (_get_prodlot_change, ['name'], 20),
2719 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
2726 def _resolve_inventory_line(self, cr, uid, inventory_line, context=None):
2727 stock_move_obj = self.pool.get('stock.move')
2728 diff = inventory_line.theoretical_qty - inventory_line.product_qty
2731 #each theorical_lines where difference between theoretical and checked quantities is not 0 is a line for which we need to create a stock move
2733 'name': _('INV:') + (inventory_line.inventory_id.name or ''),
2734 'product_id': inventory_line.product_id.id,
2735 'product_uom': inventory_line.product_uom_id.id,
2736 'date': inventory_line.inventory_id.date,
2737 'company_id': inventory_line.inventory_id.company_id.id,
2738 'inventory_id': inventory_line.inventory_id.id,
2739 'state': 'confirmed',
2740 'restrict_lot_id': inventory_line.prod_lot_id.id,
2741 'restrict_partner_id': inventory_line.partner_id.id,
2743 inventory_location_id = inventory_line.product_id.property_stock_inventory.id
2745 #found more than expected
2746 vals['location_id'] = inventory_location_id
2747 vals['location_dest_id'] = inventory_line.location_id.id
2748 vals['product_uom_qty'] = -diff
2750 #found less than expected
2751 vals['location_id'] = inventory_line.location_id.id
2752 vals['location_dest_id'] = inventory_location_id
2753 vals['product_uom_qty'] = diff
2754 return stock_move_obj.create(cr, uid, vals, context=context)
2756 def restrict_change(self, cr, uid, ids, theoretical_qty, context=None):
2757 if ids and theoretical_qty:
2758 #if the user try to modify a line prepared by openerp, reject the change and display an error message explaining how he should do
2759 old_value = self.browse(cr, uid, ids[0], context=context)
2762 'product_id': old_value.product_id.id,
2763 'product_uom_id': old_value.product_uom_id.id,
2764 'location_id': old_value.location_id.id,
2765 'prod_lot_id': old_value.prod_lot_id.id,
2766 'package_id': old_value.package_id.id,
2767 'partner_id': old_value.partner_id.id,
2770 'title': _('Error'),
2771 'message': _('You can only change the checked quantity of an existing inventory line. If you want modify a data, please set the checked quantity to 0 and create a new inventory line.')
2776 def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None):
2778 @param location_id: Location id
2779 @param product: Changed product_id
2780 @param uom: UoM product
2781 @return: Dictionary of changed values
2783 if ids and theoretical_qty:
2784 return self.restrict_change(cr, uid, ids, theoretical_qty, context=context)
2786 return {'value': {'product_uom_id': False}}
2787 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context)
2788 return {'value': {'product_uom_id': uom or obj_product.uom_id.id}}
2791 #----------------------------------------------------------
2793 #----------------------------------------------------------
2794 class stock_warehouse(osv.osv):
2795 _name = "stock.warehouse"
2796 _description = "Warehouse"
2799 'name': fields.char('Warehouse Name', required=True, select=True),
2800 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, select=True),
2801 'partner_id': fields.many2one('res.partner', 'Address'),
2802 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2803 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', domain=[('usage', '=', 'internal')], required=True),
2804 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2805 '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'),
2806 'reception_steps': fields.selection([
2807 ('one_step', 'Receive goods directly in stock (1 step)'),
2808 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2809 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments',
2810 help="Default incoming route to follow", required=True),
2811 'delivery_steps': fields.selection([
2812 ('ship_only', 'Ship directly from stock (Ship only)'),
2813 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2814 ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings',
2815 help="Default outgoing route to follow", required=True),
2816 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2817 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2818 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2819 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2820 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2821 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2822 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2823 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2824 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2825 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2826 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2827 'reception_route_id': fields.many2one('stock.location.route', 'Receipt Route'),
2828 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2829 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2830 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2831 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes',
2832 help="Routes will be created for these resupply warehouses and you can select them on products and product categories"),
2833 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"),
2836 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2837 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2838 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2839 resupply_wh_ids.add(default_resupply_wh_id)
2840 resupply_wh_ids = list(resupply_wh_ids)
2841 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2843 def _get_external_transit_location(self, cr, uid, warehouse, context=None):
2844 ''' returns browse record of inter company transit location, if found'''
2845 data_obj = self.pool.get('ir.model.data')
2846 location_obj = self.pool.get('stock.location')
2848 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2851 return location_obj.browse(cr, uid, inter_wh_loc, context=context)
2853 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2855 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2856 'warehouse_selectable': False,
2857 'product_selectable': True,
2858 'product_categ_selectable': True,
2859 'supplied_wh_id': warehouse.id,
2860 'supplier_wh_id': wh.id,
2863 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2864 route_obj = self.pool.get('stock.location.route')
2865 pull_obj = self.pool.get('procurement.rule')
2866 #create route selectable on the product to resupply the warehouse from another one
2867 external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context)
2868 internal_transit_location = warehouse.company_id.internal_transit_location_id
2869 input_loc = warehouse.wh_input_stock_loc_id
2870 if warehouse.reception_steps == 'one_step':
2871 input_loc = warehouse.lot_stock_id
2872 for wh in supplier_warehouses:
2873 transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location
2874 if transit_location:
2875 output_loc = wh.wh_output_stock_loc_id
2876 if wh.delivery_steps == 'ship_only':
2877 output_loc = wh.lot_stock_id
2878 # Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
2879 mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context)[0]
2880 pull_obj.create(cr, uid, mto_pull_vals, context=context)
2881 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2882 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2883 values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)]
2884 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2885 for pull_rule in pull_rules_list:
2886 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2887 #if the warehouse is also set as default resupply method, assign this route automatically to the warehouse
2888 if default_resupply_wh and default_resupply_wh.id == wh.id:
2889 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2892 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2893 'reception_steps': 'one_step',
2894 'delivery_steps': 'ship_only',
2896 _sql_constraints = [
2897 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2898 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2901 def _get_partner_locations(self, cr, uid, ids, context=None):
2902 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2903 data_obj = self.pool.get('ir.model.data')
2904 location_obj = self.pool.get('stock.location')
2906 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2907 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2909 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2910 customer_loc = customer_loc and customer_loc[0] or False
2911 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2912 supplier_loc = supplier_loc and supplier_loc[0] or False
2913 if not (customer_loc and supplier_loc):
2914 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2915 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2917 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2918 location_obj = self.pool.get('stock.location')
2920 new_reception_step = new_reception_step or warehouse.reception_steps
2921 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2922 if warehouse.reception_steps != new_reception_step:
2923 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2924 if new_reception_step != 'one_step':
2925 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2926 if new_reception_step == 'three_steps':
2927 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2929 if warehouse.delivery_steps != new_delivery_step:
2930 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2931 if new_delivery_step != 'ship_only':
2932 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2933 if new_delivery_step == 'pick_pack_ship':
2934 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2937 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2939 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2940 'product_categ_selectable': True,
2941 'product_selectable': False,
2945 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2946 pull_rules_list = []
2947 for from_loc, dest_loc, pick_type_id, warehouse in values:
2948 pull_rules_list.append({
2949 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2950 'location_src_id': from_loc.id,
2951 'location_id': dest_loc.id,
2952 'route_id': new_route_id,
2954 'picking_type_id': pick_type_id,
2955 'procure_method': warehouse.lot_stock_id.id != from_loc.id and 'make_to_order' or 'make_to_stock', # first part of the resuply route is MTS
2956 'warehouse_id': supplied_warehouse.id,
2957 'propagate_warehouse_id': warehouse.id,
2959 return pull_rules_list
2961 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2963 push_rules_list = []
2964 pull_rules_list = []
2965 for from_loc, dest_loc, pick_type_id in values:
2966 push_rules_list.append({
2967 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2968 'location_from_id': from_loc.id,
2969 'location_dest_id': dest_loc.id,
2970 'route_id': new_route_id,
2972 'picking_type_id': pick_type_id,
2974 'warehouse_id': warehouse.id,
2976 pull_rules_list.append({
2977 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2978 'location_src_id': from_loc.id,
2979 'location_id': dest_loc.id,
2980 'route_id': new_route_id,
2982 'picking_type_id': pick_type_id,
2983 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2985 'warehouse_id': warehouse.id,
2988 return push_rules_list, pull_rules_list
2990 def _get_mto_route(self, cr, uid, context=None):
2991 route_obj = self.pool.get('stock.location.route')
2992 data_obj = self.pool.get('ir.model.data')
2994 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2996 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2997 mto_route_id = mto_route_id and mto_route_id[0] or False
2998 if not mto_route_id:
2999 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
3002 def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None):
3003 """ Checks that the moves from the different """
3004 pull_obj = self.pool.get('procurement.rule')
3005 mto_route_id = self._get_mto_route(cr, uid, context=context)
3006 rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context)
3007 pull_obj.unlink(cr, uid, rules, context=context)
3009 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
3010 mto_route_id = self._get_mto_route(cr, uid, context=context)
3012 for value in values:
3013 from_loc, dest_loc, pick_type_id = value
3015 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
3016 'location_src_id': from_loc.id,
3017 'location_id': dest_loc.id,
3018 'route_id': mto_route_id,
3020 'picking_type_id': pick_type_id,
3021 'procure_method': 'make_to_order',
3023 'warehouse_id': warehouse.id,
3027 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
3029 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
3030 'warehouse_selectable': False,
3031 'product_selectable': True,
3032 'product_categ_selectable': True,
3033 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
3037 def create_routes(self, cr, uid, ids, warehouse, context=None):
3039 route_obj = self.pool.get('stock.location.route')
3040 pull_obj = self.pool.get('procurement.rule')
3041 push_obj = self.pool.get('stock.location.path')
3042 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3043 #create reception route and rules
3044 route_name, values = routes_dict[warehouse.reception_steps]
3045 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3046 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
3047 wh_route_ids.append((4, reception_route_id))
3048 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
3049 #create the push/pull rules
3050 for push_rule in push_rules_list:
3051 push_obj.create(cr, uid, vals=push_rule, context=context)
3052 for pull_rule in pull_rules_list:
3053 #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
3054 pull_rule['procure_method'] = 'make_to_order'
3055 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3057 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
3058 route_name, values = routes_dict[warehouse.delivery_steps]
3059 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3060 #create the route and its pull rules
3061 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
3062 wh_route_ids.append((4, delivery_route_id))
3063 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
3064 for pull_rule in pull_rules_list:
3065 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3066 #create MTO pull rule and link it to the generic MTO route
3067 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3068 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
3070 #create a route for cross dock operations, that can be set on products and product categories
3071 route_name, values = routes_dict['crossdock']
3072 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
3073 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
3074 wh_route_ids.append((4, crossdock_route_id))
3075 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)
3076 for pull_rule in pull_rules_list:
3077 # Fixed cross-dock is logically mto
3078 pull_rule['procure_method'] = 'make_to_order'
3079 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3081 #create route selectable on the product to resupply the warehouse from another one
3082 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
3084 #return routes and mto pull rule to store on the warehouse
3086 'route_ids': wh_route_ids,
3087 'mto_pull_id': mto_pull_id,
3088 'reception_route_id': reception_route_id,
3089 'delivery_route_id': delivery_route_id,
3090 'crossdock_route_id': crossdock_route_id,
3093 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
3094 picking_type_obj = self.pool.get('stock.picking.type')
3095 pull_obj = self.pool.get('procurement.rule')
3096 push_obj = self.pool.get('stock.location.path')
3097 route_obj = self.pool.get('stock.location.route')
3098 new_reception_step = new_reception_step or warehouse.reception_steps
3099 new_delivery_step = new_delivery_step or warehouse.delivery_steps
3101 #change the default source and destination location and (de)activate picking types
3102 input_loc = warehouse.wh_input_stock_loc_id
3103 if new_reception_step == 'one_step':
3104 input_loc = warehouse.lot_stock_id
3105 output_loc = warehouse.wh_output_stock_loc_id
3106 if new_delivery_step == 'ship_only':
3107 output_loc = warehouse.lot_stock_id
3108 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
3109 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
3110 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
3111 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
3113 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3114 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
3115 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
3116 route_name, values = routes_dict[new_delivery_step]
3117 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3118 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
3119 #create the pull rules
3120 for pull_rule in pull_rules_list:
3121 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3123 #update receipt route and rules: unlink the existing rules of the warehouse receipt route and recreate it
3124 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
3125 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
3126 route_name, values = routes_dict[new_reception_step]
3127 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3128 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
3129 #create the push/pull rules
3130 for push_rule in push_rules_list:
3131 push_obj.create(cr, uid, vals=push_rule, context=context)
3132 for pull_rule in pull_rules_list:
3133 #all pull rules in receipt route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
3134 pull_rule['procure_method'] = 'make_to_order'
3135 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3137 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
3140 dummy, values = routes_dict[new_delivery_step]
3141 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3142 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
3145 def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):
3146 seq_obj = self.pool.get('ir.sequence')
3147 picking_type_obj = self.pool.get('stock.picking.type')
3148 #create new sequences
3149 in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence in'), 'prefix': warehouse.code + '/IN/', 'padding': 5}, context=context)
3150 out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence out'), 'prefix': warehouse.code + '/OUT/', 'padding': 5}, context=context)
3151 pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': warehouse.code + '/PACK/', 'padding': 5}, context=context)
3152 pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': warehouse.code + '/PICK/', 'padding': 5}, context=context)
3153 int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': warehouse.code + '/INT/', 'padding': 5}, context=context)
3155 wh_stock_loc = warehouse.lot_stock_id
3156 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
3157 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
3158 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
3160 #fetch customer and supplier locations, for references
3161 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)
3163 #create in, out, internal picking types for warehouse
3164 input_loc = wh_input_stock_loc
3165 if warehouse.reception_steps == 'one_step':
3166 input_loc = wh_stock_loc
3167 output_loc = wh_output_stock_loc
3168 if warehouse.delivery_steps == 'ship_only':
3169 output_loc = wh_stock_loc
3171 #choose the next available color for the picking types of this warehouse
3173 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
3174 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
3175 #don't use sets to preserve the list order
3176 for x in all_used_colors:
3177 if x['color'] in available_colors:
3178 available_colors.remove(x['color'])
3179 if available_colors:
3180 color = available_colors[0]
3182 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
3183 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
3184 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
3186 in_type_id = picking_type_obj.create(cr, uid, vals={
3187 'name': _('Receipts'),
3188 'warehouse_id': warehouse.id,
3190 'sequence_id': in_seq_id,
3191 'default_location_src_id': supplier_loc.id,
3192 'default_location_dest_id': input_loc.id,
3193 'sequence': max_sequence + 1,
3194 'color': color}, context=context)
3195 out_type_id = picking_type_obj.create(cr, uid, vals={
3196 'name': _('Delivery Orders'),
3197 'warehouse_id': warehouse.id,
3199 'sequence_id': out_seq_id,
3200 'return_picking_type_id': in_type_id,
3201 'default_location_src_id': output_loc.id,
3202 'default_location_dest_id': customer_loc.id,
3203 'sequence': max_sequence + 4,
3204 'color': color}, context=context)
3205 picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
3206 int_type_id = picking_type_obj.create(cr, uid, vals={
3207 'name': _('Internal Transfers'),
3208 'warehouse_id': warehouse.id,
3210 'sequence_id': int_seq_id,
3211 'default_location_src_id': wh_stock_loc.id,
3212 'default_location_dest_id': wh_stock_loc.id,
3214 'sequence': max_sequence + 2,
3215 'color': color}, context=context)
3216 pack_type_id = picking_type_obj.create(cr, uid, vals={
3218 'warehouse_id': warehouse.id,
3220 'sequence_id': pack_seq_id,
3221 'default_location_src_id': wh_pack_stock_loc.id,
3222 'default_location_dest_id': output_loc.id,
3223 'active': warehouse.delivery_steps == 'pick_pack_ship',
3224 'sequence': max_sequence + 3,
3225 'color': color}, context=context)
3226 pick_type_id = picking_type_obj.create(cr, uid, vals={
3228 'warehouse_id': warehouse.id,
3230 'sequence_id': pick_seq_id,
3231 'default_location_src_id': wh_stock_loc.id,
3232 'default_location_dest_id': wh_pack_stock_loc.id,
3233 'active': warehouse.delivery_steps != 'ship_only',
3234 'sequence': max_sequence + 2,
3235 'color': color}, context=context)
3237 #write picking types on WH
3239 'in_type_id': in_type_id,
3240 'out_type_id': out_type_id,
3241 'pack_type_id': pack_type_id,
3242 'pick_type_id': pick_type_id,
3243 'int_type_id': int_type_id,
3245 super(stock_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)
3248 def create(self, cr, uid, vals, context=None):
3253 data_obj = self.pool.get('ir.model.data')
3254 seq_obj = self.pool.get('ir.sequence')
3255 picking_type_obj = self.pool.get('stock.picking.type')
3256 location_obj = self.pool.get('stock.location')
3258 #create view location for warehouse
3260 'name': _(vals.get('code')),
3262 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1],
3264 if vals.get('company_id'):
3265 loc_vals['company_id'] = vals.get('company_id')
3266 wh_loc_id = location_obj.create(cr, uid, loc_vals, context=context)
3267 vals['view_location_id'] = wh_loc_id
3268 #create all location
3269 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
3270 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
3271 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
3272 context_with_inactive = context.copy()
3273 context_with_inactive['active_test'] = False
3275 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
3276 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
3277 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
3278 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
3279 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
3281 for values in sub_locations:
3283 'name': values['name'],
3284 'usage': 'internal',
3285 'location_id': wh_loc_id,
3286 'active': values['active'],
3288 if vals.get('company_id'):
3289 loc_vals['company_id'] = vals.get('company_id')
3290 location_id = location_obj.create(cr, uid, loc_vals, context=context_with_inactive)
3291 vals[values['field']] = location_id
3294 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
3295 warehouse = self.browse(cr, uid, new_id, context=context)
3296 self.create_sequences_and_picking_types(cr, uid, warehouse, context=context)
3299 #create routes and push/pull rules
3300 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
3301 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
3304 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
3305 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
3307 def _format_routename(self, cr, uid, obj, name, context=None):
3308 return obj.name + ': ' + name
3310 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
3311 #fetch customer and supplier locations, for references
3312 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
3315 'one_step': (_('Receipt in 1 step'), []),
3316 'two_steps': (_('Receipt in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3317 'three_steps': (_('Receipt 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)]),
3318 '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)]),
3319 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
3320 '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)]),
3321 'pick_pack_ship': (_('Pick + Pack + Ship'), [(warehouse.lot_stock_id, warehouse.wh_pack_stock_loc_id, warehouse.pick_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)]),
3324 def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
3325 location_obj = self.pool.get('stock.location')
3326 route_obj = self.pool.get('stock.location.route')
3327 pull_obj = self.pool.get('procurement.rule')
3328 push_obj = self.pool.get('stock.location.path')
3330 location_id = warehouse.lot_stock_id.location_id.id
3331 location_obj.write(cr, uid, location_id, {'name': code}, context=context)
3332 #rename route and push-pull rules
3333 for route in warehouse.route_ids:
3334 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
3335 for pull in route.pull_ids:
3336 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3337 for push in route.push_ids:
3338 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3339 #change the mto pull rule name
3340 if warehouse.mto_pull_id.id:
3341 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
3343 def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None):
3344 """ Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """
3345 #Check routes that are being delivered by this warehouse and change the rule going to transit location
3346 route_obj = self.pool.get("stock.location.route")
3347 pull_obj = self.pool.get("procurement.rule")
3348 routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context)
3349 pulls = pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context)
3351 pull_obj.write(cr, uid, pulls, {'location_src_id': new_location, 'procure_method': change_to_multiple and "make_to_order" or "make_to_stock"}, context=context)
3352 # Create or clean MTO rules
3353 mto_route_id = self._get_mto_route(cr, uid, context=context)
3354 if not change_to_multiple:
3355 # If single delivery we should create the necessary MTO rules for the resupply
3356 # pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
3357 pull_recs = pull_obj.browse(cr, uid, pulls, context=context)
3358 transfer_locs = list(set([x.location_id for x in pull_recs]))
3359 vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs]
3360 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context)
3361 for mto_pull_val in mto_pull_vals:
3362 pull_obj.create(cr, uid, mto_pull_val, context=context)
3364 # We need to delete all the MTO pull rules, otherwise they risk to be used in the system
3365 pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
3367 pull_obj.unlink(cr, uid, pulls, context=context)
3369 def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None):
3371 Will check if the resupply routes to this warehouse follow the changes of number of receipt steps
3373 #Check routes that are being delivered by this warehouse and change the rule coming from transit location
3374 route_obj = self.pool.get("stock.location.route")
3375 pull_obj = self.pool.get("procurement.rule")
3376 routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context)
3377 pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')])
3379 pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context)
3381 def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None):
3383 old_val = warehouse.reception_steps
3384 new_val = reception_new
3385 change_to_one = (old_val != 'one_step' and new_val == 'one_step')
3386 change_to_multiple = (old_val == 'one_step' and new_val != 'one_step')
3387 if change_to_one or change_to_multiple:
3388 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id
3389 self._check_reception_resupply(cr, uid, warehouse, new_location, context=context)
3391 old_val = warehouse.delivery_steps
3392 new_val = delivery_new
3393 change_to_one = (old_val != 'ship_only' and new_val == 'ship_only')
3394 change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only')
3395 if change_to_one or change_to_multiple:
3396 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id
3397 self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context)
3399 def write(self, cr, uid, ids, vals, context=None):
3402 if isinstance(ids, (int, long)):
3404 seq_obj = self.pool.get('ir.sequence')
3405 route_obj = self.pool.get('stock.location.route')
3406 context_with_inactive = context.copy()
3407 context_with_inactive['active_test'] = False
3408 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
3409 #first of all, check if we need to delete and recreate route
3410 if vals.get('reception_steps') or vals.get('delivery_steps'):
3411 #activate and deactivate location according to reception and delivery option
3412 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
3413 # switch between route
3414 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
3415 # Check if we need to change something to resupply warehouses and associated MTO rules
3416 self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context)
3418 if vals.get('code') or vals.get('name'):
3419 name = warehouse.name
3421 if vals.get('name'):
3422 name = vals.get('name', warehouse.name)
3423 self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
3424 if warehouse.in_type_id:
3425 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)
3426 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)
3427 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)
3428 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)
3429 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)
3430 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
3431 for cmd in vals.get('resupply_wh_ids'):
3433 new_ids = set(cmd[2])
3434 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
3435 to_add_wh_ids = new_ids - old_ids
3437 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
3438 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
3439 to_remove_wh_ids = old_ids - new_ids
3440 if to_remove_wh_ids:
3441 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)
3442 if to_remove_route_ids:
3443 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
3447 if 'default_resupply_wh_id' in vals:
3448 if vals.get('default_resupply_wh_id') == warehouse.id:
3449 raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
3450 if warehouse.default_resupply_wh_id:
3451 #remove the existing resupplying route on the warehouse
3452 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)
3453 for inter_wh_route_id in to_remove_route_ids:
3454 self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]})
3455 if vals.get('default_resupply_wh_id'):
3456 #assign the new resupplying route on all products
3457 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)
3458 for inter_wh_route_id in to_assign_route_ids:
3459 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]})
3461 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
3463 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
3464 route_obj = self.pool.get("stock.location.route")
3465 all_routes = [route.id for route in warehouse.route_ids]
3466 all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context)
3467 all_routes += [warehouse.mto_pull_id.route_id.id]
3470 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
3472 for wh in self.browse(cr, uid, ids, context=context):
3473 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
3475 domain = [('id', 'in', all_routes)]
3477 'name': _('Warehouse\'s Routes'),
3479 'res_model': 'stock.location.route',
3480 'type': 'ir.actions.act_window',
3482 'view_mode': 'tree,form',
3483 'view_type': 'form',
3488 class stock_location_path(osv.osv):
3489 _name = "stock.location.path"
3490 _description = "Pushed Flows"
3493 def _get_rules(self, cr, uid, ids, context=None):
3495 for route in self.browse(cr, uid, ids, context=context):
3496 res += [x.id for x in route.push_ids]
3500 'name': fields.char('Operation Name', required=True),
3501 'company_id': fields.many2one('res.company', 'Company'),
3502 'route_id': fields.many2one('stock.location.route', 'Route'),
3503 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
3504 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
3505 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
3506 '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"),
3507 'auto': fields.selection(
3508 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
3510 required=True, select=1,
3511 help="This is used to define paths the product has to follow within the location tree.\n" \
3512 "The 'Automatic Move' value will create a stock move after the current one that will be "\
3513 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
3514 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
3516 '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'),
3517 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."),
3518 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3519 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3521 'stock.location.route': (_get_rules, ['sequence'], 10),
3522 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3524 'sequence': fields.integer('Sequence'),
3529 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3534 def _prepare_push_apply(self, cr, uid, rule, move, context=None):
3535 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3537 'location_id': move.location_dest_id.id,
3538 'location_dest_id': rule.location_dest_id.id,
3540 'company_id': rule.company_id and rule.company_id.id or False,
3541 'date_expected': newdate,
3542 'picking_id': False,
3543 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3544 'propagate': rule.propagate,
3545 'push_rule_id': rule.id,
3546 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3549 def _apply(self, cr, uid, rule, move, context=None):
3550 move_obj = self.pool.get('stock.move')
3551 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3552 if rule.auto == 'transparent':
3553 old_dest_location = move.location_dest_id.id
3554 move_obj.write(cr, uid, [move.id], {
3556 'date_expected': newdate,
3557 'location_dest_id': rule.location_dest_id.id
3560 #avoid looping if a push rule is not well configured
3561 if rule.location_dest_id.id != old_dest_location:
3562 #call again push_apply to see if a next step is defined
3563 move_obj._push_apply(cr, uid, [move], context=context)
3565 vals = self._prepare_push_apply(cr, uid, rule, move, context=context)
3566 move_id = move_obj.copy(cr, uid, move.id, vals, context=context)
3567 move_obj.write(cr, uid, [move.id], {
3568 'move_dest_id': move_id,
3570 move_obj.action_confirm(cr, uid, [move_id], context=None)
3573 # -------------------------
3574 # Packaging related stuff
3575 # -------------------------
3577 from openerp.report import report_sxw
3579 class stock_package(osv.osv):
3581 These are the packages, containing quants and/or other packages
3583 _name = "stock.quant.package"
3584 _description = "Physical Packages"
3585 _parent_name = "parent_id"
3586 _parent_store = True
3587 _parent_order = 'name'
3588 _order = 'parent_left'
3590 def name_get(self, cr, uid, ids, context=None):
3591 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3594 def _complete_name(self, cr, uid, ids, name, args, context=None):
3595 """ Forms complete name of location from parent location to child location.
3596 @return: Dictionary of values
3599 for m in self.browse(cr, uid, ids, context=context):
3601 parent = m.parent_id
3603 res[m.id] = parent.name + ' / ' + res[m.id]
3604 parent = parent.parent_id
3607 def _get_packages(self, cr, uid, ids, context=None):
3608 """Returns packages from quants for store"""
3610 for quant in self.browse(cr, uid, ids, context=context):
3611 if quant.package_id:
3612 res.add(quant.package_id.id)
3615 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3617 for pack in self.browse(cr, uid, ids, context=context):
3620 res.add(pack.parent_id.id)
3623 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3624 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3625 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id, 'owner_id': False})
3626 for pack in self.browse(cr, uid, ids, context=context):
3628 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3629 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3630 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3631 elif pack.children_ids:
3632 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3633 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3634 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3638 'name': fields.char('Package Reference', select=True, copy=False),
3639 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3640 'parent_left': fields.integer('Left Parent', select=1),
3641 'parent_right': fields.integer('Right Parent', select=1),
3642 'packaging_id': fields.many2one('product.packaging', 'Packaging', help="This field should be completed only if everything inside the package share the same product, otherwise it doesn't really makes sense.", select=True),
3643 'ul_id': fields.many2one('product.ul', 'Logistic Unit'),
3644 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3646 'stock.quant': (_get_packages, ['location_id'], 10),
3647 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3648 }, readonly=True, select=True),
3649 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
3650 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
3651 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
3652 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3654 'stock.quant': (_get_packages, ['company_id'], 10),
3655 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3656 }, readonly=True, select=True),
3657 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3659 'stock.quant': (_get_packages, ['owner_id'], 10),
3660 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3661 }, readonly=True, select=True),
3664 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3667 def _check_location_constraint(self, cr, uid, packs, context=None):
3668 '''checks that all quants in a package are stored in the same location. This function cannot be used
3669 as a constraint because it needs to be checked on pack operations (they may not call write on the
3672 quant_obj = self.pool.get('stock.quant')
3675 while parent.parent_id:
3676 parent = parent.parent_id
3677 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3678 quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0]
3679 location_id = quants and quants[0].location_id.id or False
3680 if not [quant.location_id.id == location_id for quant in quants]:
3681 raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
3684 def action_print(self, cr, uid, ids, context=None):
3685 context = dict(context or {}, active_ids=ids)
3686 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_package_barcode_small', context=context)
3689 def unpack(self, cr, uid, ids, context=None):
3690 quant_obj = self.pool.get('stock.quant')
3691 for package in self.browse(cr, uid, ids, context=context):
3692 quant_ids = [quant.id for quant in package.quant_ids]
3693 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3694 children_package_ids = [child_package.id for child_package in package.children_ids]
3695 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3696 #delete current package since it contains nothing anymore
3697 self.unlink(cr, uid, ids, context=context)
3698 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3700 def get_content(self, cr, uid, ids, context=None):
3701 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3702 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3704 def get_content_package(self, cr, uid, ids, context=None):
3705 quants_ids = self.get_content(cr, uid, ids, context=context)
3706 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3707 res['domain'] = [('id', 'in', quants_ids)]
3710 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3711 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3712 quant_obj = self.pool.get('stock.quant')
3713 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3715 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3716 if quant.product_id.id == product_id:
3720 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3721 '''This function computes the different product quantities for the given package
3723 quant_obj = self.pool.get('stock.quant')
3725 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3726 if quant.product_id.id not in res:
3727 res[quant.product_id.id] = 0
3728 res[quant.product_id.id] += quant.qty
3731 def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
3732 stock_pack_operation_obj = self.pool.get('stock.pack.operation')
3735 new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
3736 default['result_package_id'] = new_package_id
3737 op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
3738 for op_id in op_ids:
3739 stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
3742 class stock_pack_operation(osv.osv):
3743 _name = "stock.pack.operation"
3744 _description = "Packing Operation"
3746 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3747 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3748 #if the operation doesn't concern a package, it's not relevant to call this function
3749 if not operation.package_id or operation.product_id:
3750 return {operation.product_id.id: operation.remaining_qty}
3751 #get the total of products the package contains
3752 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3753 #reduce by the quantities linked to a move
3754 for record in operation.linked_move_operation_ids:
3755 if record.move_id.product_id.id not in res:
3756 res[record.move_id.product_id.id] = 0
3757 res[record.move_id.product_id.id] -= record.qty
3760 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3761 uom_obj = self.pool.get('product.uom')
3763 for ops in self.browse(cr, uid, ids, context=context):
3765 if ops.package_id and not ops.product_id:
3766 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3767 #should use _get_remaining_prod_quantities instead
3770 qty = ops.product_qty
3771 if ops.product_uom_id:
3772 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
3773 for record in ops.linked_move_operation_ids:
3775 #converting the remaining quantity in the pack operation UoM
3776 if ops.product_uom_id:
3777 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context)
3781 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3782 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3783 if product_id and not product_uom_id:
3784 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3785 res['value']['product_uom_id'] = product.uom_id.id
3788 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3790 uom_obj = self.pool.get('product.uom')
3792 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3793 product_uom_id = product_uom_id or product.uom_id.id
3794 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3795 if selected_uom.category_id.id != product.uom_id.category_id.id:
3797 'title': _('Warning: wrong UoM!'),
3798 '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)
3800 if product_qty and 'warning' not in res:
3801 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3802 if rounded_qty != product_qty:
3804 'title': _('Warning: wrong quantity!'),
3805 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3810 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3811 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3812 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3813 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3814 'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
3815 'package_id': fields.many2one('stock.quant.package', 'Source Package'), # 2
3816 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3817 'result_package_id': fields.many2one('stock.quant.package', 'Destination Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3818 'date': fields.datetime('Date', required=True),
3819 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3820 #'update_cost': fields.boolean('Need cost update'),
3821 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3822 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3823 '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'),
3824 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3825 'location_id': fields.many2one('stock.location', 'Source Location', required=True),
3826 'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True),
3827 'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
3831 'date': fields.date.context_today,
3833 'processed': lambda *a: 'false',
3836 def write(self, cr, uid, ids, vals, context=None):
3837 context = context or {}
3838 res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
3839 if isinstance(ids, (int, long)):
3841 if not context.get("no_recompute"):
3842 pickings = vals.get('picking_id') and [vals['picking_id']] or list(set([x.picking_id.id for x in self.browse(cr, uid, ids, context=context)]))
3843 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
3846 def create(self, cr, uid, vals, context=None):
3847 context = context or {}
3848 res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
3849 if vals.get("picking_id") and not context.get("no_recompute"):
3850 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
3853 def action_drop_down(self, cr, uid, ids, context=None):
3854 ''' Used by barcode interface to say that pack_operation has been moved from src location
3855 to destination location, if qty_done is less than product_qty than we have to split the
3856 operation in two to process the one with the qty moved
3859 move_obj = self.pool.get("stock.move")
3860 for pack_op in self.browse(cr, uid, ids, context=None):
3861 if pack_op.product_id and pack_op.location_id and pack_op.location_dest_id:
3862 move_obj.check_tracking_product(cr, uid, pack_op.product_id, pack_op.lot_id.id, pack_op.location_id, pack_op.location_dest_id, context=context)
3864 if pack_op.qty_done < pack_op.product_qty:
3865 # we split the operation in two
3866 op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
3867 self.write(cr, uid, [pack_op.id], {'product_qty': pack_op.product_qty - pack_op.qty_done, 'qty_done': 0, 'lot_id': False}, context=context)
3868 processed_ids.append(op)
3869 self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
3871 def create_and_assign_lot(self, cr, uid, id, name, context=None):
3872 ''' Used by barcode interface to create a new lot and assign it to the operation
3874 obj = self.browse(cr,uid,id,context)
3875 product_id = obj.product_id.id
3876 val = {'product_id': product_id}
3879 lots = self.pool.get('stock.production.lot').search(cr, uid, ['&', ('name', '=', name), ('product_id', '=', product_id)], context=context)
3881 new_lot_id = lots[0]
3882 val.update({'name': name})
3885 new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context)
3886 self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
3888 def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, increment=True, context=None):
3889 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3891 :param domain: list of tuple directly reusable as a domain
3892 context can receive a key 'current_package_id' with the package to consider for this operation
3898 #if current_package_id is given in the context, we increase the number of items in this package
3899 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3900 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3901 todo_operation_ids = []
3902 if existing_operation_ids:
3904 todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
3906 todo_operation_ids = existing_operation_ids
3907 if todo_operation_ids:
3908 #existing operation found for the given domain and picking => increment its quantity
3909 operation_id = todo_operation_ids[0]
3910 op_obj = self.browse(cr, uid, operation_id, context=context)
3911 qty = op_obj.qty_done
3915 qty -= 1 if qty >= 1 else 0
3916 if qty == 0 and op_obj.product_qty == 0:
3917 #we have a line with 0 qty set, so delete it
3918 self.unlink(cr, uid, [operation_id], context=context)
3920 self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
3922 #no existing operation found for the given domain and picking => create a new one
3923 picking_obj = self.pool.get("stock.picking")
3924 picking = picking_obj.browse(cr, uid, picking_id, context=context)
3926 'picking_id': picking_id,
3928 'location_id': picking.location_id.id,
3929 'location_dest_id': picking.location_dest_id.id,
3933 var_name, dummy, value = key
3935 if var_name == 'product_id':
3936 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3937 update_dict = {var_name: value}
3939 update_dict['product_uom_id'] = uom_id
3940 values.update(update_dict)
3941 operation_id = self.create(cr, uid, values, context=context)
3945 class stock_move_operation_link(osv.osv):
3947 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3949 _name = "stock.move.operation.link"
3950 _description = "Link between stock moves and pack operations"
3953 '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."),
3954 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3955 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3956 'reserved_quant_id': fields.many2one('stock.quant', 'Reserved Quant', help="Technical field containing the quant that created this link between an operation and a stock move. Used at the stock_move_obj.action_done() time to avoid seeking a matching quant again"),
3959 def get_specific_domain(self, cr, uid, record, context=None):
3960 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3961 having the record given as parameter making the link between the stock move and a pack operation'''
3963 op = record.operation_id
3965 if op.package_id and op.product_id:
3966 #if removing a product from a box, we restrict the choice of quants to this box
3967 domain.append(('package_id', '=', op.package_id.id))
3969 #if moving a box, we allow to take everything from inside boxes as well
3970 domain.append(('package_id', 'child_of', [op.package_id.id]))
3972 #if not given any information about package, we don't open boxes
3973 domain.append(('package_id', '=', False))
3974 #if lot info is given, we restrict choice to this lot otherwise we can take any
3976 domain.append(('lot_id', '=', op.lot_id.id))
3977 #if owner info is given, we restrict to this owner otherwise we restrict to no owner
3979 domain.append(('owner_id', '=', op.owner_id.id))
3981 domain.append(('owner_id', '=', False))
3984 class stock_warehouse_orderpoint(osv.osv):
3986 Defines Minimum stock rules.
3988 _name = "stock.warehouse.orderpoint"
3989 _description = "Minimum Inventory Rule"
3991 def subtract_procurements(self, cr, uid, orderpoint, context=None):
3992 '''This function returns quantity of product that needs to be deducted from the orderpoint computed quantity because there's already a procurement created with aim to fulfill it.
3995 uom_obj = self.pool.get("product.uom")
3996 for procurement in orderpoint.procurement_ids:
3997 if procurement.state in ('cancel', 'done'):
3999 procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context)
4000 for move in procurement.move_ids:
4001 #need to add the moves in draft as they aren't in the virtual quantity + moves that have not been created yet
4002 if move.state not in ('draft'):
4003 #if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted
4004 procurement_qty -= move.product_qty
4005 qty += procurement_qty
4008 def _check_product_uom(self, cr, uid, ids, context=None):
4010 Check if the UoM has the same category as the product standard UoM
4015 for rule in self.browse(cr, uid, ids, context=context):
4016 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
4020 def action_view_proc_to_process(self, cr, uid, ids, context=None):
4021 act_obj = self.pool.get('ir.actions.act_window')
4022 mod_obj = self.pool.get('ir.model.data')
4023 proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context)
4024 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
4028 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
4029 result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]"
4033 'name': fields.char('Name', required=True, copy=False),
4034 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
4035 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
4036 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
4037 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
4038 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]),
4039 'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True),
4040 'product_min_qty': fields.float('Minimum Quantity', required=True,
4041 digits_compute=dp.get_precision('Product Unit of Measure'),
4042 help="When the virtual stock goes below the Min Quantity specified for this field, Odoo generates "\
4043 "a procurement to bring the forecasted quantity to the Max Quantity."),
4044 'product_max_qty': fields.float('Maximum Quantity', required=True,
4045 digits_compute=dp.get_precision('Product Unit of Measure'),
4046 help="When the virtual stock goes below the Min Quantity, Odoo generates "\
4047 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
4048 'qty_multiple': fields.float('Qty Multiple', required=True,
4049 digits_compute=dp.get_precision('Product Unit of Measure'),
4050 help="The procurement quantity will be rounded up to this multiple. If it is 0, the exact quantity will be used. "),
4051 'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'),
4052 'group_id': fields.many2one('procurement.group', 'Procurement Group', help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by procurement rules will be grouped into one big picking.", copy=False),
4053 'company_id': fields.many2one('res.company', 'Company', required=True),
4056 'active': lambda *a: 1,
4057 'logic': lambda *a: 'max',
4058 'qty_multiple': lambda *a: 1,
4059 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
4060 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
4061 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
4063 _sql_constraints = [
4064 ('qty_multiple_check', 'CHECK( qty_multiple >= 0 )', 'Qty Multiple must be greater than or equal to zero.'),
4067 (_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']),
4070 def default_get(self, cr, uid, fields, context=None):
4071 warehouse_obj = self.pool.get('stock.warehouse')
4072 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
4073 # default 'warehouse_id' and 'location_id'
4074 if 'warehouse_id' not in res:
4075 warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or []
4076 res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False
4077 if 'location_id' not in res:
4078 res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False
4081 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
4082 """ Finds location id for changed warehouse.
4083 @param warehouse_id: Changed id of warehouse.
4084 @return: Dictionary of values.
4087 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
4088 v = {'location_id': w.lot_stock_id.id}
4092 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
4093 """ Finds UoM for changed product.
4094 @param product_id: Changed id of product.
4095 @return: Dictionary of values.
4098 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
4099 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
4100 v = {'product_uom': prod.uom_id.id}
4101 return {'value': v, 'domain': d}
4102 return {'domain': {'product_uom': []}}
4104 class stock_picking_type(osv.osv):
4105 _name = "stock.picking.type"
4106 _description = "The picking type determines the picking view"
4109 def open_barcode_interface(self, cr, uid, ids, context=None):
4110 final_url = "/barcode/web/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0'
4111 return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'}
4113 def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
4114 picking_obj = self.pool.get('stock.picking')
4115 res = dict.fromkeys(ids, [])
4116 for picking_type_id in ids:
4117 #get last 10 pickings of this type
4118 picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
4120 for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
4121 if picking.date_done > picking.date:
4122 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Late'), 'value': -1})
4123 elif picking.backorder_id:
4124 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Backorder exists'), 'value': 0})
4126 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('OK'), 'value': 1})
4127 res[picking_type_id] = json.dumps(tristates)
4130 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
4131 obj = self.pool.get('stock.picking')
4133 'count_picking_draft': [('state', '=', 'draft')],
4134 'count_picking_waiting': [('state', '=', 'confirmed')],
4135 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
4136 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4137 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4138 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
4141 for field in domains:
4142 data = obj.read_group(cr, uid, domains[field] +
4143 [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
4144 ['picking_type_id'], ['picking_type_id'], context=context)
4145 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
4147 result.setdefault(tid, {})[field] = count.get(tid, 0)
4149 if result[tid]['count_picking']:
4150 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
4151 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
4153 result[tid]['rate_picking_late'] = 0
4154 result[tid]['rate_picking_backorders'] = 0
4157 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
4158 if not picking_code:
4161 obj_data = self.pool.get('ir.model.data')
4162 stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock')
4165 'default_location_src_id': stock_loc,
4166 'default_location_dest_id': stock_loc,
4168 if picking_code == 'incoming':
4169 result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers')
4170 elif picking_code == 'outgoing':
4171 result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers')
4172 return {'value': result}
4174 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
4175 return dict(self.name_get(cr, uid, ids, context=context))
4177 def name_get(self, cr, uid, ids, context=None):
4178 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
4181 if not isinstance(ids, list):
4186 for record in self.browse(cr, uid, ids, context=context):
4188 if record.warehouse_id:
4189 name = record.warehouse_id.name + ': ' +name
4190 if context.get('special_shortened_wh_name'):
4191 if record.warehouse_id:
4192 name = record.warehouse_id.name
4194 name = _('Customer') + ' (' + record.name + ')'
4195 res.append((record.id, name))
4198 def _default_warehouse(self, cr, uid, context=None):
4199 user = self.pool.get('res.users').browse(cr, uid, uid, context)
4200 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
4201 return res and res[0] or False
4204 'name': fields.char('Picking Type Name', translate=True, required=True),
4205 'complete_name': fields.function(_get_name, type='char', string='Name'),
4206 'color': fields.integer('Color'),
4207 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
4208 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
4209 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
4210 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
4211 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
4212 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
4213 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
4214 'active': fields.boolean('Active'),
4216 # Statistics for the kanban view
4217 'last_done_picking': fields.function(_get_tristate_values,
4219 string='Last 10 Done Pickings'),
4221 'count_picking_draft': fields.function(_get_picking_count,
4222 type='integer', multi='_get_picking_count'),
4223 'count_picking_ready': fields.function(_get_picking_count,
4224 type='integer', multi='_get_picking_count'),
4225 'count_picking': fields.function(_get_picking_count,
4226 type='integer', multi='_get_picking_count'),
4227 'count_picking_waiting': fields.function(_get_picking_count,
4228 type='integer', multi='_get_picking_count'),
4229 'count_picking_late': fields.function(_get_picking_count,
4230 type='integer', multi='_get_picking_count'),
4231 'count_picking_backorders': fields.function(_get_picking_count,
4232 type='integer', multi='_get_picking_count'),
4234 'rate_picking_late': fields.function(_get_picking_count,
4235 type='integer', multi='_get_picking_count'),
4236 'rate_picking_backorders': fields.function(_get_picking_count,
4237 type='integer', multi='_get_picking_count'),
4241 'warehouse_id': _default_warehouse,
4245 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: