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
28 from openerp.osv import fields, osv
29 from openerp.tools.translate import _
30 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
31 from openerp import SUPERUSER_ID, api, models
32 import openerp.addons.decimal_precision as dp
33 from openerp.addons.procurement import procurement
37 _logger = logging.getLogger(__name__)
38 #----------------------------------------------------------
40 #----------------------------------------------------------
41 class stock_incoterms(osv.osv):
42 _name = "stock.incoterms"
43 _description = "Incoterms"
45 '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."),
46 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
47 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
53 #----------------------------------------------------------
55 #----------------------------------------------------------
57 class stock_location(osv.osv):
58 _name = "stock.location"
59 _description = "Inventory Locations"
60 _parent_name = "location_id"
62 _parent_order = 'name'
63 _order = 'parent_left'
64 _rec_name = 'complete_name'
66 def _location_owner(self, cr, uid, location, context=None):
67 ''' Return the company owning the location if any '''
68 return location and (location.usage == 'internal') and location.company_id or False
70 def _complete_name(self, cr, uid, ids, name, args, context=None):
71 """ Forms complete name of location from parent location to child location.
72 @return: Dictionary of values
75 for m in self.browse(cr, uid, ids, context=context):
77 parent = m.location_id
79 res[m.id] = parent.name + ' / ' + res[m.id]
80 parent = parent.location_id
83 def _get_sublocations(self, cr, uid, ids, context=None):
84 """ return all sublocations of the given stock locations (included) """
87 context_with_inactive = context.copy()
88 context_with_inactive['active_test'] = False
89 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
91 def _name_get(self, cr, uid, location, context=None):
93 while location.location_id and location.usage != 'view':
94 location = location.location_id
95 name = location.name + '/' + name
98 def name_get(self, cr, uid, ids, context=None):
100 for location in self.browse(cr, uid, ids, context=context):
101 res.append((location.id, self._name_get(cr, uid, location, context=context)))
105 'name': fields.char('Location Name', required=True, translate=True),
106 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
107 'usage': fields.selection([
108 ('supplier', 'Supplier Location'),
110 ('internal', 'Internal Location'),
111 ('customer', 'Customer Location'),
112 ('inventory', 'Inventory'),
113 ('procurement', 'Procurement'),
114 ('production', 'Production'),
115 ('transit', 'Transit Location')],
116 'Location Type', required=True,
117 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
118 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
119 \n* Internal Location: Physical locations inside your own warehouses,
120 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
121 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
122 \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.
123 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
124 \n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations
126 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
127 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
128 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
129 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
131 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
133 'comment': fields.text('Additional Information'),
134 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
135 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
136 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
138 'parent_left': fields.integer('Left Parent', select=1),
139 'parent_right': fields.integer('Right Parent', select=1),
141 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
142 'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
143 '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."),
144 '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."),
145 'barcode': fields.char('Barcode', oldname='loc_barcode'),
150 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
154 'scrap_location': False,
156 _sql_constraints = [('barcode_company_uniq', 'unique (barcode,company_id)', 'The barcode for a location must be unique per company !')]
158 def create(self, cr, uid, default, context=None):
159 if not default.get('barcode', False):
160 default.update({'barcode': default.get('complete_name', False)})
161 return super(stock_location, self).create(cr, uid, default, context=context)
163 def get_putaway_strategy(self, cr, uid, location, product, context=None):
164 ''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.'''
165 putaway_obj = self.pool.get('product.putaway')
168 if loc.putaway_strategy_id:
169 res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context)
172 loc = loc.location_id
174 def _default_removal_strategy(self, cr, uid, context=None):
177 def get_removal_strategy(self, cr, uid, location, product, context=None):
178 ''' Returns the removal strategy to consider for the given product and location.
179 :param location: browse record (stock.location)
180 :param product: browse record (product.product)
183 if product.categ_id.removal_strategy_id:
184 return product.categ_id.removal_strategy_id.method
187 if loc.removal_strategy_id:
188 return loc.removal_strategy_id.method
189 loc = loc.location_id
190 return self._default_removal_strategy(cr, uid, context=context)
193 def get_warehouse(self, cr, uid, location, context=None):
195 Returns warehouse id of warehouse that contains location
196 :param location: browse record (stock.location)
198 wh_obj = self.pool.get("stock.warehouse")
199 whs = wh_obj.search(cr, uid, [('view_location_id.parent_left', '<=', location.parent_left),
200 ('view_location_id.parent_right', '>=', location.parent_left)], context=context)
201 return whs and whs[0] or False
203 #----------------------------------------------------------
205 #----------------------------------------------------------
207 class stock_location_route(osv.osv):
208 _name = 'stock.location.route'
209 _description = "Inventory Routes"
213 'name': fields.char('Route Name', required=True),
214 'sequence': fields.integer('Sequence'),
215 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules', copy=True),
216 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
217 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules', copy=True),
218 'product_selectable': fields.boolean('Applicable on Product'),
219 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
220 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
221 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
222 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
223 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
227 'sequence': lambda self, cr, uid, ctx: 0,
229 'product_selectable': True,
230 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
233 def write(self, cr, uid, ids, vals, context=None):
234 '''when a route is deactivated, deactivate also its pull and push rules'''
235 if isinstance(ids, (int, long)):
237 res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context)
241 for route in self.browse(cr, uid, ids, context=context):
243 push_ids += [r.id for r in route.push_ids if r.active != vals['active']]
245 pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']]
247 self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context)
249 self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context)
252 #----------------------------------------------------------
254 #----------------------------------------------------------
256 class stock_quant(osv.osv):
258 Quants are the smallest unit of stock physical instances
260 _name = "stock.quant"
261 _description = "Quants"
263 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
264 """ Forms complete name of location from parent location to child location.
265 @return: Dictionary of values
268 for q in self.browse(cr, uid, ids, context=context):
270 res[q.id] = q.product_id.code or ''
272 res[q.id] = q.lot_id.name
273 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
276 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
277 context = dict(context or {})
279 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
280 for quant in self.browse(cr, uid, ids, context=context):
281 context.pop('force_company', None)
282 if quant.company_id.id != uid_company_id:
283 #if the company of the quant is different than the current user company, force the company in the context
284 #then re-do a browse to read the property fields for the good company.
285 context['force_company'] = quant.company_id.id
286 quant = self.browse(cr, uid, quant.id, context=context)
287 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
290 def _get_inventory_value(self, cr, uid, quant, context=None):
291 return quant.product_id.standard_price * quant.qty
294 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
295 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict", readonly=True, select=True),
296 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict", readonly=True, select=True),
297 '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),
298 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant", readonly=True, select=True),
299 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', readonly=True, store=True),
300 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for", readonly=True, select=True),
301 'lot_id': fields.many2one('stock.production.lot', 'Lot', readonly=True, select=True),
302 'cost': fields.float('Unit Cost'),
303 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant", readonly=True, select=True),
305 'create_date': fields.datetime('Creation Date', readonly=True),
306 'in_date': fields.datetime('Incoming Date', readonly=True, select=True),
308 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
309 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True, readonly=True, select=True),
310 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
312 # Used for negative quants to reconcile after compensated by a new positive one
313 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from', readonly=True, select=True),
314 '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),
315 'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", readonly=True,
316 help="Technical field used to record the destination location of a move that created a negative quant"),
320 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
323 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
324 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
325 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
326 if 'inventory_value' in fields:
328 if '__domain' in line:
329 lines = self.search(cr, uid, line['__domain'], context=context)
331 for line2 in self.browse(cr, uid, lines, context=context):
332 inv_value += line2.inventory_value
333 line['inventory_value'] = inv_value
336 def action_view_quant_history(self, cr, uid, ids, context=None):
338 This function returns an action that display the history of the quant, which
339 mean all the stock moves that lead to this quant creation with this quant quantity.
341 mod_obj = self.pool.get('ir.model.data')
342 act_obj = self.pool.get('ir.actions.act_window')
344 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
345 id = result and result[1] or False
346 result = act_obj.read(cr, uid, [id], context={})[0]
349 for quant in self.browse(cr, uid, ids, context=context):
350 move_ids += [move.id for move in quant.history_ids]
352 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
355 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
356 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
357 is also set to 'assigned'
359 :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
360 :param move: browse record
361 :param link: browse record (stock.move.operation.link)
364 reserved_availability = move.reserved_availability
365 #split quants if needed
366 for quant, qty in quants:
367 if qty <= 0.0 or (quant and quant.qty <= 0.0):
368 raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
371 self._quant_split(cr, uid, quant, qty, context=context)
372 toreserve.append(quant.id)
373 reserved_availability += quant.qty
376 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
377 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
379 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
380 #check if move'state needs to be set as 'assigned'
381 if reserved_availability == move.product_qty and move.state in ('confirmed', 'waiting'):
382 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
383 elif reserved_availability > 0 and not move.partially_available:
384 self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
386 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):
387 """Moves all given stock.quant in the given destination location. Unreserve from current move.
388 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
389 :param move: browse record (stock.move)
390 :param location_to: browse record (stock.location) depicting where the quants have to be moved
391 :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
392 :param lot_id: ID of the lot that must be set on the quants to move
393 :param owner_id: ID of the partner that must own the quants to move
394 :param src_package_id: ID of the package that contains the quants to move
395 :param dest_package_id: ID of the package that must be set on the moved quant
397 quants_reconcile = []
399 self._check_location(cr, uid, location_to, context=context)
400 for quant, qty in quants:
402 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
403 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)
405 self._quant_split(cr, uid, quant, qty, context=context)
407 to_move_quants.append(quant)
408 quants_reconcile.append(quant)
410 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]
411 self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
412 self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context)
413 if location_to.usage == 'internal':
414 if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context):
415 for quant in quants_reconcile:
417 self._quant_reconcile_negative(cr, uid, quant, move, context=context)
419 def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
420 vals = {'location_id': location_dest_id.id,
421 'history_ids': [(4, move.id)],
422 'package_id': dest_package_id,
423 'reservation_id': False}
424 self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
426 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):
427 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
428 the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached
429 it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on).
430 Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal
434 quants = [(None, qty)]
435 #don't look for quants in location that are of type production, supplier or inventory.
436 if location.usage in ['inventory', 'production', 'supplier']:
439 if not prefered_domain_list:
440 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)
441 for prefered_domain in prefered_domain_list:
443 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
445 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)
446 for quant in tmp_quants:
452 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
454 Use the removal strategies of product to search for the correct quants
455 If you inherit, put the super at the end of your method.
457 :location: browse record of the parent location where the quants have to be found
458 :product: browse record of the product to find
459 :qty in UoM of product
462 domain = domain or [('qty', '>', 0.0)]
463 if restrict_partner_id:
464 domain += [('owner_id', '=', restrict_partner_id)]
466 domain += [('lot_id', '=', restrict_lot_id)]
468 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context)
469 result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context)
472 def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None):
473 if removal_strategy == 'fifo':
474 order = 'in_date, id'
475 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
476 elif removal_strategy == 'lifo':
477 order = 'in_date desc, id desc'
478 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
479 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
481 def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False,
482 force_location_from=False, force_location_to=False, context=None):
483 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
487 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
488 location = force_location_to or move.location_dest_id
490 'product_id': move.product_id.id,
491 'location_id': location.id,
494 'history_ids': [(4, move.id)],
495 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
496 'company_id': move.company_id.id,
498 'owner_id': owner_id,
499 'package_id': dest_package_id,
502 if move.location_id.usage == 'internal':
503 #if we were trying to move something from an internal location and reach here (quant creation),
504 #it means that a negative quant has to be created as well.
505 negative_vals = vals.copy()
506 negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id
507 negative_vals['qty'] = -qty
508 negative_vals['cost'] = price_unit
509 negative_vals['negative_move_id'] = move.id
510 negative_vals['package_id'] = src_package_id
511 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
512 vals.update({'propagated_from_id': negative_quant_id})
514 #create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants
515 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
516 return self.browse(cr, uid, quant_id, context=context)
518 def _quant_split(self, cr, uid, quant, qty, context=None):
519 context = context or {}
520 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
522 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
523 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
525 return self.browse(cr, uid, new_quant, context=context)
527 def _get_latest_move(self, cr, uid, quant, context=None):
529 for m in quant.history_ids:
530 if not move or m.date > move.date:
534 @api.cr_uid_ids_context
535 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
537 for move in solving_quant.history_ids:
538 path.append((4, move.id))
539 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
541 def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
543 When new quant arrive in a location, try to reconcile it with
544 negative quants. If it's possible, apply the cost of the new
545 quant to the conter-part of the negative quant.
547 solving_quant = quant
548 dom = [('qty', '<', 0)]
550 dom += [('lot_id', '=', quant.lot_id.id)]
551 dom += [('owner_id', '=', quant.owner_id.id)]
552 dom += [('package_id', '=', quant.package_id.id)]
553 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
554 for quant_neg, qty in quants:
557 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
558 if not to_solve_quant_ids:
561 solved_quant_ids = []
562 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
565 solved_quant_ids.append(to_solve_quant.id)
566 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
567 solving_qty -= min(solving_qty, to_solve_quant.qty)
568 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
569 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
570 #if the reconciliation was not complete, we need to link together the remaining parts
571 if remaining_neg_quant:
572 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
573 if remaining_to_solve_quant_ids:
574 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
575 #delete the reconciled quants, as it is replaced by the solved quants
576 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
577 #price update + accounting entries adjustments
578 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
579 #merge history (and cost?)
580 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
581 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
582 solving_quant = remaining_solving_quant
584 def _price_update(self, cr, uid, ids, newprice, context=None):
585 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
587 def quants_unreserve(self, cr, uid, move, context=None):
588 related_quants = [x.id for x in move.reserved_quant_ids]
590 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
592 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
593 if move.partially_available:
594 self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
595 self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
597 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
598 ''' Implementation of removal strategies
599 If it can not reserve, it will return a tuple (None, qty)
603 domain += location and [('location_id', 'child_of', location.id)] or []
604 domain += [('product_id', '=', product.id)]
605 if context.get('force_company'):
606 domain += [('company_id', '=', context.get('force_company'))]
608 domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
612 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
614 res.append((None, quantity))
616 for quant in self.browse(cr, uid, quants, context=context):
617 if quantity >= abs(quant.qty):
618 res += [(quant, abs(quant.qty))]
619 quantity -= abs(quant.qty)
621 res += [(quant, quantity)]
627 def _check_location(self, cr, uid, location, context=None):
628 if location.usage == 'view':
629 raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
632 #----------------------------------------------------------
634 #----------------------------------------------------------
636 class stock_picking(osv.osv):
637 _name = "stock.picking"
638 _inherit = ['mail.thread']
639 _description = "Transfer"
640 _order = "priority desc, date asc, id desc"
642 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
643 move_obj = self.pool.get("stock.move")
645 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
646 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
648 def _set_priority(self, cr, uid, id, field, value, arg, context=None):
649 move_obj = self.pool.get("stock.move")
651 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
652 move_obj.write(cr, uid, move_ids, {'priority': value}, context=context)
654 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
655 """ Finds minimum and maximum dates for picking.
656 @return: Dictionary of values
660 res[id] = {'min_date': False, 'max_date': False, 'priority': '1'}
673 picking_id""", (tuple(ids),))
674 for pick, dt1, dt2, prio in cr.fetchall():
675 res[pick]['min_date'] = dt1
676 res[pick]['max_date'] = dt2
677 res[pick]['priority'] = prio
680 def create(self, cr, user, vals, context=None):
681 context = context or {}
682 if ('name' not in vals) or (vals.get('name') in ('/', False)):
683 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
684 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
685 vals['name'] = self.pool.get('ir.sequence').next_by_id(cr, user, sequence_id, context=context)
686 return super(stock_picking, self).create(cr, user, vals, context)
688 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
689 '''The state of a picking depends on the state of its related stock.move
690 draft: the picking has no line or any one of the lines is draft
691 done, draft, cancel: all lines are done / draft / cancel
692 confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial)
695 for pick in self.browse(cr, uid, ids, context=context):
696 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
697 res[pick.id] = 'draft'
699 if all([x.state == 'cancel' for x in pick.move_lines]):
700 res[pick.id] = 'cancel'
702 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
703 res[pick.id] = 'done'
706 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
707 order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
708 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
709 if pick.move_type == 'one':
710 res[pick.id] = order_inv[min(lst)]
712 #we are in the case of partial delivery, so if all move are assigned, picking
713 #should be assign too, else if one of the move is assigned, or partially available, picking should be
714 #in partially available state, otherwise, picking is in waiting or confirmed state
715 res[pick.id] = order_inv[max(lst)]
716 if not all(x == 2 for x in lst):
717 if any(x == 2 for x in lst):
718 res[pick.id] = 'partially_available'
720 #if all moves aren't assigned, check if we have one product partially available
721 for move in pick.move_lines:
722 if move.partially_available:
723 res[pick.id] = 'partially_available'
727 def _get_pickings(self, cr, uid, ids, context=None):
729 for move in self.browse(cr, uid, ids, context=context):
731 res.add(move.picking_id.id)
734 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
736 for pick in self.browse(cr, uid, ids, context=context):
738 if pick.pack_operation_ids:
742 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
744 for pick in self.browse(cr, uid, ids, context=context):
746 for move in pick.move_lines:
747 if move.reserved_quant_ids:
752 def check_group_lot(self, cr, uid, context=None):
753 """ This function will return true if we have the setting to use lots activated. """
754 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot')
756 def check_group_pack(self, cr, uid, context=None):
757 """ This function will return true if we have the setting to use package activated. """
758 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot')
760 def action_assign_owner(self, cr, uid, ids, context=None):
761 for picking in self.browse(cr, uid, ids, context=context):
762 packop_ids = [op.id for op in picking.pack_operation_ids]
763 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
766 'name': fields.char('Reference', select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
767 'origin': fields.char('Source Document', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
768 '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),
769 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
770 '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"),
771 'state': fields.function(_state_get, type="selection", copy=False,
773 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
774 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)},
777 ('cancel', 'Cancelled'),
778 ('waiting', 'Waiting Another Operation'),
779 ('confirmed', 'Waiting Availability'),
780 ('partially_available', 'Partially Available'),
781 ('assigned', 'Ready to Transfer'),
782 ('done', 'Transferred'),
783 ], string='Status', readonly=True, select=True, track_visibility='onchange',
785 * Draft: not confirmed yet and will not be scheduled until confirmed\n
786 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
787 * Waiting Availability: still waiting for the availability of products\n
788 * Partially Available: some products are available and reserved\n
789 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
790 * Transferred: has been processed, can't be modified or cancelled anymore\n
791 * Cancelled: has been cancelled, can't be confirmed anymore"""
793 'priority': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_priority, type='selection', selection=procurement.PROCUREMENT_PRIORITIES, string='Priority',
794 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",
795 track_visibility='onchange', required=True),
796 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
797 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'),
798 'max_date': fields.function(get_min_max_date, multi="min_max_date",
799 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"),
800 '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'),
801 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
802 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=True),
803 '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'),
804 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
805 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
806 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
807 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
808 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
809 '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"),
811 'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
812 # Used to search on pickings
813 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
814 '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),
815 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
816 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
817 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
819 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
820 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
822 'barcode_nomenclature_id': fields.many2one('barcode.nomenclature','Barcode Nomenclature', help='A barcode nomenclature', required="True"),
825 def _get_default_nomenclature(self, cr, uid, context=None):
826 nom_obj = self.pool.get('barcode.nomenclature')
827 res = nom_obj.search(cr, uid, [], limit=1, context=context)
829 return nom_obj.browse(cr, uid, res[0], context=context).id
835 'move_type': 'direct',
836 'priority': '1', # normal
837 'date': fields.datetime.now,
838 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c),
839 'recompute_pack_op': True,
840 'barcode_nomenclature_id': _get_default_nomenclature,
843 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
846 def do_print_picking(self, cr, uid, ids, context=None):
847 '''This function prints the picking list'''
848 context = dict(context or {}, active_ids=ids)
849 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
852 def action_confirm(self, cr, uid, ids, context=None):
854 todo_force_assign = []
855 for picking in self.browse(cr, uid, ids, context=context):
856 if picking.location_id.usage in ('supplier', 'inventory', 'production'):
857 todo_force_assign.append(picking.id)
858 for r in picking.move_lines:
859 if r.state == 'draft':
862 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
864 if todo_force_assign:
865 self.force_assign(cr, uid, todo_force_assign, context=context)
868 def action_assign(self, cr, uid, ids, context=None):
869 """ Check availability of picking moves.
870 This has the effect of changing the state and reserve quants on available moves, and may
871 also impact the state of the picking as it is computed based on move's states.
874 for pick in self.browse(cr, uid, ids, context=context):
875 if pick.state == 'draft':
876 self.action_confirm(cr, uid, [pick.id], context=context)
878 #skip the moves that don't need to be checked
879 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
881 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
882 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
885 def force_assign(self, cr, uid, ids, context=None):
886 """ Changes state of picking to available if moves are confirmed or waiting.
889 for pick in self.browse(cr, uid, ids, context=context):
890 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
891 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
892 #pack_operation might have changed and need to be recomputed
893 self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context)
896 def action_cancel(self, cr, uid, ids, context=None):
897 for pick in self.browse(cr, uid, ids, context=context):
898 ids2 = [move.id for move in pick.move_lines]
899 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
902 def action_done(self, cr, uid, ids, context=None):
903 """Changes picking state to done by processing the Stock Moves of the Picking
905 Normally that happens when the button "Done" is pressed on a Picking view.
908 for pick in self.browse(cr, uid, ids, context=context):
910 for move in pick.move_lines:
911 if move.state == 'draft':
912 todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
913 elif move.state in ('assigned', 'confirmed'):
916 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
919 def unlink(self, cr, uid, ids, context=None):
920 #on picking deletion, cancel its move then unlink them too
921 move_obj = self.pool.get('stock.move')
922 context = context or {}
923 for pick in self.browse(cr, uid, ids, context=context):
924 move_ids = [move.id for move in pick.move_lines]
925 move_obj.action_cancel(cr, uid, move_ids, context=context)
926 move_obj.unlink(cr, uid, move_ids, context=context)
927 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
929 def write(self, cr, uid, ids, vals, context=None):
930 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
931 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
932 if 'move_lines' in vals or 'pack_operation_ids' in vals:
933 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
936 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
937 """ 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.
939 if not backorder_moves:
940 backorder_moves = picking.move_lines
941 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
942 if 'do_only_split' in context and context['do_only_split']:
943 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
945 if backorder_move_ids:
946 backorder_id = self.copy(cr, uid, picking.id, {
949 'pack_operation_ids': [],
950 'backorder_id': picking.id,
952 backorder = self.browse(cr, uid, backorder_id, context=context)
953 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (backorder.name), context=context)
954 move_obj = self.pool.get("stock.move")
955 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
957 self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
958 self.action_confirm(cr, uid, [backorder_id], context=context)
962 @api.cr_uid_ids_context
963 def recheck_availability(self, cr, uid, picking_ids, context=None):
964 self.action_assign(cr, uid, picking_ids, context=context)
965 self.do_prepare_partial(cr, uid, picking_ids, context=context)
967 def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
968 """This method searches for the higher level packages that can be moved as a single operation, given a list of quants
969 to move and their suggested destination, and returns the list of matching packages.
971 # Try to find as much as possible top-level packages that can be moved
972 pack_obj = self.pool.get("stock.quant.package")
973 quant_obj = self.pool.get("stock.quant")
974 top_lvl_packages = set()
975 quants_to_compare = quants_suggested_locations.keys()
976 for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
980 pack_destination = False
982 pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
984 for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
985 # If the quant is not in the quants to compare and not in the common location
986 if not quant in quants_to_compare:
990 #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)
991 if not pack_destination:
992 pack_destination = quants_suggested_locations[quant]
993 elif pack_destination != quants_suggested_locations[quant]:
997 good_pack = test_pack
998 if test_pack.parent_id:
999 test_pack = test_pack.parent_id
1001 #stop the loop when there's no parent package anymore
1004 #stop the loop when the package test_pack is not totally reserved for moves of this picking
1005 #(some quants may be reserved for other picking or not reserved at all)
1008 top_lvl_packages.add(good_pack)
1009 return list(top_lvl_packages)
1011 def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
1012 """ returns a list of dict, ready to be used in create() of stock.pack.operation.
1014 :param picking: browse record (stock.picking)
1015 :param quants: browse record list (stock.quant). List of quants associated to the picking
1016 :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
1018 def _picking_putaway_apply(product):
1020 # Search putaway strategy
1021 if product_putaway_strats.get(product.id):
1022 location = product_putaway_strats[product.id]
1024 location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
1025 product_putaway_strats[product.id] = location
1026 return location or picking.location_dest_id.id
1028 pack_obj = self.pool.get("stock.quant.package")
1029 quant_obj = self.pool.get("stock.quant")
1032 #for each quant of the picking, find the suggested location
1033 quants_suggested_locations = {}
1034 product_putaway_strats = {}
1035 for quant in quants:
1038 suggested_location_id = _picking_putaway_apply(quant.product_id)
1039 quants_suggested_locations[quant] = suggested_location_id
1041 #find the packages we can movei as a whole
1042 top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
1043 # and then create pack operations for the top-level packages found
1044 for pack in top_lvl_packages:
1045 pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
1046 pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
1048 'picking_id': picking.id,
1049 'package_id': pack.id,
1051 'location_id': pack.location_id.id,
1052 'location_dest_id': quants_suggested_locations[pack_quants[0]],
1054 #remove the quants inside the package so that they are excluded from the rest of the computation
1055 for quant in pack_quants:
1056 del quants_suggested_locations[quant]
1058 # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
1059 for quant, dest_location_id in quants_suggested_locations.items():
1060 key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
1061 if qtys_grouped.get(key):
1062 qtys_grouped[key] += quant.qty
1064 qtys_grouped[key] = quant.qty
1066 # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
1067 for product, qty in forced_qties.items():
1070 suggested_location_id = _picking_putaway_apply(product)
1071 key = (product.id, False, False, False, picking.location_id.id, suggested_location_id)
1072 if qtys_grouped.get(key):
1073 qtys_grouped[key] += qty
1075 qtys_grouped[key] = qty
1077 # Create the necessary operations for the grouped quants and remaining qtys
1078 for key, qty in qtys_grouped.items():
1080 'picking_id': picking.id,
1082 'product_id': key[0],
1083 'package_id': key[1],
1086 'location_id': key[4],
1087 'location_dest_id': key[5],
1088 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id,
1092 @api.cr_uid_ids_context
1093 def open_barcode_interface(self, cr, uid, picking_ids, context=None):
1094 final_url="/stock/barcode/#action=stock.ui&picking_id="+str(picking_ids[0])
1095 return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
1097 @api.cr_uid_ids_context
1098 def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
1099 self.do_prepare_partial(cr, uid, picking_ids, context=context)
1100 return self.open_barcode_interface(cr, uid, picking_ids, context=context)
1102 @api.cr_uid_ids_context
1103 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
1104 context = context or {}
1105 pack_operation_obj = self.pool.get('stock.pack.operation')
1106 #used to avoid recomputing the remaining quantities at each new pack operation created
1107 ctx = context.copy()
1108 ctx['no_recompute'] = True
1110 #get list of existing operations and delete them
1111 existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
1112 if existing_package_ids:
1113 pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
1114 for picking in self.browse(cr, uid, picking_ids, context=context):
1115 forced_qties = {} # Quantity remaining after calculating reserved quants
1117 #Calculate packages, reserved quants, qtys of this picking's moves
1118 for move in picking.move_lines:
1119 if move.state not in ('assigned', 'confirmed'):
1121 move_quants = move.reserved_quant_ids
1122 picking_quants += move_quants
1123 forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
1124 #if we used force_assign() on the move, or if the move is incomming, forced_qty > 0
1126 if forced_qties.get(move.product_id):
1127 forced_qties[move.product_id] += forced_qty
1129 forced_qties[move.product_id] = forced_qty
1130 for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
1131 pack_operation_obj.create(cr, uid, vals, context=ctx)
1132 #recompute the remaining quantities all at once
1133 self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
1134 self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context)
1136 @api.cr_uid_ids_context
1137 def do_unreserve(self, cr, uid, picking_ids, context=None):
1139 Will remove all quants for picking in picking_ids
1141 moves_to_unreserve = []
1142 pack_line_to_unreserve = []
1143 for picking in self.browse(cr, uid, picking_ids, context=context):
1144 moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
1145 pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
1146 if moves_to_unreserve:
1147 if pack_line_to_unreserve:
1148 self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
1149 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
1151 def recompute_remaining_qty(self, cr, uid, picking, context=None):
1152 def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
1153 move_dict = prod2move_ids[product_id][index]
1154 qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
1155 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)
1156 if move_dict['remaining_qty'] == qty_on_link:
1157 prod2move_ids[product_id].pop(index)
1159 move_dict['remaining_qty'] -= qty_on_link
1162 def _create_link_for_quant(operation_id, quant, qty):
1163 """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
1164 if not quant.reservation_id.id:
1165 return _create_link_for_product(operation_id, quant.product_id.id, qty)
1167 for i in range(0, len(prod2move_ids[quant.product_id.id])):
1168 if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
1170 qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
1174 def _create_link_for_product(operation_id, product_id, qty):
1175 '''method that creates the link between a given operation and move(s) of given product, for the given quantity.
1176 Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
1178 if prod2move_ids.get(product_id):
1179 while prod2move_ids[product_id] and qty_to_assign > 0:
1180 qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
1181 qty_to_assign -= qty_on_link
1182 return qty_to_assign == 0
1184 uom_obj = self.pool.get('product.uom')
1185 package_obj = self.pool.get('stock.quant.package')
1186 quant_obj = self.pool.get('stock.quant')
1187 quants_in_package_done = set()
1190 #make a dictionary giving for each product, the moves and related quantity that can be used in operation links
1191 for move in picking.move_lines:
1192 if not prod2move_ids.get(move.product_id.id):
1193 prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
1195 prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
1197 need_rereserve = False
1198 #sort the operations in order to give higher priority to those with a package, then a serial number
1199 operations = picking.pack_operation_ids
1200 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))
1201 #delete existing operations to start again from scratch
1202 cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),))
1204 #1) first, try to create links when quants can be identified without any doubt
1205 for ops in operations:
1206 #for each operation, create the links with the stock move by seeking on the matching reserved quants,
1207 #and deffer the operation if there is some ambiguity on the move to select
1208 if ops.package_id and not ops.product_id:
1210 quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
1211 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1212 remaining_qty_on_quant = quant.qty
1213 if quant.reservation_id:
1214 #avoid quants being counted twice
1215 quants_in_package_done.add(quant.id)
1216 qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
1217 remaining_qty_on_quant -= qty_on_link
1218 if remaining_qty_on_quant:
1219 still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
1220 need_rereserve = True
1221 elif ops.product_id.id:
1222 #Check moves with same product
1223 qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
1224 for move_dict in prod2move_ids.get(ops.product_id.id, []):
1225 move = move_dict['move']
1226 for quant in move.reserved_quant_ids:
1227 if not qty_to_assign > 0:
1229 if quant.id in quants_in_package_done:
1232 #check if the quant is matching the operation details
1234 flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id])], context=context)) or False
1236 flag = not quant.package_id.id
1237 flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
1238 flag = flag and (ops.owner_id.id == quant.owner_id.id)
1240 max_qty_on_link = min(quant.qty, qty_to_assign)
1241 qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
1242 qty_to_assign -= qty_on_link
1243 if qty_to_assign > 0:
1244 #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
1245 #all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
1246 still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
1247 need_rereserve = True
1249 #2) then, process the remaining part
1250 all_op_processed = True
1251 for ops, product_id, remaining_qty in still_to_do:
1252 all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty)
1253 return (need_rereserve, all_op_processed)
1255 def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
1256 need_rereserve = False
1257 all_op_processed = True
1258 if picking.pack_operation_ids:
1259 need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
1260 return need_rereserve, all_op_processed
1262 @api.cr_uid_ids_context
1263 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
1264 for picking in self.browse(cr, uid, picking_ids, context=context):
1265 if picking.pack_operation_ids:
1266 self.recompute_remaining_qty(cr, uid, picking, context=context)
1268 def _prepare_values_extra_move(self, cr, uid, op, product, remaining_qty, context=None):
1270 Creates an extra move when there is no corresponding original move to be copied
1272 picking = op.picking_id
1274 'picking_id': picking.id,
1275 'location_id': picking.location_id.id,
1276 'location_dest_id': picking.location_dest_id.id,
1277 'product_id': product.id,
1278 'product_uom': product.uom_id.id,
1279 'product_uom_qty': remaining_qty,
1280 'name': _('Extra Move: ') + product.name,
1285 def _create_extra_moves(self, cr, uid, picking, context=None):
1286 '''This function creates move lines on a picking, at the time of do_transfer, based on
1287 unexpected product transfers (or exceeding quantities) found in the pack operations.
1289 move_obj = self.pool.get('stock.move')
1290 operation_obj = self.pool.get('stock.pack.operation')
1292 for op in picking.pack_operation_ids:
1293 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1294 if remaining_qty > 0:
1295 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1296 vals = self._prepare_values_extra_move(cr, uid, op, product, remaining_qty, context=context)
1297 moves.append(move_obj.create(cr, uid, vals, context=context))
1299 move_obj.action_confirm(cr, uid, moves, context=context)
1302 def rereserve_pick(self, cr, uid, ids, context=None):
1304 This can be used to provide a button that rereserves taking into account the existing pack operations
1306 for pick in self.browse(cr, uid, ids, context=context):
1307 self.rereserve_quants(cr, uid, pick, move_ids = [x.id for x in pick.move_lines], context=context)
1309 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1310 """ Unreserve quants then try to reassign quants."""
1311 stock_move_obj = self.pool.get('stock.move')
1313 self.do_unreserve(cr, uid, [picking.id], context=context)
1314 self.action_assign(cr, uid, [picking.id], context=context)
1316 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1317 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1319 @api.cr_uid_ids_context
1320 def do_enter_transfer_details(self, cr, uid, picking, context=None):
1325 'active_model': self._name,
1326 'active_ids': picking,
1327 'active_id': len(picking) and picking[0] or False
1330 created_id = self.pool['stock.transfer_details'].create(cr, uid, {'picking_id': len(picking) and picking[0] or False}, context)
1331 return self.pool['stock.transfer_details'].wizard_view(cr, uid, created_id, context)
1334 @api.cr_uid_ids_context
1335 def do_transfer(self, cr, uid, picking_ids, context=None):
1337 If no pack operation, we do simple action_done of the picking
1338 Otherwise, do the pack operations
1342 stock_move_obj = self.pool.get('stock.move')
1343 for picking in self.browse(cr, uid, picking_ids, context=context):
1344 if not picking.pack_operation_ids:
1345 self.action_done(cr, uid, [picking.id], context=context)
1348 need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
1349 #create extra moves in the picking (unexpected product moves coming from pack operations)
1351 if not all_op_processed:
1352 todo_move_ids += self._create_extra_moves(cr, uid, picking, context=context)
1355 #split move lines eventually
1357 toassign_move_ids = []
1358 for move in picking.move_lines:
1359 remaining_qty = move.remaining_qty
1360 if move.state in ('done', 'cancel'):
1361 #ignore stock moves cancelled or already done
1363 elif move.state == 'draft':
1364 toassign_move_ids.append(move.id)
1365 if remaining_qty == 0:
1366 if move.state in ('draft', 'assigned', 'confirmed'):
1367 todo_move_ids.append(move.id)
1368 elif remaining_qty > 0 and remaining_qty < move.product_qty:
1369 new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
1370 todo_move_ids.append(move.id)
1371 #Assign move as it was assigned before
1372 toassign_move_ids.append(new_move)
1373 if need_rereserve or not all_op_processed:
1374 if not picking.location_id.usage in ("supplier", "production", "inventory"):
1375 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1376 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1377 if todo_move_ids and not context.get('do_only_split'):
1378 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1379 elif context.get('do_only_split'):
1380 context = dict(context, split=todo_move_ids)
1382 self._create_backorder(cr, uid, picking, context=context)
1383 if toassign_move_ids:
1384 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1387 @api.cr_uid_ids_context
1388 def do_split(self, cr, uid, picking_ids, context=None):
1389 """ just split the picking (create a backorder) without making it 'done' """
1392 ctx = context.copy()
1393 ctx['do_only_split'] = True
1394 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1396 def get_next_picking_for_ui(self, cr, uid, context=None):
1397 """ returns the next pickings to process. Used in the barcode scanner UI"""
1400 domain = [('state', 'in', ('assigned', 'partially_available'))]
1401 if context.get('default_picking_type_id'):
1402 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1403 return self.search(cr, uid, domain, context=context)
1405 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1406 """ called when button 'done' is pushed in the barcode scanner UI """
1407 #write qty_done into field product_qty for every package_operation before doing the transfer
1408 pack_op_obj = self.pool.get('stock.pack.operation')
1409 for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
1410 pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
1411 self.do_transfer(cr, uid, [picking_id], context=context)
1412 #return id of next picking to work on
1413 return self.get_next_picking_for_ui(cr, uid, context=context)
1415 @api.cr_uid_ids_context
1416 def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
1417 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1418 Used in the barcode scanner UI and the normal interface as well.
1419 operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
1420 if operation_filter_ids == None:
1421 operation_filter_ids = []
1422 stock_operation_obj = self.pool.get('stock.pack.operation')
1423 package_obj = self.pool.get('stock.quant.package')
1424 stock_move_obj = self.pool.get('stock.move')
1425 for picking_id in picking_ids:
1426 operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
1427 if operation_filter_ids != []:
1428 operation_search_domain.append(('id', 'in', operation_filter_ids))
1429 operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
1430 pack_operation_ids = []
1432 for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
1433 #If we haven't done all qty in operation, we have to split into 2 operation
1435 if (operation.qty_done < operation.product_qty):
1436 new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
1437 stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0, 'lot_id': False}, context=context)
1438 op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
1439 pack_operation_ids.append(op.id)
1440 if op.product_id and op.location_id and op.location_dest_id:
1441 stock_move_obj.check_tracking_product(cr, uid, op.product_id, op.lot_id.id, op.location_id, op.location_dest_id, context=context)
1442 package_id = package_obj.create(cr, uid, {}, context=context)
1443 stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
1446 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
1447 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)
1449 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
1450 '''This function is called each time there barcode scanner reads an input'''
1451 stock_operation_obj = self.pool.get('stock.pack.operation')
1452 answer = {'filter_loc': False, 'operation_id': False}
1454 # Barcode Nomenclatures
1455 #this_picking ==? self
1456 this_picking = self.search(cr, uid, [('id', '=', picking_id)], context=context)
1457 #this_picking = self.read(cr, uid, picking_id, context=context)
1458 rec = self.browse(cr, uid, self, context=context)
1459 barcode_nom = rec.barcode_nomenclature_id
1460 parsed_result = barcode_nom.parse_barcode(barcode_str)
1462 #check if the barcode is a weighted barcode or simply a product
1463 if parsed_result['type'] in ['weight', 'product', 'package']:
1465 if parsed_result['type'] == 'weight':
1466 domain = ['|', ('barcode', '=', parsed_result['base_code']), ('default_code', '=', parsed_result['base_code'])]
1467 weight=parsed_result['value']
1468 obj = self.pool.get('product.product')
1469 id_in_operation = 'product_id'
1470 elif parsed_result['type'] == 'product':
1471 domain = ['|', ('barcode', '=', parsed_result['code']), ('default_code', '=', parsed_result['code'])]
1472 obj = self.pool.get('product.product')
1473 id_in_operation = 'product_id'
1475 domain = [('name', '=', parsed_result['code'])]
1476 obj = self.pool.get('stock.quant.package')
1477 id_in_operation = 'package_id'
1479 matching_product_ids = obj.search(cr, uid, domain, context=context)
1480 if matching_product_ids:
1481 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [(id_in_operation, '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, weight=weight, increment=True, context=context)
1482 answer['operation_id'] = op_id
1485 #check if the barcode correspond to a lot
1486 elif parsed_result['type'] == 'lot':
1487 lot_obj = self.pool.get('stock.production.lot')
1488 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', parsed_result['code'])], context=context)
1489 if matching_lot_ids:
1490 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1491 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)
1492 answer['operation_id'] = op_id
1495 #check if the barcode correspond to a location
1496 elif parsed_result['type'] == 'location':
1497 stock_location_obj = self.pool.get('stock.location')
1498 matching_location_ids = stock_location_obj.search(cr, uid, [('barcode', '=', parsed_result['code'])], context=context)
1499 if matching_location_ids:
1500 #if we have a location, return immediatly with the location name
1501 location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
1502 answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
1503 answer['filter_loc_id'] = matching_location_ids[0]
1509 class stock_production_lot(osv.osv):
1510 _name = 'stock.production.lot'
1511 _inherit = ['mail.thread']
1512 _description = 'Lot/Serial'
1514 'name': fields.char('Serial Number', required=True, help="Unique Serial Number"),
1515 'ref': fields.char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's serial number"),
1516 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1517 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
1518 'create_date': fields.datetime('Creation Date'),
1521 'name': lambda x, y, z, c: x.pool.get('ir.sequence').next_by_code(y, z, 'stock.lot.serial'),
1522 'product_id': lambda x, y, z, c: c.get('product_id', False),
1524 _sql_constraints = [
1525 ('name_ref_uniq', 'unique (name, ref, product_id)', 'The combination of serial number, internal reference and product must be unique !'),
1528 def action_traceability(self, cr, uid, ids, context=None):
1529 """ It traces the information of lots
1530 @param self: The object pointer.
1531 @param cr: A database cursor
1532 @param uid: ID of the user currently logged in
1533 @param ids: List of IDs selected
1534 @param context: A standard dictionary
1535 @return: A dictionary of values
1537 quant_obj = self.pool.get("stock.quant")
1538 quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1540 for quant in quant_obj.browse(cr, uid, quants, context=context):
1541 moves |= {move.id for move in quant.history_ids}
1544 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
1545 'name': _('Traceability'),
1546 'view_mode': 'tree,form',
1547 'view_type': 'form',
1548 'context': {'tree_view_ref': 'stock.view_move_tree'},
1549 'res_model': 'stock.move',
1550 'type': 'ir.actions.act_window',
1555 # ----------------------------------------------------
1557 # ----------------------------------------------------
1559 class stock_move(osv.osv):
1560 _name = "stock.move"
1561 _description = "Stock Move"
1562 _order = 'date_expected desc, id'
1565 def get_price_unit(self, cr, uid, move, context=None):
1566 """ Returns the unit price to store on the quant """
1567 return move.price_unit or move.product_id.standard_price
1569 def name_get(self, cr, uid, ids, context=None):
1571 for line in self.browse(cr, uid, ids, context=context):
1572 name = line.location_id.name + ' > ' + line.location_dest_id.name
1573 if line.product_id.code:
1574 name = line.product_id.code + ': ' + name
1575 if line.picking_id.origin:
1576 name = line.picking_id.origin + '/ ' + name
1577 res.append((line.id, name))
1580 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1581 uom_obj = self.pool.get('product.uom')
1583 for m in self.browse(cr, uid, ids, context=context):
1584 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)
1587 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1588 uom_obj = self.pool.get('product.uom')
1590 for move in self.browse(cr, uid, ids, context=context):
1591 qty = move.product_qty
1592 for record in move.linked_move_operation_ids:
1594 #converting the remaining quantity in the move UoM
1595 res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context)
1598 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1599 res = dict.fromkeys(ids, False)
1600 for move in self.browse(cr, uid, ids, context=context):
1601 if move.state == 'done':
1602 res[move.id] = [q.lot_id.id for q in move.quant_ids if q.lot_id]
1604 res[move.id] = [q.lot_id.id for q in move.reserved_quant_ids if q.lot_id]
1607 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1608 quant_obj = self.pool.get('stock.quant')
1609 res = dict.fromkeys(ids, False)
1610 for move in self.browse(cr, uid, ids, context=context):
1611 if move.state == 'done':
1612 res[move.id] = move.product_qty
1614 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1615 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1617 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1618 availability += quant.qty
1619 res[move.id] = min(move.product_qty, availability)
1622 def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
1623 settings_obj = self.pool.get('stock.config.settings')
1624 uom_obj = self.pool.get('product.uom')
1625 res = dict.fromkeys(ids, '')
1626 for move in self.browse(cr, uid, ids, context=context):
1627 if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
1628 res[move.id] = '' # 'not applicable' or 'n/a' could work too
1630 total_available = min(move.product_qty, move.reserved_availability + move.availability)
1631 total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
1632 info = str(total_available)
1633 #look in the settings if we need to display the UoM name or not
1634 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1636 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1637 if stock_settings.group_uom:
1638 info += ' ' + move.product_uom.name
1639 if move.reserved_availability:
1640 if move.reserved_availability != total_available:
1641 #some of the available quantity is assigned and some are available but not reserved
1642 reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
1643 info += _(' (%s reserved)') % str(reserved_available)
1645 #all available quantity is assigned
1646 info += _(' (reserved)')
1650 def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
1651 res = dict.fromkeys(ids, 0)
1652 for move in self.browse(cr, uid, ids, context=context):
1653 res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
1656 def _get_move(self, cr, uid, ids, context=None):
1658 for quant in self.browse(cr, uid, ids, context=context):
1659 if quant.reservation_id:
1660 res.add(quant.reservation_id.id)
1663 def _get_move_ids(self, cr, uid, ids, context=None):
1665 for picking in self.browse(cr, uid, ids, context=context):
1666 res += [x.id for x in picking.move_lines]
1669 def _get_moves_from_prod(self, cr, uid, ids, context=None):
1671 return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context)
1674 def _set_product_qty(self, cr, uid, id, field, value, arg, context=None):
1675 """ The meaning of product_qty field changed lately and is now a functional field computing the quantity
1676 in the default product UoM. This code has been added to raise an error if a write is made given a value
1677 for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
1680 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`.'))
1683 'name': fields.char('Description', required=True, select=True),
1684 'priority': fields.selection(procurement.PROCUREMENT_PRIORITIES, 'Priority'),
1685 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1686 '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)]}),
1687 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1688 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1689 'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, _type='float', store={
1690 'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_id', 'product_uom_qty', 'product_uom'], 20),
1691 'product.product': (_get_moves_from_prod, ['uom_id'], 20),
1692 }, string='Quantity',
1693 digits_compute=dp.get_precision('Product Unit of Measure'),
1694 help='Quantity in the default UoM of the product'),
1695 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1696 required=True, states={'done': [('readonly', True)]},
1697 help="This is the quantity of products from an inventory "
1698 "point of view. For moves in the state 'done', this is the "
1699 "quantity of products that were actually moved. For other "
1700 "moves, this is the quantity of product that is planned to "
1701 "be moved. Lowering this quantity does not generate a "
1702 "backorder. Changing this quantity on assigned moves affects "
1703 "the product reservation, and should be done with care."
1705 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1706 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1707 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1709 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1711 '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."),
1712 '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."),
1714 '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"),
1717 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True, copy=False),
1718 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1720 'picking_id': fields.many2one('stock.picking', 'Reference Stock Move', select=True, states={'done': [('readonly', True)]}),
1721 'note': fields.text('Notes'),
1722 'state': fields.selection([('draft', 'New'),
1723 ('cancel', 'Cancelled'),
1724 ('waiting', 'Waiting Another Move'),
1725 ('confirmed', 'Waiting Availability'),
1726 ('assigned', 'Available'),
1728 ], 'Status', readonly=True, select=True, copy=False,
1729 help= "* New: When the stock move is created and not yet confirmed.\n"\
1730 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1731 "* 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"\
1732 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1733 "* Done: When the shipment is processed, the state is \'Done\'."),
1734 'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved", copy=False),
1735 '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
1737 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1738 '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),
1739 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1740 'origin': fields.char("Source Document"),
1741 'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True,
1742 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."""),
1744 # used for colors in tree views:
1745 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1747 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1748 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1749 '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'),
1750 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1751 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1752 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1753 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1754 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1755 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1756 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1757 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1758 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1759 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.production.lot', string='Lots'),
1760 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move', copy=False),
1761 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1762 'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
1763 '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'),
1764 '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'),
1765 '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'"),
1766 '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'"),
1767 '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"),
1768 '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)."),
1771 def _default_location_destination(self, cr, uid, context=None):
1772 context = context or {}
1773 if context.get('default_picking_type_id', False):
1774 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1775 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1778 def _default_location_source(self, cr, uid, context=None):
1779 context = context or {}
1780 if context.get('default_picking_type_id', False):
1781 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1782 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1785 def _default_destination_address(self, cr, uid, context=None):
1786 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1787 return user.company_id.partner_id.id
1790 'location_id': _default_location_source,
1791 'location_dest_id': _default_location_destination,
1792 'partner_id': _default_destination_address,
1795 'product_uom_qty': 1.0,
1797 'date': fields.datetime.now,
1798 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1799 'date_expected': fields.datetime.now,
1800 'procure_method': 'make_to_stock',
1802 'partially_available': False,
1805 def _check_uom(self, cr, uid, ids, context=None):
1806 for move in self.browse(cr, uid, ids, context=context):
1807 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1813 '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.',
1817 @api.cr_uid_ids_context
1818 def do_unreserve(self, cr, uid, move_ids, context=None):
1819 quant_obj = self.pool.get("stock.quant")
1820 for move in self.browse(cr, uid, move_ids, context=context):
1821 if move.state in ('done', 'cancel'):
1822 raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
1823 quant_obj.quants_unreserve(cr, uid, move, context=context)
1824 if self.find_move_ancestors(cr, uid, move, context=context):
1825 self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context)
1827 self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
1829 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1830 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or move.origin or "/")
1831 group_id = move.group_id and move.group_id.id or False
1833 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1834 group_id = move.rule_id.group_id.id
1835 elif move.rule_id.group_propagation_option == 'none':
1838 'name': move.rule_id and move.rule_id.name or "/",
1840 'company_id': move.company_id and move.company_id.id or False,
1841 'date_planned': move.date,
1842 'product_id': move.product_id.id,
1843 'product_qty': move.product_qty,
1844 'product_uom': move.product_uom.id,
1845 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1846 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1847 'location_id': move.location_id.id,
1848 'move_dest_id': move.id,
1849 'group_id': group_id,
1850 'route_ids': [(4, x.id) for x in move.route_ids],
1851 'warehouse_id': move.warehouse_id.id or (move.picking_type_id and move.picking_type_id.warehouse_id.id or False),
1852 'priority': move.priority,
1855 def _push_apply(self, cr, uid, moves, context=None):
1856 push_obj = self.pool.get("stock.location.path")
1858 #1) if the move is already chained, there is no need to check push rules
1859 #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
1860 # to receive goods without triggering the push rules again (which would duplicate chained operations)
1861 if not move.move_dest_id and not move.origin_returned_move_id:
1862 domain = [('location_from_id', '=', move.location_dest_id.id)]
1863 #priority goes to the route defined on the product and product category
1864 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1865 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1867 #then we search on the warehouse if a rule can apply
1869 if move.warehouse_id:
1870 wh_route_ids = [x.id for x in move.warehouse_id.route_ids]
1871 elif move.picking_type_id and move.picking_type_id.warehouse_id:
1872 wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids]
1874 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context)
1876 #if no specialized push rule has been found yet, we try to find a general one (without route)
1877 rules = push_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)
1879 rule = push_obj.browse(cr, uid, rules[0], context=context)
1880 push_obj._apply(cr, uid, rule, move, context=context)
1883 def _create_procurement(self, cr, uid, move, context=None):
1884 """ This will create a procurement order """
1885 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1887 def write(self, cr, uid, ids, vals, context=None):
1890 if isinstance(ids, (int, long)):
1892 # Check that we do not modify a stock.move which is done
1893 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1894 for move in self.browse(cr, uid, ids, context=context):
1895 if move.state == 'done':
1896 if frozen_fields.intersection(vals):
1897 raise osv.except_osv(_('Operation Forbidden!'),
1898 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1899 propagated_changes_dict = {}
1900 #propagation of quantity change
1901 if vals.get('product_uom_qty'):
1902 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1903 if vals.get('product_uom_id'):
1904 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1905 #propagation of expected date:
1906 propagated_date_field = False
1907 if vals.get('date_expected'):
1908 #propagate any manual change of the expected date
1909 propagated_date_field = 'date_expected'
1910 elif (vals.get('state', '') == 'done' and vals.get('date')):
1911 #propagate also any delta observed when setting the move as done
1912 propagated_date_field = 'date'
1914 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1915 #any propagation is (maybe) needed
1916 for move in self.browse(cr, uid, ids, context=context):
1917 if move.move_dest_id and move.propagate:
1918 if 'date_expected' in propagated_changes_dict:
1919 propagated_changes_dict.pop('date_expected')
1920 if propagated_date_field:
1921 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1922 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1923 delta = new_date - current_date
1924 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1925 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1926 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1927 propagated_changes_dict['date_expected'] = new_move_date
1928 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1929 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1930 if propagated_changes_dict:
1931 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1932 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1934 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1935 """ On change of product quantity finds UoM and UoS quantities
1936 @param product_id: Product id
1937 @param product_qty: Changed Quantity of product
1938 @param product_uom: Unit of measure of product
1939 @param product_uos: Unit of sale of product
1940 @return: Dictionary of values
1943 'product_uos_qty': 0.00
1947 if (not product_id) or (product_qty <= 0.0):
1948 result['product_qty'] = 0.0
1949 return {'value': result}
1951 product_obj = self.pool.get('product.product')
1952 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1954 # Warn if the quantity was decreased
1956 for move in self.read(cr, uid, ids, ['product_qty']):
1957 if product_qty < move['product_qty']:
1959 'title': _('Information'),
1960 'message': _("By changing this quantity here, you accept the "
1961 "new quantity as complete: Odoo will not "
1962 "automatically generate a back order.")})
1965 if product_uos and product_uom and (product_uom != product_uos):
1966 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1968 result['product_uos_qty'] = product_qty
1970 return {'value': result, 'warning': warning}
1972 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1973 product_uos, product_uom):
1974 """ On change of product quantity finds UoM and UoS quantities
1975 @param product_id: Product id
1976 @param product_uos_qty: Changed UoS Quantity of product
1977 @param product_uom: Unit of measure of product
1978 @param product_uos: Unit of sale of product
1979 @return: Dictionary of values
1982 'product_uom_qty': 0.00
1985 if (not product_id) or (product_uos_qty <= 0.0):
1986 result['product_uos_qty'] = 0.0
1987 return {'value': result}
1989 product_obj = self.pool.get('product.product')
1990 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1992 # No warning if the quantity was decreased to avoid double warnings:
1993 # The clients should call onchange_quantity too anyway
1995 if product_uos and product_uom and (product_uom != product_uos):
1996 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1998 result['product_uom_qty'] = product_uos_qty
1999 return {'value': result}
2001 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
2002 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
2003 @param prod_id: Changed Product id
2004 @param loc_id: Source location id
2005 @param loc_dest_id: Destination location id
2006 @param partner_id: Address id of partner
2007 @return: Dictionary of values
2011 user = self.pool.get('res.users').browse(cr, uid, uid)
2012 lang = user and user.lang or False
2014 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
2016 lang = addr_rec and addr_rec.lang or False
2017 ctx = {'lang': lang}
2019 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
2020 uos_id = product.uos_id and product.uos_id.id or False
2022 'name': product.partner_ref,
2023 'product_uom': product.uom_id.id,
2024 'product_uos': uos_id,
2025 'product_uom_qty': 1.00,
2026 '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'],
2029 result['location_id'] = loc_id
2031 result['location_dest_id'] = loc_dest_id
2032 return {'value': result}
2034 @api.cr_uid_ids_context
2035 def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
2036 """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
2037 (and company). Those attributes are also given as parameters.
2039 pick_obj = self.pool.get("stock.picking")
2040 picks = pick_obj.search(cr, uid, [
2041 ('group_id', '=', procurement_group),
2042 ('location_id', '=', location_from),
2043 ('location_dest_id', '=', location_to),
2044 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
2048 move = self.browse(cr, uid, move_ids, context=context)[0]
2050 'origin': move.origin,
2051 'company_id': move.company_id and move.company_id.id or False,
2052 'move_type': move.group_id and move.group_id.move_type or 'direct',
2053 'partner_id': move.partner_id.id or False,
2054 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
2056 pick = pick_obj.create(cr, uid, values, context=context)
2057 return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
2059 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
2060 """ On change of Scheduled Date gives a Move date.
2061 @param date_expected: Scheduled Date
2062 @param date: Move Date
2065 if not date_expected:
2066 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
2067 return {'value': {'date': date_expected}}
2069 def attribute_price(self, cr, uid, move, context=None):
2071 Attribute price to move, important in inter-company moves or receipts with only one partner
2073 if not move.price_unit:
2074 price = move.product_id.standard_price
2075 self.write(cr, uid, [move.id], {'price_unit': price})
2077 def action_confirm(self, cr, uid, ids, context=None):
2078 """ Confirms stock move or put it in waiting if it's linked to another move.
2079 @return: List of ids.
2081 if isinstance(ids, (int, long)):
2088 for move in self.browse(cr, uid, ids, context=context):
2089 self.attribute_price(cr, uid, move, context=context)
2091 #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)
2092 if move.move_orig_ids:
2094 #if the move is split and some of the ancestor was preceeded, then it's waiting as well
2095 elif move.split_from:
2096 move2 = move.split_from
2097 while move2 and state != 'waiting':
2098 if move2.move_orig_ids:
2100 move2 = move2.split_from
2101 states[state].append(move.id)
2103 if not move.picking_id and move.picking_type_id:
2104 key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
2105 if key not in to_assign:
2107 to_assign[key].append(move.id)
2109 for move in self.browse(cr, uid, states['confirmed'], context=context):
2110 if move.procure_method == 'make_to_order':
2111 self._create_procurement(cr, uid, move, context=context)
2112 states['waiting'].append(move.id)
2113 states['confirmed'].remove(move.id)
2115 for state, write_ids in states.items():
2117 self.write(cr, uid, write_ids, {'state': state})
2118 #assign picking in batch for all confirmed move that share the same details
2119 for key, move_ids in to_assign.items():
2120 procurement_group, location_from, location_to = key
2121 self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
2122 moves = self.browse(cr, uid, ids, context=context)
2123 self._push_apply(cr, uid, moves, context=context)
2126 def force_assign(self, cr, uid, ids, context=None):
2127 """ Changes the state to assigned.
2130 return self.write(cr, uid, ids, {'state': 'assigned'}, context=context)
2132 def check_tracking_product(self, cr, uid, product, lot_id, location, location_dest, context=None):
2134 if product.track_all and not location_dest.usage == 'inventory':
2136 elif product.track_incoming and location.usage in ('supplier', 'transit', 'inventory') and location_dest.usage == 'internal':
2138 elif product.track_outgoing and location_dest.usage in ('customer', 'transit') and location.usage == 'internal':
2140 if check and not lot_id:
2141 raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (product.name))
2144 def check_tracking(self, cr, uid, move, lot_id, context=None):
2145 """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
2147 self.check_tracking_product(cr, uid, move.product_id, lot_id, move.location_id, move.location_dest_id, context=context)
2150 def action_assign(self, cr, uid, ids, context=None):
2151 """ Checks the product type and accordingly writes the state.
2153 context = context or {}
2154 quant_obj = self.pool.get("stock.quant")
2155 to_assign_moves = []
2159 for move in self.browse(cr, uid, ids, context=context):
2160 if move.state not in ('confirmed', 'waiting', 'assigned'):
2162 if move.location_id.usage in ('supplier', 'inventory', 'production'):
2163 to_assign_moves.append(move.id)
2164 #in case the move is returned, we want to try to find quants before forcing the assignment
2165 if not move.origin_returned_move_id:
2167 if move.product_id.type == 'consu':
2168 to_assign_moves.append(move.id)
2171 todo_moves.append(move)
2173 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
2174 main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
2176 #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
2177 ancestors = self.find_move_ancestors(cr, uid, move, context=context)
2178 if move.state == 'waiting' and not ancestors:
2179 #if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock
2180 main_domain[move.id] += [('id', '=', False)]
2182 main_domain[move.id] += [('history_ids', 'in', ancestors)]
2184 #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
2185 if move.origin_returned_move_id:
2186 main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
2187 for link in move.linked_move_operation_ids:
2188 operations.add(link.operation_id)
2189 # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
2190 operations = list(operations)
2191 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))
2192 for ops in operations:
2193 #first try to find quants based on specific domains given by linked operations
2194 for record in ops.linked_move_operation_ids:
2195 move = record.move_id
2196 if move.id in main_domain:
2197 domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2200 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)
2201 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
2202 for move in todo_moves:
2203 if move.linked_move_operation_ids:
2206 #then if the move isn't totally assigned, try to find quants without any specific domain
2207 if move.state != 'assigned':
2208 qty_already_assigned = move.reserved_availability
2209 qty = move.product_qty - qty_already_assigned
2210 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)
2211 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
2213 #force assignation of consumable products and incoming from supplier/inventory/production
2215 self.force_assign(cr, uid, to_assign_moves, context=context)
2217 def action_cancel(self, cr, uid, ids, context=None):
2218 """ Cancels the moves and if all moves are cancelled it cancels the picking.
2221 procurement_obj = self.pool.get('procurement.order')
2222 context = context or {}
2224 for move in self.browse(cr, uid, ids, context=context):
2225 if move.state == 'done':
2226 raise osv.except_osv(_('Operation Forbidden!'),
2227 _('You cannot cancel a stock move that has been set to \'Done\'.'))
2228 if move.reserved_quant_ids:
2229 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
2230 if context.get('cancel_procurement'):
2232 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
2233 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
2235 if move.move_dest_id:
2237 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
2238 elif move.move_dest_id.state == 'waiting':
2239 #If waiting, the chain will be broken and we are not sure if we can still wait for it (=> could take from stock instead)
2240 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2241 if move.procurement_id:
2242 # Does the same as procurement check, only eliminating a refresh
2243 procs_to_check.append(move.procurement_id.id)
2245 res = self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2247 procurement_obj.check(cr, uid, procs_to_check, context=context)
2250 def _check_package_from_moves(self, cr, uid, ids, context=None):
2251 pack_obj = self.pool.get("stock.quant.package")
2253 for move in self.browse(cr, uid, ids, context=context):
2254 packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0])
2255 return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
2257 def find_move_ancestors(self, cr, uid, move, context=None):
2258 '''Find the first level ancestors of given move '''
2262 ancestors += [x.id for x in move2.move_orig_ids]
2263 #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
2264 move2 = not move2.move_orig_ids and move2.split_from or False
2267 @api.cr_uid_ids_context
2268 def recalculate_move_state(self, cr, uid, move_ids, context=None):
2269 '''Recompute the state of moves given because their reserved quants were used to fulfill another operation'''
2270 for move in self.browse(cr, uid, move_ids, context=context):
2272 reserved_quant_ids = move.reserved_quant_ids
2273 if len(reserved_quant_ids) > 0 and not move.partially_available:
2274 vals['partially_available'] = True
2275 if len(reserved_quant_ids) == 0 and move.partially_available:
2276 vals['partially_available'] = False
2277 if move.state == 'assigned':
2278 if self.find_move_ancestors(cr, uid, move, context=context):
2279 vals['state'] = 'waiting'
2281 vals['state'] = 'confirmed'
2283 self.write(cr, uid, [move.id], vals, context=context)
2285 def action_done(self, cr, uid, ids, context=None):
2286 """ Process completely the moves given as ids and if all moves are done, it will finish the picking.
2288 context = context or {}
2289 picking_obj = self.pool.get("stock.picking")
2290 quant_obj = self.pool.get("stock.quant")
2291 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
2293 ids = self.action_confirm(cr, uid, todo, context=context)
2295 procurement_ids = []
2296 #Search operations that are linked to the moves
2299 for move in self.browse(cr, uid, ids, context=context):
2300 move_qty[move.id] = move.product_qty
2301 for link in move.linked_move_operation_ids:
2302 operations.add(link.operation_id)
2304 #Sort operations according to entire packages first, then package + lot, package only, lot only
2305 operations = list(operations)
2306 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))
2308 for ops in operations:
2310 pickings.add(ops.picking_id.id)
2311 main_domain = [('qty', '>', 0)]
2312 for record in ops.linked_move_operation_ids:
2313 move = record.move_id
2314 self.check_tracking(cr, uid, move, not ops.product_id and ops.package_id.id or ops.lot_id.id, context=context)
2315 prefered_domain = [('reservation_id', '=', move.id)]
2316 fallback_domain = [('reservation_id', '=', False)]
2317 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2318 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2319 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2320 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,
2321 restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2322 if ops.result_package_id.id:
2323 #if a result package is given, all quants go there
2324 quant_dest_package_id = ops.result_package_id.id
2325 elif ops.product_id and ops.package_id:
2326 #if a package and a product is given, we will remove quants from the pack.
2327 quant_dest_package_id = False
2329 #otherwise we keep the current pack of the quant, which may mean None
2330 quant_dest_package_id = ops.package_id.id
2331 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)
2332 # Handle pack in pack
2333 if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
2334 self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
2335 move_qty[move.id] -= record.qty
2336 #Check for remaining qtys and unreserve/check move_dest_id in
2337 move_dest_ids = set()
2338 for move in self.browse(cr, uid, ids, context=context):
2339 if move_qty[move.id] > 0: # (=In case no pack operations in picking)
2340 main_domain = [('qty', '>', 0)]
2341 prefered_domain = [('reservation_id', '=', move.id)]
2342 fallback_domain = [('reservation_id', '=', False)]
2343 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2344 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2345 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
2346 qty = move_qty[move.id]
2347 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)
2348 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)
2350 # If the move has a destination, add it to the list to reserve
2351 if move.move_dest_id and move.move_dest_id.state in ('waiting', 'confirmed'):
2352 move_dest_ids.add(move.move_dest_id.id)
2354 if move.procurement_id:
2355 procurement_ids.append(move.procurement_id.id)
2357 #unreserve the quants and make them available for other operations/moves
2358 quant_obj.quants_unreserve(cr, uid, move, context=context)
2359 # Check the packages have been placed in the correct locations
2360 self._check_package_from_moves(cr, uid, ids, context=context)
2361 #set the move as done
2362 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2363 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
2364 #assign destination moves
2366 self.action_assign(cr, uid, list(move_dest_ids), context=context)
2367 #check picking state to set the date_done is needed
2369 for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
2370 if picking.state == 'done' and not picking.date_done:
2371 done_picking.append(picking.id)
2373 picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2376 def unlink(self, cr, uid, ids, context=None):
2377 context = context or {}
2378 for move in self.browse(cr, uid, ids, context=context):
2379 if move.state not in ('draft', 'cancel'):
2380 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2381 return super(stock_move, self).unlink(cr, uid, ids, context=context)
2383 def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
2384 """ Move the scrap/damaged product into scrap location
2385 @param cr: the database cursor
2386 @param uid: the user id
2387 @param ids: ids of stock move object to be scrapped
2388 @param quantity : specify scrap qty
2389 @param location_id : specify scrap location
2390 @param context: context arguments
2391 @return: Scraped lines
2393 #quantity should be given in MOVE UOM
2395 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2397 for move in self.browse(cr, uid, ids, context=context):
2398 source_location = move.location_id
2399 if move.state == 'done':
2400 source_location = move.location_dest_id
2401 #Previously used to prevent scraping from virtual location but not necessary anymore
2402 #if source_location.usage != 'internal':
2403 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2404 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2405 move_qty = move.product_qty
2406 uos_qty = quantity / move_qty * move.product_uos_qty
2408 'location_id': source_location.id,
2409 'product_uom_qty': quantity,
2410 'product_uos_qty': uos_qty,
2411 'state': move.state,
2413 'location_dest_id': location_id,
2414 'restrict_lot_id': restrict_lot_id,
2415 'restrict_partner_id': restrict_partner_id,
2417 new_move = self.copy(cr, uid, move.id, default_val)
2420 product_obj = self.pool.get('product.product')
2421 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2423 uom = product.uom_id.name if product.uom_id else ''
2424 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2425 move.picking_id.message_post(body=message)
2427 self.action_done(cr, uid, res, context=context)
2430 def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
2431 """ Splits qty from move move into a new move
2432 :param move: browse record
2433 :param qty: float. quantity to split (given in product UoM)
2434 :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.
2435 :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.
2436 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
2438 returns the ID of the backorder move created
2440 if move.state in ('done', 'cancel'):
2441 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
2442 if move.state == 'draft':
2443 #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
2444 #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
2445 raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
2447 if move.product_qty <= qty or qty == 0:
2450 uom_obj = self.pool.get('product.uom')
2451 context = context or {}
2453 uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom)
2454 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
2457 'product_uom_qty': uom_qty,
2458 'product_uos_qty': uos_qty,
2459 'procure_method': 'make_to_stock',
2460 'restrict_lot_id': restrict_lot_id,
2461 'restrict_partner_id': restrict_partner_id,
2462 'split_from': move.id,
2463 'procurement_id': move.procurement_id.id,
2464 'move_dest_id': move.move_dest_id.id,
2466 if context.get('source_location_id'):
2467 defaults['location_id'] = context['source_location_id']
2468 new_move = self.copy(cr, uid, move.id, defaults)
2470 ctx = context.copy()
2471 ctx['do_not_propagate'] = True
2472 self.write(cr, uid, [move.id], {
2473 'product_uom_qty': move.product_uom_qty - uom_qty,
2474 'product_uos_qty': move.product_uos_qty - uos_qty,
2477 if move.move_dest_id and move.propagate and move.move_dest_id.state not in ('done', 'cancel'):
2478 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2479 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2480 #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
2481 #thus the result of action_confirm should always be a list of 1 element length)
2482 return self.action_confirm(cr, uid, [new_move], context=context)[0]
2485 def get_code_from_locs(self, cr, uid, move, location_id=False, location_dest_id=False, context=None):
2487 Returns the code the picking type should have. This can easily be used
2488 to check if a move is internal or not
2489 move, location_id and location_dest_id are browse records
2492 src_loc = location_id or move.location_id
2493 dest_loc = location_dest_id or move.location_dest_id
2494 if src_loc.usage == 'internal' and dest_loc.usage != 'internal':
2496 if src_loc.usage != 'internal' and dest_loc.usage == 'internal':
2501 class stock_inventory(osv.osv):
2502 _name = "stock.inventory"
2503 _description = "Inventory"
2505 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2507 for inv in self.browse(cr, uid, ids, context=context):
2513 def _get_available_filters(self, cr, uid, context=None):
2515 This function will return the list of filter allowed according to the options checked
2516 in 'Settings\Warehouse'.
2518 :rtype: list of tuple
2520 #default available choices
2521 res_filter = [('none', _('All products')), ('product', _('One product only'))]
2522 settings_obj = self.pool.get('stock.config.settings')
2523 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2524 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2528 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2529 if stock_settings.group_stock_tracking_owner:
2530 res_filter.append(('owner', _('One owner only')))
2531 res_filter.append(('product_owner', _('One product for a specific owner')))
2532 if stock_settings.group_stock_tracking_lot:
2533 res_filter.append(('lot', _('One Lot/Serial Number')))
2534 if stock_settings.group_stock_packaging:
2535 res_filter.append(('pack', _('A Pack')))
2538 def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
2540 for inv in self.browse(cr, uid, ids, context=context):
2541 res[inv.id] = sum([x.product_qty for x in inv.line_ids])
2544 INVENTORY_STATE_SELECTION = [
2546 ('cancel', 'Cancelled'),
2547 ('confirm', 'In Progress'),
2548 ('done', 'Validated'),
2552 'name': fields.char('Inventory Reference', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2553 '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."),
2554 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines.", copy=True),
2555 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
2556 'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True, copy=False),
2557 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2558 'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2559 '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."),
2560 '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."),
2561 '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."),
2562 '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),
2563 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2564 'filter': fields.selection(_get_available_filters, 'Selection Filter', required=True),
2565 'total_qty': fields.function(_get_total_qty, type="float"),
2568 def _default_stock_location(self, cr, uid, context=None):
2570 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2571 return warehouse.lot_stock_id.id
2576 'date': fields.datetime.now,
2578 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2579 'location_id': _default_stock_location,
2583 def reset_real_qty(self, cr, uid, ids, context=None):
2584 inventory = self.browse(cr, uid, ids[0], context=context)
2585 line_ids = [line.id for line in inventory.line_ids]
2586 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2589 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2590 """ Creates a stock move from an inventory line
2591 @param inventory_line:
2595 return self.pool.get('stock.move').create(cr, uid, move_vals)
2597 def action_done(self, cr, uid, ids, context=None):
2598 """ Finish the inventory
2601 for inv in self.browse(cr, uid, ids, context=context):
2602 for inventory_line in inv.line_ids:
2603 if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty:
2604 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)))
2605 self.action_check(cr, uid, [inv.id], context=context)
2607 self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
2608 self.post_inventory(cr, uid, inv, context=context)
2611 def post_inventory(self, cr, uid, inv, context=None):
2612 #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
2613 #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
2614 #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
2615 move_obj = self.pool.get('stock.move')
2616 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2618 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2619 stock_move_obj = self.pool.get('stock.move')
2620 product_obj = self.pool.get('product.product')
2621 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2623 'name': _('INV:') + (inventory.name or ''),
2624 'product_id': todo_line['product_id'],
2625 'product_uom': todo_line['product_uom_id'],
2626 'date': inventory.date,
2627 'company_id': inventory.company_id.id,
2628 'inventory_id': inventory.id,
2629 'state': 'assigned',
2630 'restrict_lot_id': todo_line.get('prod_lot_id'),
2631 'restrict_partner_id': todo_line.get('partner_id'),
2634 if todo_line['product_qty'] < 0:
2635 #found more than expected
2636 vals['location_id'] = inventory_location_id
2637 vals['location_dest_id'] = todo_line['location_id']
2638 vals['product_uom_qty'] = -todo_line['product_qty']
2640 #found less than expected
2641 vals['location_id'] = todo_line['location_id']
2642 vals['location_dest_id'] = inventory_location_id
2643 vals['product_uom_qty'] = todo_line['product_qty']
2644 return stock_move_obj.create(cr, uid, vals, context=context)
2646 def action_check(self, cr, uid, ids, context=None):
2647 """ Checks the inventory and computes the stock move to do
2650 inventory_line_obj = self.pool.get('stock.inventory.line')
2651 stock_move_obj = self.pool.get('stock.move')
2652 for inventory in self.browse(cr, uid, ids, context=context):
2653 #first remove the existing stock moves linked to this inventory
2654 move_ids = [move.id for move in inventory.move_ids]
2655 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2656 for line in inventory.line_ids:
2657 #compare the checked quantities on inventory lines to the theorical one
2658 inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context)
2660 def action_cancel_draft(self, cr, uid, ids, context=None):
2661 """ Cancels the stock move and change inventory state to draft.
2664 for inv in self.browse(cr, uid, ids, context=context):
2665 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2666 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2669 def action_cancel_inventory(self, cr, uid, ids, context=None):
2670 self.action_cancel_draft(cr, uid, ids, context=context)
2672 def prepare_inventory(self, cr, uid, ids, context=None):
2673 inventory_line_obj = self.pool.get('stock.inventory.line')
2674 for inventory in self.browse(cr, uid, ids, context=context):
2675 # If there are inventory lines already (e.g. from import), respect those and set their theoretical qty
2676 line_ids = [line.id for line in inventory.line_ids]
2678 #compute the inventory lines and create them
2679 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2680 for product_line in vals:
2681 inventory_line_obj.create(cr, uid, product_line, context=context)
2683 # On import calculate theoretical quantity
2684 quant_obj = self.pool.get("stock.quant")
2685 for line in inventory.line_ids:
2686 dom = [('company_id', '=', line.company_id.id), ('location_id', 'child_of', line.location_id.id), ('lot_id', '=', line.prod_lot_id.id),
2687 ('product_id','=', line.product_id.id), ('owner_id', '=', line.partner_id.id)]
2689 dom += [('package_id', '=', line.package_id.id)]
2690 quants = quant_obj.search(cr, uid, dom, context=context)
2692 for quant in quant_obj.browse(cr, uid, quants, context=context):
2693 tot_qty += quant.qty
2694 inventory_line_obj.write(cr, uid, [line.id], {'theoretical_qty': tot_qty}, context=context)
2696 return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
2698 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2699 location_obj = self.pool.get('stock.location')
2700 product_obj = self.pool.get('product.product')
2701 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2702 domain = ' location_id in %s'
2703 args = (tuple(location_ids),)
2704 if inventory.partner_id:
2705 domain += ' and owner_id = %s'
2706 args += (inventory.partner_id.id,)
2707 if inventory.lot_id:
2708 domain += ' and lot_id = %s'
2709 args += (inventory.lot_id.id,)
2710 if inventory.product_id:
2711 domain += ' and product_id = %s'
2712 args += (inventory.product_id.id,)
2713 if inventory.package_id:
2714 domain += ' and package_id = %s'
2715 args += (inventory.package_id.id,)
2718 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2719 FROM stock_quant WHERE''' + domain + '''
2720 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2723 for product_line in cr.dictfetchall():
2724 #replace the None the dictionary by False, because falsy values are tested later on
2725 for key, value in product_line.items():
2727 product_line[key] = False
2728 product_line['inventory_id'] = inventory.id
2729 product_line['theoretical_qty'] = product_line['product_qty']
2730 if product_line['product_id']:
2731 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2732 product_line['product_uom_id'] = product.uom_id.id
2733 vals.append(product_line)
2737 class stock_inventory_line(osv.osv):
2738 _name = "stock.inventory.line"
2739 _description = "Inventory Line"
2740 _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2742 def _get_product_name_change(self, cr, uid, ids, context=None):
2743 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2745 def _get_location_change(self, cr, uid, ids, context=None):
2746 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2748 def _get_prodlot_change(self, cr, uid, ids, context=None):
2749 return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2752 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2753 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2754 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2755 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2756 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2757 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2758 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2759 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2760 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2761 'theoretical_qty': fields.float('Theoretical Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), readonly=True),
2762 'partner_id': fields.many2one('res.partner', 'Owner'),
2763 'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
2764 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2765 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2766 'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
2767 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2768 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2769 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
2770 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2771 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2772 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
2773 'stock.production.lot': (_get_prodlot_change, ['name'], 20),
2774 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
2781 def create(self, cr, uid, values, context=None):
2784 product_obj = self.pool.get('product.product')
2785 if 'product_id' in values and not 'product_uom_id' in values:
2786 values['product_uom_id'] = product_obj.browse(cr, uid, values.get('product_id'), context=context).uom_id.id
2787 return super(stock_inventory_line, self).create(cr, uid, values, context=context)
2789 def _resolve_inventory_line(self, cr, uid, inventory_line, context=None):
2790 stock_move_obj = self.pool.get('stock.move')
2791 diff = inventory_line.theoretical_qty - inventory_line.product_qty
2794 #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
2796 'name': _('INV:') + (inventory_line.inventory_id.name or ''),
2797 'product_id': inventory_line.product_id.id,
2798 'product_uom': inventory_line.product_uom_id.id,
2799 'date': inventory_line.inventory_id.date,
2800 'company_id': inventory_line.inventory_id.company_id.id,
2801 'inventory_id': inventory_line.inventory_id.id,
2802 'state': 'confirmed',
2803 'restrict_lot_id': inventory_line.prod_lot_id.id,
2804 'restrict_partner_id': inventory_line.partner_id.id,
2806 inventory_location_id = inventory_line.product_id.property_stock_inventory.id
2808 #found more than expected
2809 vals['location_id'] = inventory_location_id
2810 vals['location_dest_id'] = inventory_line.location_id.id
2811 vals['product_uom_qty'] = -diff
2813 #found less than expected
2814 vals['location_id'] = inventory_line.location_id.id
2815 vals['location_dest_id'] = inventory_location_id
2816 vals['product_uom_qty'] = diff
2817 return stock_move_obj.create(cr, uid, vals, context=context)
2819 def restrict_change(self, cr, uid, ids, theoretical_qty, context=None):
2820 if ids and theoretical_qty:
2821 #if the user try to modify a line prepared by openerp, reject the change and display an error message explaining how he should do
2822 old_value = self.browse(cr, uid, ids[0], context=context)
2825 'product_id': old_value.product_id.id,
2826 'product_uom_id': old_value.product_uom_id.id,
2827 'location_id': old_value.location_id.id,
2828 'prod_lot_id': old_value.prod_lot_id.id,
2829 'package_id': old_value.package_id.id,
2830 'partner_id': old_value.partner_id.id,
2833 'title': _('Error'),
2834 '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.')
2839 def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None):
2841 @param location_id: Location id
2842 @param product: Changed product_id
2843 @param uom: UoM product
2844 @return: Dictionary of changed values
2846 if ids and theoretical_qty:
2847 return self.restrict_change(cr, uid, ids, theoretical_qty, context=context)
2849 return {'value': {'product_uom_id': False}}
2850 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context)
2851 return {'value': {'product_uom_id': uom or obj_product.uom_id.id}}
2854 #----------------------------------------------------------
2856 #----------------------------------------------------------
2857 class stock_warehouse(osv.osv):
2858 _name = "stock.warehouse"
2859 _description = "Warehouse"
2862 'name': fields.char('Warehouse Name', required=True, select=True),
2863 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, select=True),
2864 'partner_id': fields.many2one('res.partner', 'Address'),
2865 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2866 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', domain=[('usage', '=', 'internal')], required=True),
2867 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2868 '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'),
2869 'reception_steps': fields.selection([
2870 ('one_step', 'Receive goods directly in stock (1 step)'),
2871 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2872 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments',
2873 help="Default incoming route to follow", required=True),
2874 'delivery_steps': fields.selection([
2875 ('ship_only', 'Ship directly from stock (Ship only)'),
2876 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2877 ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings',
2878 help="Default outgoing route to follow", required=True),
2879 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2880 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2881 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2882 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2883 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2884 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2885 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2886 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2887 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2888 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2889 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2890 'reception_route_id': fields.many2one('stock.location.route', 'Receipt Route'),
2891 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2892 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2893 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2894 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes',
2895 help="Routes will be created for these resupply warehouses and you can select them on products and product categories"),
2896 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"),
2899 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2900 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2901 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2902 resupply_wh_ids.add(default_resupply_wh_id)
2903 resupply_wh_ids = list(resupply_wh_ids)
2904 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2906 def _get_external_transit_location(self, cr, uid, warehouse, context=None):
2907 ''' returns browse record of inter company transit location, if found'''
2908 data_obj = self.pool.get('ir.model.data')
2909 location_obj = self.pool.get('stock.location')
2911 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2914 return location_obj.browse(cr, uid, inter_wh_loc, context=context)
2916 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2918 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2919 'warehouse_selectable': False,
2920 'product_selectable': True,
2921 'product_categ_selectable': True,
2922 'supplied_wh_id': warehouse.id,
2923 'supplier_wh_id': wh.id,
2926 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2927 route_obj = self.pool.get('stock.location.route')
2928 pull_obj = self.pool.get('procurement.rule')
2929 #create route selectable on the product to resupply the warehouse from another one
2930 external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context)
2931 internal_transit_location = warehouse.company_id.internal_transit_location_id
2932 input_loc = warehouse.wh_input_stock_loc_id
2933 if warehouse.reception_steps == 'one_step':
2934 input_loc = warehouse.lot_stock_id
2935 for wh in supplier_warehouses:
2936 transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location
2937 if transit_location:
2938 output_loc = wh.wh_output_stock_loc_id
2939 if wh.delivery_steps == 'ship_only':
2940 output_loc = wh.lot_stock_id
2941 # Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
2942 mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context)[0]
2943 pull_obj.create(cr, uid, mto_pull_vals, context=context)
2944 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2945 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2946 values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)]
2947 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2948 for pull_rule in pull_rules_list:
2949 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2950 #if the warehouse is also set as default resupply method, assign this route automatically to the warehouse
2951 if default_resupply_wh and default_resupply_wh.id == wh.id:
2952 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2955 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2956 'reception_steps': 'one_step',
2957 'delivery_steps': 'ship_only',
2959 _sql_constraints = [
2960 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2961 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2964 def _get_partner_locations(self, cr, uid, ids, context=None):
2965 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2966 data_obj = self.pool.get('ir.model.data')
2967 location_obj = self.pool.get('stock.location')
2969 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2970 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2972 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2973 customer_loc = customer_loc and customer_loc[0] or False
2974 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2975 supplier_loc = supplier_loc and supplier_loc[0] or False
2976 if not (customer_loc and supplier_loc):
2977 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2978 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2980 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2981 location_obj = self.pool.get('stock.location')
2983 new_reception_step = new_reception_step or warehouse.reception_steps
2984 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2985 if warehouse.reception_steps != new_reception_step:
2986 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2987 if new_reception_step != 'one_step':
2988 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2989 if new_reception_step == 'three_steps':
2990 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2992 if warehouse.delivery_steps != new_delivery_step:
2993 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2994 if new_delivery_step != 'ship_only':
2995 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2996 if new_delivery_step == 'pick_pack_ship':
2997 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
3000 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
3002 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
3003 'product_categ_selectable': True,
3004 'product_selectable': False,
3008 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
3009 pull_rules_list = []
3010 for from_loc, dest_loc, pick_type_id, warehouse in values:
3011 pull_rules_list.append({
3012 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
3013 'location_src_id': from_loc.id,
3014 'location_id': dest_loc.id,
3015 'route_id': new_route_id,
3017 'picking_type_id': pick_type_id,
3018 '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
3019 'warehouse_id': supplied_warehouse.id,
3020 'propagate_warehouse_id': warehouse.id,
3022 return pull_rules_list
3024 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
3026 push_rules_list = []
3027 pull_rules_list = []
3028 for from_loc, dest_loc, pick_type_id in values:
3029 push_rules_list.append({
3030 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
3031 'location_from_id': from_loc.id,
3032 'location_dest_id': dest_loc.id,
3033 'route_id': new_route_id,
3035 'picking_type_id': pick_type_id,
3037 'warehouse_id': warehouse.id,
3039 pull_rules_list.append({
3040 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
3041 'location_src_id': from_loc.id,
3042 'location_id': dest_loc.id,
3043 'route_id': new_route_id,
3045 'picking_type_id': pick_type_id,
3046 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
3048 'warehouse_id': warehouse.id,
3051 return push_rules_list, pull_rules_list
3053 def _get_mto_route(self, cr, uid, context=None):
3054 route_obj = self.pool.get('stock.location.route')
3055 data_obj = self.pool.get('ir.model.data')
3057 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
3059 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
3060 mto_route_id = mto_route_id and mto_route_id[0] or False
3061 if not mto_route_id:
3062 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
3065 def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None):
3066 """ Checks that the moves from the different """
3067 pull_obj = self.pool.get('procurement.rule')
3068 mto_route_id = self._get_mto_route(cr, uid, context=context)
3069 rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context)
3070 pull_obj.unlink(cr, uid, rules, context=context)
3072 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
3073 mto_route_id = self._get_mto_route(cr, uid, context=context)
3075 for value in values:
3076 from_loc, dest_loc, pick_type_id = value
3078 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
3079 'location_src_id': from_loc.id,
3080 'location_id': dest_loc.id,
3081 'route_id': mto_route_id,
3083 'picking_type_id': pick_type_id,
3084 'procure_method': 'make_to_order',
3086 'warehouse_id': warehouse.id,
3090 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
3092 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
3093 'warehouse_selectable': False,
3094 'product_selectable': True,
3095 'product_categ_selectable': True,
3096 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
3100 def create_routes(self, cr, uid, ids, warehouse, context=None):
3102 route_obj = self.pool.get('stock.location.route')
3103 pull_obj = self.pool.get('procurement.rule')
3104 push_obj = self.pool.get('stock.location.path')
3105 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3106 #create reception route and rules
3107 route_name, values = routes_dict[warehouse.reception_steps]
3108 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3109 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
3110 wh_route_ids.append((4, reception_route_id))
3111 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
3112 #create the push/pull rules
3113 for push_rule in push_rules_list:
3114 push_obj.create(cr, uid, vals=push_rule, context=context)
3115 for pull_rule in pull_rules_list:
3116 #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
3117 pull_rule['procure_method'] = 'make_to_order'
3118 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3120 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
3121 route_name, values = routes_dict[warehouse.delivery_steps]
3122 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3123 #create the route and its pull rules
3124 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
3125 wh_route_ids.append((4, delivery_route_id))
3126 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
3127 for pull_rule in pull_rules_list:
3128 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3129 #create MTO pull rule and link it to the generic MTO route
3130 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3131 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
3133 #create a route for cross dock operations, that can be set on products and product categories
3134 route_name, values = routes_dict['crossdock']
3135 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
3136 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
3137 wh_route_ids.append((4, crossdock_route_id))
3138 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)
3139 for pull_rule in pull_rules_list:
3140 # Fixed cross-dock is logically mto
3141 pull_rule['procure_method'] = 'make_to_order'
3142 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3144 #create route selectable on the product to resupply the warehouse from another one
3145 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
3147 #return routes and mto pull rule to store on the warehouse
3149 'route_ids': wh_route_ids,
3150 'mto_pull_id': mto_pull_id,
3151 'reception_route_id': reception_route_id,
3152 'delivery_route_id': delivery_route_id,
3153 'crossdock_route_id': crossdock_route_id,
3156 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
3157 picking_type_obj = self.pool.get('stock.picking.type')
3158 pull_obj = self.pool.get('procurement.rule')
3159 push_obj = self.pool.get('stock.location.path')
3160 route_obj = self.pool.get('stock.location.route')
3161 new_reception_step = new_reception_step or warehouse.reception_steps
3162 new_delivery_step = new_delivery_step or warehouse.delivery_steps
3164 #change the default source and destination location and (de)activate picking types
3165 input_loc = warehouse.wh_input_stock_loc_id
3166 if new_reception_step == 'one_step':
3167 input_loc = warehouse.lot_stock_id
3168 output_loc = warehouse.wh_output_stock_loc_id
3169 if new_delivery_step == 'ship_only':
3170 output_loc = warehouse.lot_stock_id
3171 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
3172 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
3173 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
3174 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
3176 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3177 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
3178 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
3179 route_name, values = routes_dict[new_delivery_step]
3180 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3181 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
3182 #create the pull rules
3183 for pull_rule in pull_rules_list:
3184 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3186 #update receipt route and rules: unlink the existing rules of the warehouse receipt route and recreate it
3187 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
3188 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
3189 route_name, values = routes_dict[new_reception_step]
3190 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3191 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
3192 #create the push/pull rules
3193 for push_rule in push_rules_list:
3194 push_obj.create(cr, uid, vals=push_rule, context=context)
3195 for pull_rule in pull_rules_list:
3196 #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
3197 pull_rule['procure_method'] = 'make_to_order'
3198 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3200 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
3203 dummy, values = routes_dict[new_delivery_step]
3204 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3205 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
3208 def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):
3209 seq_obj = self.pool.get('ir.sequence')
3210 picking_type_obj = self.pool.get('stock.picking.type')
3211 #create new sequences
3212 in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence in'), 'prefix': warehouse.code + '/IN/', 'padding': 5}, context=context)
3213 out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence out'), 'prefix': warehouse.code + '/OUT/', 'padding': 5}, context=context)
3214 pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': warehouse.code + '/PACK/', 'padding': 5}, context=context)
3215 pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': warehouse.code + '/PICK/', 'padding': 5}, context=context)
3216 int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': warehouse.code + '/INT/', 'padding': 5}, context=context)
3218 wh_stock_loc = warehouse.lot_stock_id
3219 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
3220 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
3221 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
3223 #fetch customer and supplier locations, for references
3224 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)
3226 #create in, out, internal picking types for warehouse
3227 input_loc = wh_input_stock_loc
3228 if warehouse.reception_steps == 'one_step':
3229 input_loc = wh_stock_loc
3230 output_loc = wh_output_stock_loc
3231 if warehouse.delivery_steps == 'ship_only':
3232 output_loc = wh_stock_loc
3234 #choose the next available color for the picking types of this warehouse
3236 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
3237 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
3238 #don't use sets to preserve the list order
3239 for x in all_used_colors:
3240 if x['color'] in available_colors:
3241 available_colors.remove(x['color'])
3242 if available_colors:
3243 color = available_colors[0]
3245 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
3246 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
3247 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
3249 in_type_id = picking_type_obj.create(cr, uid, vals={
3250 'name': _('Receipts'),
3251 'warehouse_id': warehouse.id,
3253 'sequence_id': in_seq_id,
3254 'default_location_src_id': supplier_loc.id,
3255 'default_location_dest_id': input_loc.id,
3256 'sequence': max_sequence + 1,
3257 'color': color}, context=context)
3258 out_type_id = picking_type_obj.create(cr, uid, vals={
3259 'name': _('Delivery Orders'),
3260 'warehouse_id': warehouse.id,
3262 'sequence_id': out_seq_id,
3263 'return_picking_type_id': in_type_id,
3264 'default_location_src_id': output_loc.id,
3265 'default_location_dest_id': customer_loc.id,
3266 'sequence': max_sequence + 4,
3267 'color': color}, context=context)
3268 picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
3269 int_type_id = picking_type_obj.create(cr, uid, vals={
3270 'name': _('Internal Transfers'),
3271 'warehouse_id': warehouse.id,
3273 'sequence_id': int_seq_id,
3274 'default_location_src_id': wh_stock_loc.id,
3275 'default_location_dest_id': wh_stock_loc.id,
3277 'sequence': max_sequence + 2,
3278 'color': color}, context=context)
3279 pack_type_id = picking_type_obj.create(cr, uid, vals={
3281 'warehouse_id': warehouse.id,
3283 'sequence_id': pack_seq_id,
3284 'default_location_src_id': wh_pack_stock_loc.id,
3285 'default_location_dest_id': output_loc.id,
3286 'active': warehouse.delivery_steps == 'pick_pack_ship',
3287 'sequence': max_sequence + 3,
3288 'color': color}, context=context)
3289 pick_type_id = picking_type_obj.create(cr, uid, vals={
3291 'warehouse_id': warehouse.id,
3293 'sequence_id': pick_seq_id,
3294 'default_location_src_id': wh_stock_loc.id,
3295 'default_location_dest_id': wh_pack_stock_loc.id,
3296 'active': warehouse.delivery_steps != 'ship_only',
3297 'sequence': max_sequence + 2,
3298 'color': color}, context=context)
3300 #write picking types on WH
3302 'in_type_id': in_type_id,
3303 'out_type_id': out_type_id,
3304 'pack_type_id': pack_type_id,
3305 'pick_type_id': pick_type_id,
3306 'int_type_id': int_type_id,
3308 super(stock_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)
3311 def create(self, cr, uid, vals, context=None):
3316 data_obj = self.pool.get('ir.model.data')
3317 seq_obj = self.pool.get('ir.sequence')
3318 picking_type_obj = self.pool.get('stock.picking.type')
3319 location_obj = self.pool.get('stock.location')
3321 #create view location for warehouse
3323 'name': _(vals.get('code')),
3325 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1],
3327 if vals.get('company_id'):
3328 loc_vals['company_id'] = vals.get('company_id')
3329 wh_loc_id = location_obj.create(cr, uid, loc_vals, context=context)
3330 vals['view_location_id'] = wh_loc_id
3331 #create all location
3332 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
3333 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
3334 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
3335 context_with_inactive = context.copy()
3336 context_with_inactive['active_test'] = False
3338 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
3339 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
3340 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
3341 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
3342 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
3344 for values in sub_locations:
3346 'name': values['name'],
3347 'usage': 'internal',
3348 'location_id': wh_loc_id,
3349 'active': values['active'],
3351 if vals.get('company_id'):
3352 loc_vals['company_id'] = vals.get('company_id')
3353 location_id = location_obj.create(cr, uid, loc_vals, context=context_with_inactive)
3354 vals[values['field']] = location_id
3357 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
3358 warehouse = self.browse(cr, uid, new_id, context=context)
3359 self.create_sequences_and_picking_types(cr, uid, warehouse, context=context)
3362 #create routes and push/pull rules
3363 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
3364 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
3367 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
3368 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
3370 def _format_routename(self, cr, uid, obj, name, context=None):
3371 return obj.name + ': ' + name
3373 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
3374 #fetch customer and supplier locations, for references
3375 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
3378 'one_step': (_('Receipt in 1 step'), []),
3379 'two_steps': (_('Receipt in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3380 '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)]),
3381 '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)]),
3382 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
3383 '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)]),
3384 '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)]),
3387 def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
3388 location_obj = self.pool.get('stock.location')
3389 route_obj = self.pool.get('stock.location.route')
3390 pull_obj = self.pool.get('procurement.rule')
3391 push_obj = self.pool.get('stock.location.path')
3393 location_id = warehouse.lot_stock_id.location_id.id
3394 location_obj.write(cr, uid, location_id, {'name': code}, context=context)
3395 #rename route and push-pull rules
3396 for route in warehouse.route_ids:
3397 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
3398 for pull in route.pull_ids:
3399 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3400 for push in route.push_ids:
3401 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3402 #change the mto pull rule name
3403 if warehouse.mto_pull_id.id:
3404 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
3406 def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None):
3407 """ Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """
3408 #Check routes that are being delivered by this warehouse and change the rule going to transit location
3409 route_obj = self.pool.get("stock.location.route")
3410 pull_obj = self.pool.get("procurement.rule")
3411 routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context)
3412 pulls = pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context)
3414 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)
3415 # Create or clean MTO rules
3416 mto_route_id = self._get_mto_route(cr, uid, context=context)
3417 if not change_to_multiple:
3418 # If single delivery we should create the necessary MTO rules for the resupply
3419 # 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)
3420 pull_recs = pull_obj.browse(cr, uid, pulls, context=context)
3421 transfer_locs = list(set([x.location_id for x in pull_recs]))
3422 vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs]
3423 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context)
3424 for mto_pull_val in mto_pull_vals:
3425 pull_obj.create(cr, uid, mto_pull_val, context=context)
3427 # We need to delete all the MTO pull rules, otherwise they risk to be used in the system
3428 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)
3430 pull_obj.unlink(cr, uid, pulls, context=context)
3432 def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None):
3434 Will check if the resupply routes to this warehouse follow the changes of number of receipt steps
3436 #Check routes that are being delivered by this warehouse and change the rule coming from transit location
3437 route_obj = self.pool.get("stock.location.route")
3438 pull_obj = self.pool.get("procurement.rule")
3439 routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context)
3440 pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')])
3442 pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context)
3444 def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None):
3446 old_val = warehouse.reception_steps
3447 new_val = reception_new
3448 change_to_one = (old_val != 'one_step' and new_val == 'one_step')
3449 change_to_multiple = (old_val == 'one_step' and new_val != 'one_step')
3450 if change_to_one or change_to_multiple:
3451 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id
3452 self._check_reception_resupply(cr, uid, warehouse, new_location, context=context)
3454 old_val = warehouse.delivery_steps
3455 new_val = delivery_new
3456 change_to_one = (old_val != 'ship_only' and new_val == 'ship_only')
3457 change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only')
3458 if change_to_one or change_to_multiple:
3459 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id
3460 self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context)
3462 def write(self, cr, uid, ids, vals, context=None):
3465 if isinstance(ids, (int, long)):
3467 seq_obj = self.pool.get('ir.sequence')
3468 route_obj = self.pool.get('stock.location.route')
3469 context_with_inactive = context.copy()
3470 context_with_inactive['active_test'] = False
3471 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
3472 #first of all, check if we need to delete and recreate route
3473 if vals.get('reception_steps') or vals.get('delivery_steps'):
3474 #activate and deactivate location according to reception and delivery option
3475 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
3476 # switch between route
3477 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
3478 # Check if we need to change something to resupply warehouses and associated MTO rules
3479 self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context)
3481 if vals.get('code') or vals.get('name'):
3482 name = warehouse.name
3484 if vals.get('name'):
3485 name = vals.get('name', warehouse.name)
3486 self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
3487 if warehouse.in_type_id:
3488 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)
3489 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)
3490 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)
3491 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)
3492 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)
3493 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
3494 for cmd in vals.get('resupply_wh_ids'):
3496 new_ids = set(cmd[2])
3497 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
3498 to_add_wh_ids = new_ids - old_ids
3500 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
3501 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
3502 to_remove_wh_ids = old_ids - new_ids
3503 if to_remove_wh_ids:
3504 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)
3505 if to_remove_route_ids:
3506 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
3510 if 'default_resupply_wh_id' in vals:
3511 if vals.get('default_resupply_wh_id') == warehouse.id:
3512 raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
3513 if warehouse.default_resupply_wh_id:
3514 #remove the existing resupplying route on the warehouse
3515 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)
3516 for inter_wh_route_id in to_remove_route_ids:
3517 self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]})
3518 if vals.get('default_resupply_wh_id'):
3519 #assign the new resupplying route on all products
3520 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)
3521 for inter_wh_route_id in to_assign_route_ids:
3522 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]})
3524 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
3526 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
3527 route_obj = self.pool.get("stock.location.route")
3528 all_routes = [route.id for route in warehouse.route_ids]
3529 all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context)
3530 all_routes += [warehouse.mto_pull_id.route_id.id]
3533 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
3535 for wh in self.browse(cr, uid, ids, context=context):
3536 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
3538 domain = [('id', 'in', all_routes)]
3540 'name': _('Warehouse\'s Routes'),
3542 'res_model': 'stock.location.route',
3543 'type': 'ir.actions.act_window',
3545 'view_mode': 'tree,form',
3546 'view_type': 'form',
3551 class stock_location_path(osv.osv):
3552 _name = "stock.location.path"
3553 _description = "Pushed Flows"
3556 def _get_rules(self, cr, uid, ids, context=None):
3558 for route in self.browse(cr, uid, ids, context=context):
3559 res += [x.id for x in route.push_ids]
3563 'name': fields.char('Operation Name', required=True),
3564 'company_id': fields.many2one('res.company', 'Company'),
3565 'route_id': fields.many2one('stock.location.route', 'Route'),
3566 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
3567 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
3568 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
3569 '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"),
3570 'auto': fields.selection(
3571 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
3573 required=True, select=1,
3574 help="This is used to define paths the product has to follow within the location tree.\n" \
3575 "The 'Automatic Move' value will create a stock move after the current one that will be "\
3576 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
3577 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
3579 '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'),
3580 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."),
3581 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3582 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3584 'stock.location.route': (_get_rules, ['sequence'], 10),
3585 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3587 'sequence': fields.integer('Sequence'),
3592 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3597 def _prepare_push_apply(self, cr, uid, rule, move, context=None):
3598 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3600 'location_id': move.location_dest_id.id,
3601 'location_dest_id': rule.location_dest_id.id,
3603 'company_id': rule.company_id and rule.company_id.id or False,
3604 'date_expected': newdate,
3605 'picking_id': False,
3606 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3607 'propagate': rule.propagate,
3608 'push_rule_id': rule.id,
3609 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3612 def _apply(self, cr, uid, rule, move, context=None):
3613 move_obj = self.pool.get('stock.move')
3614 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3615 if rule.auto == 'transparent':
3616 old_dest_location = move.location_dest_id.id
3617 move_obj.write(cr, uid, [move.id], {
3619 'date_expected': newdate,
3620 'location_dest_id': rule.location_dest_id.id
3623 #avoid looping if a push rule is not well configured
3624 if rule.location_dest_id.id != old_dest_location:
3625 #call again push_apply to see if a next step is defined
3626 move_obj._push_apply(cr, uid, [move], context=context)
3628 vals = self._prepare_push_apply(cr, uid, rule, move, context=context)
3629 move_id = move_obj.copy(cr, uid, move.id, vals, context=context)
3630 move_obj.write(cr, uid, [move.id], {
3631 'move_dest_id': move_id,
3633 move_obj.action_confirm(cr, uid, [move_id], context=None)
3636 # -------------------------
3637 # Packaging related stuff
3638 # -------------------------
3640 from openerp.report import report_sxw
3642 class stock_package(osv.osv):
3644 These are the packages, containing quants and/or other packages
3646 _name = "stock.quant.package"
3647 _description = "Physical Packages"
3648 _parent_name = "parent_id"
3649 _parent_store = True
3650 _parent_order = 'name'
3651 _order = 'parent_left'
3653 def name_get(self, cr, uid, ids, context=None):
3654 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3657 def _complete_name(self, cr, uid, ids, name, args, context=None):
3658 """ Forms complete name of location from parent location to child location.
3659 @return: Dictionary of values
3662 for m in self.browse(cr, uid, ids, context=context):
3664 parent = m.parent_id
3666 res[m.id] = parent.name + ' / ' + res[m.id]
3667 parent = parent.parent_id
3670 def _get_packages(self, cr, uid, ids, context=None):
3671 """Returns packages from quants for store"""
3673 for quant in self.browse(cr, uid, ids, context=context):
3674 if quant.package_id:
3675 res.add(quant.package_id.id)
3678 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3680 for pack in self.browse(cr, uid, ids, context=context):
3683 res.add(pack.parent_id.id)
3686 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3687 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3688 res = dict((res_id, {'location_id': False, 'company_id': default_company_id, 'owner_id': False}) for res_id in ids)
3689 for pack in self.browse(cr, uid, ids, context=context):
3691 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3692 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3693 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3694 elif pack.children_ids:
3695 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3696 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3697 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3701 'name': fields.char('Package Reference', select=True, copy=False),
3702 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3703 'parent_left': fields.integer('Left Parent', select=1),
3704 'parent_right': fields.integer('Right Parent', select=1),
3705 '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),
3706 'ul_id': fields.many2one('product.ul', 'Logistic Unit'),
3707 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3709 'stock.quant': (_get_packages, ['location_id'], 10),
3710 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3711 }, readonly=True, select=True),
3712 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
3713 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
3714 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
3715 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3717 'stock.quant': (_get_packages, ['company_id'], 10),
3718 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3719 }, readonly=True, select=True),
3720 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3722 'stock.quant': (_get_packages, ['owner_id'], 10),
3723 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3724 }, readonly=True, select=True),
3727 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').next_by_code(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3730 def _check_location_constraint(self, cr, uid, packs, context=None):
3731 '''checks that all quants in a package are stored in the same location. This function cannot be used
3732 as a constraint because it needs to be checked on pack operations (they may not call write on the
3735 quant_obj = self.pool.get('stock.quant')
3738 while parent.parent_id:
3739 parent = parent.parent_id
3740 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3741 quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0]
3742 location_id = quants and quants[0].location_id.id or False
3743 if not [quant.location_id.id == location_id for quant in quants]:
3744 raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
3747 def action_print(self, cr, uid, ids, context=None):
3748 context = dict(context or {}, active_ids=ids)
3749 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_package_barcode_small', context=context)
3752 def unpack(self, cr, uid, ids, context=None):
3753 quant_obj = self.pool.get('stock.quant')
3754 for package in self.browse(cr, uid, ids, context=context):
3755 quant_ids = [quant.id for quant in package.quant_ids]
3756 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3757 children_package_ids = [child_package.id for child_package in package.children_ids]
3758 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3759 #delete current package since it contains nothing anymore
3760 self.unlink(cr, uid, ids, context=context)
3761 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3763 def get_content(self, cr, uid, ids, context=None):
3764 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3765 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3767 def get_content_package(self, cr, uid, ids, context=None):
3768 quants_ids = self.get_content(cr, uid, ids, context=context)
3769 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3770 res['domain'] = [('id', 'in', quants_ids)]
3773 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3774 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3775 quant_obj = self.pool.get('stock.quant')
3776 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3778 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3779 if quant.product_id.id == product_id:
3783 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3784 '''This function computes the different product quantities for the given package
3786 quant_obj = self.pool.get('stock.quant')
3788 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3789 if quant.product_id.id not in res:
3790 res[quant.product_id.id] = 0
3791 res[quant.product_id.id] += quant.qty
3794 def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
3795 stock_pack_operation_obj = self.pool.get('stock.pack.operation')
3798 new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
3799 default['result_package_id'] = new_package_id
3800 op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
3801 for op_id in op_ids:
3802 stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
3805 class stock_pack_operation(osv.osv):
3806 _name = "stock.pack.operation"
3807 _description = "Packing Operation"
3809 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3810 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3811 #if the operation doesn't concern a package, it's not relevant to call this function
3812 if not operation.package_id or operation.product_id:
3813 return {operation.product_id.id: operation.remaining_qty}
3814 #get the total of products the package contains
3815 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3816 #reduce by the quantities linked to a move
3817 for record in operation.linked_move_operation_ids:
3818 if record.move_id.product_id.id not in res:
3819 res[record.move_id.product_id.id] = 0
3820 res[record.move_id.product_id.id] -= record.qty
3823 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3824 uom_obj = self.pool.get('product.uom')
3826 for ops in self.browse(cr, uid, ids, context=context):
3828 if ops.package_id and not ops.product_id:
3829 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3830 #should use _get_remaining_prod_quantities instead
3833 qty = ops.product_qty
3834 if ops.product_uom_id:
3835 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
3836 for record in ops.linked_move_operation_ids:
3838 #converting the remaining quantity in the pack operation UoM
3839 if ops.product_uom_id:
3840 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context)
3844 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3845 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3846 if product_id and not product_uom_id:
3847 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3848 res['value']['product_uom_id'] = product.uom_id.id
3851 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3853 uom_obj = self.pool.get('product.uom')
3855 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3856 product_uom_id = product_uom_id or product.uom_id.id
3857 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3858 if selected_uom.category_id.id != product.uom_id.category_id.id:
3860 'title': _('Warning: wrong UoM!'),
3861 '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)
3863 if product_qty and 'warning' not in res:
3864 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3865 if rounded_qty != product_qty:
3867 'title': _('Warning: wrong quantity!'),
3868 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3873 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3874 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3875 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3876 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3877 'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
3878 'package_id': fields.many2one('stock.quant.package', 'Source Package'), # 2
3879 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3880 'result_package_id': fields.many2one('stock.quant.package', 'Destination Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3881 'date': fields.datetime('Date', required=True),
3882 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3883 #'update_cost': fields.boolean('Need cost update'),
3884 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3885 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3886 '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'),
3887 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3888 'location_id': fields.many2one('stock.location', 'Source Location', required=True),
3889 'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True),
3890 'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
3894 'date': fields.date.context_today,
3896 'processed': lambda *a: 'false',
3899 def write(self, cr, uid, ids, vals, context=None):
3900 context = context or {}
3901 res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
3902 if isinstance(ids, (int, long)):
3904 if not context.get("no_recompute"):
3905 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)]))
3906 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
3909 def create(self, cr, uid, vals, context=None):
3910 context = context or {}
3911 res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
3912 if vals.get("picking_id") and not context.get("no_recompute"):
3913 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
3916 def action_drop_down(self, cr, uid, ids, context=None):
3917 ''' Used by barcode interface to say that pack_operation has been moved from src location
3918 to destination location, if qty_done is less than product_qty than we have to split the
3919 operation in two to process the one with the qty moved
3922 move_obj = self.pool.get("stock.move")
3923 for pack_op in self.browse(cr, uid, ids, context=None):
3924 if pack_op.product_id and pack_op.location_id and pack_op.location_dest_id:
3925 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)
3927 if pack_op.qty_done < pack_op.product_qty:
3928 # we split the operation in two
3929 op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
3930 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)
3931 processed_ids.append(op)
3932 self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
3934 def create_and_assign_lot(self, cr, uid, id, name, context=None):
3935 ''' Used by barcode interface to create a new lot and assign it to the operation
3937 obj = self.browse(cr,uid,id,context)
3938 product_id = obj.product_id.id
3939 val = {'product_id': product_id}
3942 lots = self.pool.get('stock.production.lot').search(cr, uid, ['&', ('name', '=', name), ('product_id', '=', product_id)], context=context)
3944 new_lot_id = lots[0]
3945 val.update({'name': name})
3948 new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context)
3949 self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
3951 def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, weight=-1, increment=True, context=None):
3952 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+weight if weight != -1, +1 otherwise) otherwise create it
3954 :param domain: list of tuple directly reusable as a domain
3955 context can receive a key 'current_package_id' with the package to consider for this operation
3956 weight is used for weighted products for which quantity != 1 (not per unit but e.g. per kg). Weight == -1 when buttons - or + are pressed.
3962 #if current_package_id is given in the context, we increase the number of items in this package
3963 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3964 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3965 todo_operation_ids = []
3966 if existing_operation_ids:
3968 todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
3970 todo_operation_ids = existing_operation_ids
3971 if todo_operation_ids:
3972 #existing operation found for the given domain and picking => increment its quantity
3973 operation_id = todo_operation_ids[0]
3974 op_obj = self.browse(cr, uid, operation_id, context=context)
3975 qty = op_obj.qty_done
3977 if weight == -1: # increment by 1
3978 if qty < op_obj.product_qty:
3979 qty = min(qty+1, op_obj.product_qty);
3982 else: # Weigth scanned
3985 if qty == 0 and op_obj.product_qty == 0:
3986 #we have a line with 0 qty set, so delete it
3987 self.unlink(cr, uid, [operation_id], context=context)
3990 qty = max(0, qty-1) #if qty >= 1 else 0
3991 self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
3993 #no existing operation found for the given domain and picking => create a new one
3994 picking_obj = self.pool.get("stock.picking")
3995 picking = picking_obj.browse(cr, uid, picking_id, context=context)
3997 'picking_id': picking_id,
3999 'location_id': picking.location_id.id,
4000 'location_dest_id': picking.location_dest_id.id,
4001 'qty_done': weight if weight != -1 else 1,
4004 var_name, dummy, value = key
4006 if var_name == 'product_id':
4007 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
4008 update_dict = {var_name: value}
4010 update_dict['product_uom_id'] = uom_id
4011 values.update(update_dict)
4012 operation_id = self.create(cr, uid, values, context=context)
4016 class stock_move_operation_link(osv.osv):
4018 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
4020 _name = "stock.move.operation.link"
4021 _description = "Link between stock moves and pack operations"
4024 '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."),
4025 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
4026 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
4027 '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"),
4030 def get_specific_domain(self, cr, uid, record, context=None):
4031 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
4032 having the record given as parameter making the link between the stock move and a pack operation'''
4034 op = record.operation_id
4036 if op.package_id and op.product_id:
4037 #if removing a product from a box, we restrict the choice of quants to this box
4038 domain.append(('package_id', '=', op.package_id.id))
4040 #if moving a box, we allow to take everything from inside boxes as well
4041 domain.append(('package_id', 'child_of', [op.package_id.id]))
4043 #if not given any information about package, we don't open boxes
4044 domain.append(('package_id', '=', False))
4045 #if lot info is given, we restrict choice to this lot otherwise we can take any
4047 domain.append(('lot_id', '=', op.lot_id.id))
4048 #if owner info is given, we restrict to this owner otherwise we restrict to no owner
4050 domain.append(('owner_id', '=', op.owner_id.id))
4052 domain.append(('owner_id', '=', False))
4055 class stock_warehouse_orderpoint(osv.osv):
4057 Defines Minimum stock rules.
4059 _name = "stock.warehouse.orderpoint"
4060 _description = "Minimum Inventory Rule"
4062 def subtract_procurements(self, cr, uid, orderpoint, context=None):
4063 '''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.
4066 uom_obj = self.pool.get("product.uom")
4067 for procurement in orderpoint.procurement_ids:
4068 if procurement.state in ('cancel', 'done'):
4070 procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context)
4071 for move in procurement.move_ids:
4072 #need to add the moves in draft as they aren't in the virtual quantity + moves that have not been created yet
4073 if move.state not in ('draft'):
4074 #if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted
4075 procurement_qty -= move.product_qty
4076 qty += procurement_qty
4079 def _check_product_uom(self, cr, uid, ids, context=None):
4081 Check if the UoM has the same category as the product standard UoM
4086 for rule in self.browse(cr, uid, ids, context=context):
4087 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
4091 def action_view_proc_to_process(self, cr, uid, ids, context=None):
4092 act_obj = self.pool.get('ir.actions.act_window')
4093 mod_obj = self.pool.get('ir.model.data')
4094 proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context)
4095 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
4099 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
4100 result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]"
4104 'name': fields.char('Name', required=True, copy=False),
4105 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
4106 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
4107 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
4108 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
4109 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]),
4110 'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True),
4111 'product_min_qty': fields.float('Minimum Quantity', required=True,
4112 digits_compute=dp.get_precision('Product Unit of Measure'),
4113 help="When the virtual stock goes below the Min Quantity specified for this field, Odoo generates "\
4114 "a procurement to bring the forecasted quantity to the Max Quantity."),
4115 'product_max_qty': fields.float('Maximum Quantity', required=True,
4116 digits_compute=dp.get_precision('Product Unit of Measure'),
4117 help="When the virtual stock goes below the Min Quantity, Odoo generates "\
4118 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
4119 'qty_multiple': fields.float('Qty Multiple', required=True,
4120 digits_compute=dp.get_precision('Product Unit of Measure'),
4121 help="The procurement quantity will be rounded up to this multiple. If it is 0, the exact quantity will be used. "),
4122 'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'),
4123 '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),
4124 'company_id': fields.many2one('res.company', 'Company', required=True),
4127 'active': lambda *a: 1,
4128 'logic': lambda *a: 'max',
4129 'qty_multiple': lambda *a: 1,
4130 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').next_by_code(cr, uid, 'stock.orderpoint') or '',
4131 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
4132 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
4134 _sql_constraints = [
4135 ('qty_multiple_check', 'CHECK( qty_multiple >= 0 )', 'Qty Multiple must be greater than or equal to zero.'),
4138 (_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']),
4141 def default_get(self, cr, uid, fields, context=None):
4142 warehouse_obj = self.pool.get('stock.warehouse')
4143 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
4144 # default 'warehouse_id' and 'location_id'
4145 if 'warehouse_id' not in res:
4146 warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or []
4147 res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False
4148 if 'location_id' not in res:
4149 res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False
4152 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
4153 """ Finds location id for changed warehouse.
4154 @param warehouse_id: Changed id of warehouse.
4155 @return: Dictionary of values.
4158 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
4159 v = {'location_id': w.lot_stock_id.id}
4163 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
4164 """ Finds UoM for changed product.
4165 @param product_id: Changed id of product.
4166 @return: Dictionary of values.
4169 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
4170 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
4171 v = {'product_uom': prod.uom_id.id}
4172 return {'value': v, 'domain': d}
4173 return {'domain': {'product_uom': []}}
4175 class stock_picking_type(osv.osv):
4176 _name = "stock.picking.type"
4177 _description = "The picking type determines the picking view"
4180 def open_barcode_interface(self, cr, uid, ids, context=None):
4181 final_url = "/stock/barcode/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0'
4182 return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'}
4184 def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
4185 picking_obj = self.pool.get('stock.picking')
4187 for picking_type_id in ids:
4188 #get last 10 pickings of this type
4189 picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
4191 for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
4192 if picking.date_done > picking.date:
4193 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Late'), 'value': -1})
4194 elif picking.backorder_id:
4195 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Backorder exists'), 'value': 0})
4197 tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('OK'), 'value': 1})
4198 res[picking_type_id] = json.dumps(tristates)
4201 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
4202 obj = self.pool.get('stock.picking')
4204 'count_picking_draft': [('state', '=', 'draft')],
4205 'count_picking_waiting': [('state', '=', 'confirmed')],
4206 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
4207 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4208 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4209 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
4212 for field in domains:
4213 data = obj.read_group(cr, uid, domains[field] +
4214 [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
4215 ['picking_type_id'], ['picking_type_id'], context=context)
4216 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
4218 result.setdefault(tid, {})[field] = count.get(tid, 0)
4220 if result[tid]['count_picking']:
4221 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
4222 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
4224 result[tid]['rate_picking_late'] = 0
4225 result[tid]['rate_picking_backorders'] = 0
4228 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
4229 if not picking_code:
4232 obj_data = self.pool.get('ir.model.data')
4233 stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock')
4236 'default_location_src_id': stock_loc,
4237 'default_location_dest_id': stock_loc,
4239 if picking_code == 'incoming':
4240 result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers')
4241 elif picking_code == 'outgoing':
4242 result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers')
4243 return {'value': result}
4245 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
4246 return dict(self.name_get(cr, uid, ids, context=context))
4248 def name_get(self, cr, uid, ids, context=None):
4249 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
4252 if not isinstance(ids, list):
4257 for record in self.browse(cr, uid, ids, context=context):
4259 if record.warehouse_id:
4260 name = record.warehouse_id.name + ': ' +name
4261 if context.get('special_shortened_wh_name'):
4262 if record.warehouse_id:
4263 name = record.warehouse_id.name
4265 name = _('Customer') + ' (' + record.name + ')'
4266 res.append((record.id, name))
4269 def _default_warehouse(self, cr, uid, context=None):
4270 user = self.pool.get('res.users').browse(cr, uid, uid, context)
4271 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
4272 return res and res[0] or False
4275 'name': fields.char('Picking Type Name', translate=True, required=True),
4276 'complete_name': fields.function(_get_name, type='char', string='Name'),
4277 'color': fields.integer('Color'),
4278 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
4279 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
4280 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
4281 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
4282 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
4283 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
4284 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
4285 'active': fields.boolean('Active'),
4287 # Statistics for the kanban view
4288 'last_done_picking': fields.function(_get_tristate_values,
4290 string='Last 10 Done Pickings'),
4292 'count_picking_draft': fields.function(_get_picking_count,
4293 type='integer', multi='_get_picking_count'),
4294 'count_picking_ready': fields.function(_get_picking_count,
4295 type='integer', multi='_get_picking_count'),
4296 'count_picking': fields.function(_get_picking_count,
4297 type='integer', multi='_get_picking_count'),
4298 'count_picking_waiting': fields.function(_get_picking_count,
4299 type='integer', multi='_get_picking_count'),
4300 'count_picking_late': fields.function(_get_picking_count,
4301 type='integer', multi='_get_picking_count'),
4302 'count_picking_backorders': fields.function(_get_picking_count,
4303 type='integer', multi='_get_picking_count'),
4305 'rate_picking_late': fields.function(_get_picking_count,
4306 type='integer', multi='_get_picking_count'),
4307 'rate_picking_backorders': fields.function(_get_picking_count,
4308 type='integer', multi='_get_picking_count'),
4312 'warehouse_id': _default_warehouse,
4316 class barcode_rule(models.Model):
4317 _inherit = 'barcode.rule'
4319 type = openerp.fields.Selection(selection_add=[
4320 ('weight','Weighted Product'),
4321 ('location','Location'),
4323 ('package','Package')
4326 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: