1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import date, datetime
23 from dateutil import relativedelta
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
30 from openerp import SUPERUSER_ID
31 import openerp.addons.decimal_precision as dp
32 from openerp.addons.procurement import procurement
36 _logger = logging.getLogger(__name__)
37 #----------------------------------------------------------
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41 _name = "stock.incoterms"
42 _description = "Incoterms"
44 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
45 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
46 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
52 #----------------------------------------------------------
54 #----------------------------------------------------------
56 class stock_location(osv.osv):
57 _name = "stock.location"
58 _description = "Inventory Locations"
59 _parent_name = "location_id"
61 _parent_order = 'name'
62 _order = 'parent_left'
63 _rec_name = 'complete_name'
65 def _location_owner(self, cr, uid, location, context=None):
66 ''' Return the company owning the location if any '''
67 return location and (location.usage == 'internal') and location.company_id or False
69 def _complete_name(self, cr, uid, ids, name, args, context=None):
70 """ Forms complete name of location from parent location to child location.
71 @return: Dictionary of values
74 for m in self.browse(cr, uid, ids, context=context):
76 parent = m.location_id
78 res[m.id] = parent.name + ' / ' + res[m.id]
79 parent = parent.location_id
82 def _get_sublocations(self, cr, uid, ids, context=None):
83 """ return all sublocations of the given stock locations (included) """
86 context_with_inactive = context.copy()
87 context_with_inactive['active_test'] = False
88 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
90 def _name_get(self, cr, uid, location, context=None):
92 while location.location_id and location.usage != 'view':
93 location = location.location_id
94 name = location.name + '/' + name
97 def name_get(self, cr, uid, ids, context=None):
99 for location in self.browse(cr, uid, ids, context=context):
100 res.append((location.id, self._name_get(cr, uid, location, context=context)))
104 'name': fields.char('Location Name', size=64, required=True, translate=True),
105 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
106 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location')], 'Location Type', required=True,
107 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
108 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
109 \n* Internal Location: Physical locations inside your own warehouses,
110 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
111 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
112 \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.
113 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
114 \n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations
117 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
118 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
119 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
120 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
122 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
124 'comment': fields.text('Additional Information'),
125 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
126 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
127 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
129 'parent_left': fields.integer('Left Parent', select=1),
130 'parent_right': fields.integer('Right Parent', select=1),
132 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
133 'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
134 '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."),
135 '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."),
136 'loc_barcode': fields.char('Location Barcode'),
141 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
145 'scrap_location': False,
147 _sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')]
149 def create(self, cr, uid, default, context=None):
150 if not default.get('loc_barcode', False):
151 default.update({'loc_barcode': default.get('complete_name', False)})
152 return super(stock_location, self).create(cr, uid, default, context=context)
154 def get_putaway_strategy(self, cr, uid, location, product, context=None):
155 ''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.'''
156 putaway_obj = self.pool.get('product.putaway')
159 if loc.putaway_strategy_id:
160 res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context)
163 loc = loc.location_id
165 def _default_removal_strategy(self, cr, uid, context=None):
168 def get_removal_strategy(self, cr, uid, location, product, context=None):
169 ''' Returns the removal strategy to consider for the given product and location.
170 :param location: browse record (stock.location)
171 :param product: browse record (product.product)
174 if product.categ_id.removal_strategy_id:
175 return product.categ_id.removal_strategy_id.method
178 if loc.removal_strategy_id:
179 return loc.removal_strategy_id.method
180 loc = loc.location_id
181 return self._default_removal_strategy(cr, uid, context=context)
184 #----------------------------------------------------------
186 #----------------------------------------------------------
188 class stock_location_route(osv.osv):
189 _name = 'stock.location.route'
190 _description = "Inventory Routes"
194 'name': fields.char('Route Name', required=True),
195 'sequence': fields.integer('Sequence'),
196 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'),
197 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
198 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'),
199 'product_selectable': fields.boolean('Applicable on Product'),
200 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
201 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
202 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
203 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
204 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
208 'sequence': lambda self, cr, uid, ctx: 0,
210 'product_selectable': True,
211 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
214 def write(self, cr, uid, ids, vals, context=None):
215 '''when a route is deactivated, deactivate also its pull and push rules'''
216 if isinstance(ids, (int, long)):
218 res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context)
222 for route in self.browse(cr, uid, ids, context=context):
224 push_ids += [r.id for r in route.push_ids if r.active != vals['active']]
226 pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']]
228 self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context)
230 self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context)
233 #----------------------------------------------------------
235 #----------------------------------------------------------
237 class stock_quant(osv.osv):
239 Quants are the smallest unit of stock physical instances
241 _name = "stock.quant"
242 _description = "Quants"
244 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
245 """ Forms complete name of location from parent location to child location.
246 @return: Dictionary of values
249 for q in self.browse(cr, uid, ids, context=context):
251 res[q.id] = q.product_id.code or ''
253 res[q.id] = q.lot_id.name
254 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
257 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
259 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
260 for quant in self.browse(cr, uid, ids, context=context):
261 context.pop('force_company', None)
262 if quant.company_id.id != uid_company_id:
263 #if the company of the quant is different than the current user company, force the company in the context
264 #then re-do a browse to read the property fields for the good company.
265 context['force_company'] = quant.company_id.id
266 quant = self.browse(cr, uid, quant.id, context=context)
267 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
270 def _get_inventory_value(self, cr, uid, quant, context=None):
271 return quant.product_id.standard_price * quant.qty
274 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
275 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict"),
276 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict"),
277 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"),
278 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"),
279 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True),
280 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"),
281 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
282 'cost': fields.float('Unit Cost'),
283 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"),
285 'create_date': fields.datetime('Creation Date'),
286 'in_date': fields.datetime('Incoming Date'),
288 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
289 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True),
290 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
292 # Used for negative quants to reconcile after compensated by a new positive one
293 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'),
294 '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.'),
295 'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", help="Technical field used to record the destination location of a move that created a negative quant"),
299 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
302 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
303 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
304 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
305 if 'inventory_value' in fields:
307 if '__domain' in line:
308 lines = self.search(cr, uid, line['__domain'], context=context)
310 for line2 in self.browse(cr, uid, lines, context=context):
311 inv_value += line2.inventory_value
312 line['inventory_value'] = inv_value
315 def action_view_quant_history(self, cr, uid, ids, context=None):
317 This function returns an action that display the history of the quant, which
318 mean all the stock moves that lead to this quant creation with this quant quantity.
320 mod_obj = self.pool.get('ir.model.data')
321 act_obj = self.pool.get('ir.actions.act_window')
323 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
324 id = result and result[1] or False
325 result = act_obj.read(cr, uid, [id], context={})[0]
328 for quant in self.browse(cr, uid, ids, context=context):
329 move_ids += [move.id for move in quant.history_ids]
331 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
334 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
335 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
336 is also set to 'assigned'
338 :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
339 :param move: browse record
340 :param link: browse record (stock.move.operation.link)
343 reserved_availability = move.reserved_availability
344 #split quants if needed
345 for quant, qty in quants:
346 if qty <= 0.0 or (quant and quant.qty <= 0.0):
347 raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
350 self._quant_split(cr, uid, quant, qty, context=context)
351 toreserve.append(quant.id)
352 reserved_availability += quant.qty
355 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
356 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
358 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
359 #check if move'state needs to be set as 'assigned'
360 if reserved_availability == move.product_qty and move.state in ('confirmed', 'waiting'):
361 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
362 elif reserved_availability > 0 and not move.partially_available:
363 self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
365 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):
366 """Moves all given stock.quant in the given destination location.
367 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
368 :param move: browse record (stock.move)
369 :param location_to: browse record (stock.location) depicting where the quants have to be moved
370 :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
371 :param lot_id: ID of the lot that must be set on the quants to move
372 :param owner_id: ID of the partner that must own the quants to move
373 :param src_package_id: ID of the package that contains the quants to move
374 :param dest_package_id: ID of the package that must be set on the moved quant
376 quants_reconcile = []
378 self._check_location(cr, uid, location_to, context=context)
379 for quant, qty in quants:
381 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
382 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)
384 self._quant_split(cr, uid, quant, qty, context=context)
386 to_move_quants.append(quant)
387 quants_reconcile.append(quant)
389 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]
390 self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
391 self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context)
392 if location_to.usage == 'internal':
393 if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context):
394 for quant in quants_reconcile:
396 self._quant_reconcile_negative(cr, uid, quant, move, context=context)
398 def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
399 vals = {'location_id': location_dest_id.id,
400 'history_ids': [(4, move.id)],
401 'package_id': dest_package_id}
402 self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
404 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):
405 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
406 the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached
407 it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on).
408 Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal
412 quants = [(None, qty)]
413 #don't look for quants in location that are of type production, supplier or inventory.
414 if location.usage in ['inventory', 'production', 'supplier']:
417 if not prefered_domain_list:
418 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)
419 for prefered_domain in prefered_domain_list:
421 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
423 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)
424 for quant in tmp_quants:
430 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
432 Use the removal strategies of product to search for the correct quants
433 If you inherit, put the super at the end of your method.
435 :location: browse record of the parent location where the quants have to be found
436 :product: browse record of the product to find
437 :qty in UoM of product
440 domain = domain or [('qty', '>', 0.0)]
441 if restrict_partner_id:
442 domain += [('owner_id', '=', restrict_partner_id)]
444 domain += [('lot_id', '=', restrict_lot_id)]
446 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context)
447 result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context)
450 def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None):
451 if removal_strategy == 'fifo':
452 order = 'in_date, id'
453 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
454 elif removal_strategy == 'lifo':
455 order = 'in_date desc, id desc'
456 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
457 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
459 def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False,
460 force_location_from=False, force_location_to=False, context=None):
461 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
465 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
466 location = force_location_to or move.location_dest_id
468 'product_id': move.product_id.id,
469 'location_id': location.id,
472 'history_ids': [(4, move.id)],
473 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
474 'company_id': move.company_id.id,
476 'owner_id': owner_id,
477 'package_id': dest_package_id,
480 if move.location_id.usage == 'internal':
481 #if we were trying to move something from an internal location and reach here (quant creation),
482 #it means that a negative quant has to be created as well.
483 negative_vals = vals.copy()
484 negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id
485 negative_vals['qty'] = -qty
486 negative_vals['cost'] = price_unit
487 negative_vals['negative_move_id'] = move.id
488 negative_vals['package_id'] = src_package_id
489 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
490 vals.update({'propagated_from_id': negative_quant_id})
492 #create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants
493 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
494 return self.browse(cr, uid, quant_id, context=context)
496 def _quant_split(self, cr, uid, quant, qty, context=None):
497 context = context or {}
498 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
500 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
501 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
503 return self.browse(cr, uid, new_quant, context=context)
505 def _get_latest_move(self, cr, uid, quant, context=None):
507 for m in quant.history_ids:
508 if not move or m.date > move.date:
512 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
514 for move in solving_quant.history_ids:
515 path.append((4, move.id))
516 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
518 def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
520 When new quant arrive in a location, try to reconcile it with
521 negative quants. If it's possible, apply the cost of the new
522 quant to the conter-part of the negative quant.
524 solving_quant = quant
525 dom = [('qty', '<', 0)]
527 dom += [('lot_id', '=', quant.lot_id.id)]
528 dom += [('owner_id', '=', quant.owner_id.id)]
529 dom += [('package_id', '=', quant.package_id.id)]
530 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
531 for quant_neg, qty in quants:
534 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
535 if not to_solve_quant_ids:
538 solved_quant_ids = []
539 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
542 solved_quant_ids.append(to_solve_quant.id)
543 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
544 solving_qty -= min(solving_qty, to_solve_quant.qty)
545 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
546 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
547 #if the reconciliation was not complete, we need to link together the remaining parts
548 if remaining_neg_quant:
549 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
550 if remaining_to_solve_quant_ids:
551 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
552 #delete the reconciled quants, as it is replaced by the solved quants
553 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
554 #price update + accounting entries adjustments
555 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
556 #merge history (and cost?)
557 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
558 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
559 solving_quant = remaining_solving_quant
561 def _price_update(self, cr, uid, ids, newprice, context=None):
562 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
564 def quants_unreserve(self, cr, uid, move, context=None):
565 related_quants = [x.id for x in move.reserved_quant_ids]
567 #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
569 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
570 if move.partially_available:
571 self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
572 self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
574 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
575 ''' Implementation of removal strategies
576 If it can not reserve, it will return a tuple (None, qty)
580 domain += location and [('location_id', 'child_of', location.id)] or []
581 domain += [('product_id', '=', product.id)]
582 if context.get('force_company'):
583 domain += [('company_id', '=', context.get('force_company'))]
585 domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
589 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
591 res.append((None, quantity))
593 for quant in self.browse(cr, uid, quants, context=context):
594 if quantity >= abs(quant.qty):
595 res += [(quant, abs(quant.qty))]
596 quantity -= abs(quant.qty)
598 res += [(quant, quantity)]
604 def _check_location(self, cr, uid, location, context=None):
605 if location.usage == 'view':
606 raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
610 #----------------------------------------------------------
612 #----------------------------------------------------------
614 class stock_picking(osv.osv):
615 _name = "stock.picking"
616 _inherit = ['mail.thread']
617 _description = "Picking List"
618 _order = "priority desc, date asc, id desc"
620 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
621 move_obj = self.pool.get("stock.move")
623 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
624 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
626 def _set_priority(self, cr, uid, id, field, value, arg, context=None):
627 move_obj = self.pool.get("stock.move")
629 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
630 move_obj.write(cr, uid, move_ids, {'priority': value}, context=context)
632 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
633 """ Finds minimum and maximum dates for picking.
634 @return: Dictionary of values
638 res[id] = {'min_date': False, 'max_date': False, 'priority': '1'}
651 picking_id""", (tuple(ids),))
652 for pick, dt1, dt2, prio in cr.fetchall():
653 res[pick]['min_date'] = dt1
654 res[pick]['max_date'] = dt2
655 res[pick]['priority'] = prio
658 def create(self, cr, user, vals, context=None):
659 context = context or {}
660 if ('name' not in vals) or (vals.get('name') in ('/', False)):
661 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
662 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
663 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
664 return super(stock_picking, self).create(cr, user, vals, context)
666 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
667 '''The state of a picking depends on the state of its related stock.move
668 draft: the picking has no line or any one of the lines is draft
669 done, draft, cancel: all lines are done / draft / cancel
670 confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial)
673 for pick in self.browse(cr, uid, ids, context=context):
674 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
675 res[pick.id] = 'draft'
677 if all([x.state == 'cancel' for x in pick.move_lines]):
678 res[pick.id] = 'cancel'
680 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
681 res[pick.id] = 'done'
684 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
685 order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
686 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
687 if pick.move_type == 'one':
688 res[pick.id] = order_inv[min(lst)]
690 #we are in the case of partial delivery, so if all move are assigned, picking
691 #should be assign too, else if one of the move is assigned, or partially available, picking should be
692 #in partially available state, otherwise, picking is in waiting or confirmed state
693 res[pick.id] = order_inv[max(lst)]
694 if not all(x == 2 for x in lst):
695 if any(x == 2 for x in lst):
696 res[pick.id] = 'partially_available'
698 #if all moves aren't assigned, check if we have one product partially available
699 for move in pick.move_lines:
700 if move.partially_available:
701 res[pick.id] = 'partially_available'
705 def _get_pickings(self, cr, uid, ids, context=None):
707 for move in self.browse(cr, uid, ids, context=context):
709 res.add(move.picking_id.id)
712 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
714 for pick in self.browse(cr, uid, ids, context=context):
716 if pick.pack_operation_ids:
720 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
722 for pick in self.browse(cr, uid, ids, context=context):
724 for move in pick.move_lines:
725 if move.reserved_quant_ids:
730 def check_group_lot(self, cr, uid, context=None):
731 """ This function will return true if we have the setting to use lots activated. """
732 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot')
734 def check_group_pack(self, cr, uid, context=None):
735 """ This function will return true if we have the setting to use package activated. """
736 return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot')
738 def action_assign_owner(self, cr, uid, ids, context=None):
739 for picking in self.browse(cr, uid, ids, context=context):
740 packop_ids = [op.id for op in picking.pack_operation_ids]
741 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
744 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
745 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
746 '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),
747 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
748 '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"),
749 'state': fields.function(_state_get, type="selection",
751 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
752 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)},
755 ('cancel', 'Cancelled'),
756 ('waiting', 'Waiting Another Operation'),
757 ('confirmed', 'Waiting Availability'),
758 ('partially_available', 'Partially Available'),
759 ('assigned', 'Ready to Transfer'),
760 ('done', 'Transferred'),
761 ], string='Status', readonly=True, select=True, track_visibility='onchange',
763 * Draft: not confirmed yet and will not be scheduled until confirmed\n
764 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
765 * Waiting Availability: still waiting for the availability of products\n
766 * Partially Available: some products are available and reserved\n
767 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
768 * Transferred: has been processed, can't be modified or cancelled anymore\n
769 * Cancelled: has been cancelled, can't be confirmed anymore"""
771 'priority': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_priority, type='selection', selection=procurement.PROCUREMENT_PRIORITIES, string='Priority',
772 store={'stock.move': (_get_pickings, ['priority'], 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",
773 track_visibility='onchange', required=True),
774 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
775 store={'stock.move': (_get_pickings, ['date_expected'], 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'),
776 'max_date': fields.function(get_min_max_date, multi="min_max_date",
777 store={'stock.move': (_get_pickings, ['date_expected'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
778 'date': fields.datetime('Commitment Date', help="Date promised for the completion of the transfer order, usually set the time of the order and revised later on.", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, track_visibility='onchange'),
779 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
780 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
781 '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'),
782 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
783 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
784 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
785 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
786 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
787 '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"),
789 'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
790 # Used to search on pickings
791 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
792 'recompute_pack_op': fields.boolean('Recompute pack operation?', help='True if reserved quants changed, which mean we might need to recompute the package operations'),
793 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
794 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
795 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
797 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
798 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
803 'name': lambda self, cr, uid, context: '/',
805 'move_type': 'direct',
806 'priority': '1', # normal
807 'date': fields.datetime.now,
808 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c),
809 'recompute_pack_op': True,
812 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
815 def copy(self, cr, uid, id, default=None, context=None):
818 default = default.copy()
819 picking_obj = self.browse(cr, uid, id, context=context)
820 if ('name' not in default) or (picking_obj.name == '/'):
821 default['name'] = '/'
822 if not default.get('backorder_id'):
823 default['backorder_id'] = False
824 default['pack_operation_ids'] = []
825 default['date_done'] = False
826 return super(stock_picking, self).copy(cr, uid, id, default, context)
828 def do_print_picking(self, cr, uid, ids, context=None):
829 '''This function prints the picking list'''
830 context = context or {}
831 context['active_ids'] = ids
832 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
835 def action_confirm(self, cr, uid, ids, context=None):
837 todo_force_assign = []
838 for picking in self.browse(cr, uid, ids, context=context):
839 if picking.location_id.usage in ('supplier', 'inventory', 'production'):
840 todo_force_assign.append(picking.id)
841 for r in picking.move_lines:
842 if r.state == 'draft':
845 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
847 if todo_force_assign:
848 self.force_assign(cr, uid, todo_force_assign, context=context)
851 def action_assign(self, cr, uid, ids, context=None):
852 """ Check availability of picking moves.
853 This has the effect of changing the state and reserve quants on available moves, and may
854 also impact the state of the picking as it is computed based on move's states.
857 for pick in self.browse(cr, uid, ids, context=context):
858 if pick.state == 'draft':
859 self.action_confirm(cr, uid, [pick.id], context=context)
861 #skip the moves that don't need to be checked
862 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
864 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
865 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
868 def force_assign(self, cr, uid, ids, context=None):
869 """ Changes state of picking to available if moves are confirmed or waiting.
872 for pick in self.browse(cr, uid, ids, context=context):
873 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
874 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
875 #pack_operation might have changed and need to be recomputed
876 self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context)
879 def action_cancel(self, cr, uid, ids, context=None):
880 for pick in self.browse(cr, uid, ids, context=context):
881 ids2 = [move.id for move in pick.move_lines]
882 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
885 def action_done(self, cr, uid, ids, context=None):
886 """Changes picking state to done by processing the Stock Moves of the Picking
888 Normally that happens when the button "Done" is pressed on a Picking view.
891 for pick in self.browse(cr, uid, ids, context=context):
893 for move in pick.move_lines:
894 if move.state == 'draft':
895 todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
896 elif move.state in ('assigned', 'confirmed'):
899 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
902 def unlink(self, cr, uid, ids, context=None):
903 #on picking deletion, cancel its move then unlink them too
904 move_obj = self.pool.get('stock.move')
905 context = context or {}
906 for pick in self.browse(cr, uid, ids, context=context):
907 move_ids = [move.id for move in pick.move_lines]
908 move_obj.action_cancel(cr, uid, move_ids, context=context)
909 move_obj.unlink(cr, uid, move_ids, context=context)
910 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
912 def write(self, cr, uid, ids, vals, context=None):
913 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
914 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
915 if 'move_lines' in vals or 'pack_operation_ids' in vals:
916 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
919 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
920 """ 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.
922 if not backorder_moves:
923 backorder_moves = picking.move_lines
924 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
925 if 'do_only_split' in context and context['do_only_split']:
926 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
928 if backorder_move_ids:
929 backorder_id = self.copy(cr, uid, picking.id, {
932 'pack_operation_ids': [],
933 'backorder_id': picking.id,
935 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (picking.name), context=context)
936 move_obj = self.pool.get("stock.move")
937 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
939 self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
940 self.action_confirm(cr, uid, [backorder_id], context=context)
944 def recheck_availability(self, cr, uid, picking_ids, context=None):
945 self.action_assign(cr, uid, picking_ids, context=context)
946 self.do_prepare_partial(cr, uid, picking_ids, context=context)
948 def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
949 """This method searches for the higher level packages that can be moved as a single operation, given a list of quants
950 to move and their suggested destination, and returns the list of matching packages.
952 # Try to find as much as possible top-level packages that can be moved
953 pack_obj = self.pool.get("stock.quant.package")
954 quant_obj = self.pool.get("stock.quant")
955 top_lvl_packages = set()
956 quants_to_compare = quants_suggested_locations.keys()
957 for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
961 pack_destination = False
963 pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
965 for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
966 # If the quant is not in the quants to compare and not in the common location
967 if not quant in quants_to_compare:
971 #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)
972 if not pack_destination:
973 pack_destination = quants_suggested_locations[quant]
974 elif pack_destination != quants_suggested_locations[quant]:
978 good_pack = test_pack
979 if test_pack.parent_id:
980 test_pack = test_pack.parent_id
982 #stop the loop when there's no parent package anymore
985 #stop the loop when the package test_pack is not totally reserved for moves of this picking
986 #(some quants may be reserved for other picking or not reserved at all)
989 top_lvl_packages.add(good_pack)
990 return list(top_lvl_packages)
992 def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
993 """ returns a list of dict, ready to be used in create() of stock.pack.operation.
995 :param picking: browse record (stock.picking)
996 :param quants: browse record list (stock.quant). List of quants associated to the picking
997 :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
999 def _picking_putaway_apply(product):
1001 # Search putaway strategy
1002 if product_putaway_strats.get(product.id):
1003 location = product_putaway_strats[product.id]
1005 location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
1006 product_putaway_strats[product.id] = location
1007 return location or picking.location_dest_id.id
1009 pack_obj = self.pool.get("stock.quant.package")
1010 quant_obj = self.pool.get("stock.quant")
1013 #for each quant of the picking, find the suggested location
1014 quants_suggested_locations = {}
1015 product_putaway_strats = {}
1016 for quant in quants:
1019 suggested_location_id = _picking_putaway_apply(quant.product_id)
1020 quants_suggested_locations[quant] = suggested_location_id
1022 #find the packages we can movei as a whole
1023 top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
1024 # and then create pack operations for the top-level packages found
1025 for pack in top_lvl_packages:
1026 pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
1027 pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
1029 'picking_id': picking.id,
1030 'package_id': pack.id,
1032 'location_id': pack.location_id.id,
1033 'location_dest_id': quants_suggested_locations[pack_quants[0]],
1035 #remove the quants inside the package so that they are excluded from the rest of the computation
1036 for quant in pack_quants:
1037 del quants_suggested_locations[quant]
1039 # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
1040 for quant, dest_location_id in quants_suggested_locations.items():
1041 key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
1042 if qtys_grouped.get(key):
1043 qtys_grouped[key] += quant.qty
1045 qtys_grouped[key] = quant.qty
1047 # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
1048 for product, qty in forced_qties.items():
1051 suggested_location_id = _picking_putaway_apply(product)
1052 key = (product.id, False, False, False, picking.location_id.id, suggested_location_id)
1053 if qtys_grouped.get(key):
1054 qtys_grouped[key] += qty
1056 qtys_grouped[key] = qty
1058 # Create the necessary operations for the grouped quants and remaining qtys
1059 for key, qty in qtys_grouped.items():
1061 'picking_id': picking.id,
1063 'product_id': key[0],
1064 'package_id': key[1],
1067 'location_id': key[4],
1068 'location_dest_id': key[5],
1069 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id,
1073 def open_barcode_interface(self, cr, uid, picking_ids, context=None):
1074 final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0])
1075 return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
1077 def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
1078 self.do_prepare_partial(cr, uid, picking_ids, context=context)
1079 return self.open_barcode_interface(cr, uid, picking_ids, context=context)
1081 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
1082 context = context or {}
1083 pack_operation_obj = self.pool.get('stock.pack.operation')
1084 #used to avoid recomputing the remaining quantities at each new pack operation created
1085 ctx = context.copy()
1086 ctx['no_recompute'] = True
1088 #get list of existing operations and delete them
1089 existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
1090 if existing_package_ids:
1091 pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
1092 for picking in self.browse(cr, uid, picking_ids, context=context):
1093 forced_qties = {} # Quantity remaining after calculating reserved quants
1095 #Calculate packages, reserved quants, qtys of this picking's moves
1096 for move in picking.move_lines:
1097 if move.state not in ('assigned', 'confirmed'):
1099 move_quants = move.reserved_quant_ids
1100 picking_quants += move_quants
1101 forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
1102 #if we used force_assign() on the move, or if the move is incomming, forced_qty > 0
1104 if forced_qties.get(move.product_id):
1105 forced_qties[move.product_id] += forced_qty
1107 forced_qties[move.product_id] = forced_qty
1108 for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
1109 pack_operation_obj.create(cr, uid, vals, context=ctx)
1110 #recompute the remaining quantities all at once
1111 self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
1112 self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context)
1114 def do_unreserve(self, cr, uid, picking_ids, context=None):
1116 Will remove all quants for picking in picking_ids
1118 moves_to_unreserve = []
1119 pack_line_to_unreserve = []
1120 for picking in self.browse(cr, uid, picking_ids, context=context):
1121 moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
1122 pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
1123 if moves_to_unreserve:
1124 if pack_line_to_unreserve:
1125 self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
1126 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
1128 def recompute_remaining_qty(self, cr, uid, picking, context=None):
1129 def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
1130 move_dict = prod2move_ids[product_id][index]
1131 qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
1132 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)
1133 if move_dict['remaining_qty'] == qty_on_link:
1134 prod2move_ids[product_id].pop(index)
1136 move_dict['remaining_qty'] -= qty_on_link
1139 def _create_link_for_quant(operation_id, quant, qty):
1140 """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
1141 if not quant.reservation_id.id:
1142 return _create_link_for_product(operation_id, quant.product_id.id, qty)
1144 for i in range(0, len(prod2move_ids[quant.product_id.id])):
1145 if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
1147 qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
1151 def _create_link_for_product(operation_id, product_id, qty):
1152 '''method that creates the link between a given operation and move(s) of given product, for the given quantity.
1153 Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
1155 if prod2move_ids.get(product_id):
1156 while prod2move_ids[product_id] and qty_to_assign > 0:
1157 qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
1158 qty_to_assign -= qty_on_link
1159 return qty_to_assign == 0
1161 uom_obj = self.pool.get('product.uom')
1162 package_obj = self.pool.get('stock.quant.package')
1163 quant_obj = self.pool.get('stock.quant')
1164 quants_in_package_done = set()
1167 #make a dictionary giving for each product, the moves and related quantity that can be used in operation links
1168 for move in picking.move_lines:
1169 if not prod2move_ids.get(move.product_id.id):
1170 prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
1172 prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
1174 need_rereserve = False
1175 #sort the operations in order to give higher priority to those with a package, then a serial number
1176 operations = picking.pack_operation_ids
1177 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))
1178 #delete existing operations to start again from scratch
1179 cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),))
1181 #1) first, try to create links when quants can be identified without any doubt
1182 for ops in operations:
1183 #for each operation, create the links with the stock move by seeking on the matching reserved quants,
1184 #and deffer the operation if there is some ambiguity on the move to select
1185 if ops.package_id and not ops.product_id:
1187 quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
1188 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1189 remaining_qty_on_quant = quant.qty
1190 if quant.reservation_id:
1191 #avoid quants being counted twice
1192 quants_in_package_done.add(quant.id)
1193 qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
1194 remaining_qty_on_quant -= qty_on_link
1195 if remaining_qty_on_quant:
1196 still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
1197 need_rereserve = True
1198 elif ops.product_id.id:
1199 #Check moves with same product
1200 qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
1201 for move_dict in prod2move_ids.get(ops.product_id.id, []):
1202 move = move_dict['move']
1203 for quant in move.reserved_quant_ids:
1204 if not qty_to_assign > 0:
1206 if quant.id in quants_in_package_done:
1209 #check if the quant is matching the operation details
1211 flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id]), ('id', '=', quant.package_id.id)], context=context)) or False
1213 flag = not quant.package_id.id
1214 flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
1215 flag = flag and (ops.owner_id.id == quant.owner_id.id)
1217 max_qty_on_link = min(quant.qty, qty_to_assign)
1218 qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
1219 qty_to_assign -= qty_on_link
1220 if qty_to_assign > 0:
1221 #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
1222 #all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
1223 still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
1224 need_rereserve = True
1226 #2) then, process the remaining part
1227 all_op_processed = True
1228 for ops, product_id, remaining_qty in still_to_do:
1229 all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty)
1230 return (need_rereserve, all_op_processed)
1232 def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
1233 need_rereserve = False
1234 all_op_processed = True
1235 if picking.pack_operation_ids:
1236 need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
1237 return need_rereserve, all_op_processed
1239 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
1240 for picking in self.browse(cr, uid, picking_ids, context=context):
1241 if picking.pack_operation_ids:
1242 self.recompute_remaining_qty(cr, uid, picking, context=context)
1244 def _create_extra_moves(self, cr, uid, picking, context=None):
1245 '''This function creates move lines on a picking, at the time of do_transfer, based on
1246 unexpected product transfers (or exceeding quantities) found in the pack operations.
1248 move_obj = self.pool.get('stock.move')
1249 operation_obj = self.pool.get('stock.pack.operation')
1251 for op in picking.pack_operation_ids:
1252 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1253 if remaining_qty > 0:
1254 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1256 'picking_id': picking.id,
1257 'location_id': picking.location_id.id,
1258 'location_dest_id': picking.location_dest_id.id,
1259 'product_id': product_id,
1260 'product_uom': product.uom_id.id,
1261 'product_uom_qty': remaining_qty,
1262 'name': _('Extra Move: ') + product.name,
1265 moves.append(move_obj.create(cr, uid, vals, context=context))
1267 move_obj.action_confirm(cr, uid, moves, context=context)
1270 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1271 """ Unreserve quants then try to reassign quants."""
1272 stock_move_obj = self.pool.get('stock.move')
1274 self.do_unreserve(cr, uid, [picking.id], context=context)
1275 self.action_assign(cr, uid, [picking.id], context=context)
1277 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1278 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1280 def do_transfer(self, cr, uid, picking_ids, context=None):
1282 If no pack operation, we do simple action_done of the picking
1283 Otherwise, do the pack operations
1287 stock_move_obj = self.pool.get('stock.move')
1288 for picking in self.browse(cr, uid, picking_ids, context=context):
1289 if not picking.pack_operation_ids:
1290 self.action_done(cr, uid, [picking.id], context=context)
1293 need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
1294 #create extra moves in the picking (unexpected product moves coming from pack operations)
1296 if not all_op_processed:
1297 todo_move_ids += self._create_extra_moves(cr, uid, picking, context=context)
1300 #split move lines eventually
1302 toassign_move_ids = []
1303 for move in picking.move_lines:
1304 remaining_qty = move.remaining_qty
1305 if move.state in ('done', 'cancel'):
1306 #ignore stock moves cancelled or already done
1308 elif move.state == 'draft':
1309 toassign_move_ids.append(move.id)
1310 if remaining_qty == 0:
1311 if move.state in ('draft', 'assigned', 'confirmed'):
1312 todo_move_ids.append(move.id)
1313 elif remaining_qty > 0 and remaining_qty < move.product_qty:
1314 new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
1315 todo_move_ids.append(move.id)
1316 #Assign move as it was assigned before
1317 toassign_move_ids.append(new_move)
1318 if (need_rereserve or not all_op_processed) and not picking.location_id.usage in ("supplier", "production", "inventory"):
1319 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1320 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1321 if todo_move_ids and not context.get('do_only_split'):
1322 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1323 elif context.get('do_only_split'):
1324 context.update({'split': todo_move_ids})
1326 self._create_backorder(cr, uid, picking, context=context)
1327 if toassign_move_ids:
1328 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1331 def do_split(self, cr, uid, picking_ids, context=None):
1332 """ just split the picking (create a backorder) without making it 'done' """
1335 ctx = context.copy()
1336 ctx['do_only_split'] = True
1337 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1339 def get_next_picking_for_ui(self, cr, uid, context=None):
1340 """ returns the next pickings to process. Used in the barcode scanner UI"""
1343 domain = [('state', 'in', ('assigned', 'partially_available'))]
1344 if context.get('default_picking_type_id'):
1345 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1346 return self.search(cr, uid, domain, context=context)
1348 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1349 """ called when button 'done' is pushed in the barcode scanner UI """
1350 #write qty_done into field product_qty for every package_operation before doing the transfer
1351 pack_op_obj = self.pool.get('stock.pack.operation')
1352 for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
1353 pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
1354 self.do_transfer(cr, uid, [picking_id], context=context)
1355 #return id of next picking to work on
1356 return self.get_next_picking_for_ui(cr, uid, context=context)
1358 def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
1359 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1360 Used in the barcode scanner UI and the normal interface as well.
1361 operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
1362 if operation_filter_ids == None:
1363 operation_filter_ids = []
1364 stock_operation_obj = self.pool.get('stock.pack.operation')
1365 package_obj = self.pool.get('stock.quant.package')
1366 stock_move_obj = self.pool.get('stock.move')
1367 for picking_id in picking_ids:
1368 operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
1369 if operation_filter_ids != []:
1370 operation_search_domain.append(('id', 'in', operation_filter_ids))
1371 operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
1372 pack_operation_ids = []
1374 for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
1375 #If we haven't done all qty in operation, we have to split into 2 operation
1377 if (operation.qty_done < operation.product_qty):
1378 new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
1379 stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0, 'lot_id': False}, context=context)
1380 op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
1381 pack_operation_ids.append(op.id)
1382 for record in op.linked_move_operation_ids:
1383 stock_move_obj.check_tracking(cr, uid, record.move_id, op.package_id.id or op.lot_id.id, context=context)
1384 package_id = package_obj.create(cr, uid, {}, context=context)
1385 stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
1388 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
1389 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)
1391 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
1392 '''This function is called each time there barcode scanner reads an input'''
1393 lot_obj = self.pool.get('stock.production.lot')
1394 package_obj = self.pool.get('stock.quant.package')
1395 product_obj = self.pool.get('product.product')
1396 stock_operation_obj = self.pool.get('stock.pack.operation')
1397 stock_location_obj = self.pool.get('stock.location')
1398 answer = {'filter_loc': False, 'operation_id': False}
1399 #check if the barcode correspond to a location
1400 matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context)
1401 if matching_location_ids:
1402 #if we have a location, return immediatly with the location name
1403 location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
1404 answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
1405 answer['filter_loc_id'] = matching_location_ids[0]
1407 #check if the barcode correspond to a product
1408 matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context)
1409 if matching_product_ids:
1410 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1411 answer['operation_id'] = op_id
1413 #check if the barcode correspond to a lot
1414 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1415 if matching_lot_ids:
1416 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1417 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)
1418 answer['operation_id'] = op_id
1420 #check if the barcode correspond to a package
1421 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1422 if matching_package_ids:
1423 op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1424 answer['operation_id'] = op_id
1429 class stock_production_lot(osv.osv):
1430 _name = 'stock.production.lot'
1431 _inherit = ['mail.thread']
1432 _description = 'Lot/Serial'
1434 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1435 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1436 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1437 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
1438 'create_date': fields.datetime('Creation Date'),
1441 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1442 'product_id': lambda x, y, z, c: c.get('product_id', False),
1444 _sql_constraints = [
1445 ('name_ref_uniq', 'unique (name, ref, product_id)', 'The combination of serial number, internal reference and product must be unique !'),
1448 def action_traceability(self, cr, uid, ids, context=None):
1449 """ It traces the information of lots
1450 @param self: The object pointer.
1451 @param cr: A database cursor
1452 @param uid: ID of the user currently logged in
1453 @param ids: List of IDs selected
1454 @param context: A standard dictionary
1455 @return: A dictionary of values
1457 quant_obj = self.pool.get("stock.quant")
1458 quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1460 for quant in quant_obj.browse(cr, uid, quants, context=context):
1461 moves |= {move.id for move in quant.history_ids}
1464 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
1465 'name': _('Traceability'),
1466 'view_mode': 'tree,form',
1467 'view_type': 'form',
1468 'context': {'tree_view_ref': 'stock.view_move_tree'},
1469 'res_model': 'stock.move',
1470 'type': 'ir.actions.act_window',
1475 # ----------------------------------------------------
1477 # ----------------------------------------------------
1479 class stock_move(osv.osv):
1480 _name = "stock.move"
1481 _description = "Stock Move"
1482 _order = 'date_expected desc, id'
1485 def get_price_unit(self, cr, uid, move, context=None):
1486 """ Returns the unit price to store on the quant """
1487 return move.price_unit or move.product_id.standard_price
1489 def name_get(self, cr, uid, ids, context=None):
1491 for line in self.browse(cr, uid, ids, context=context):
1492 name = line.location_id.name + ' > ' + line.location_dest_id.name
1493 if line.product_id.code:
1494 name = line.product_id.code + ': ' + name
1495 if line.picking_id.origin:
1496 name = line.picking_id.origin + '/ ' + name
1497 res.append((line.id, name))
1500 def create(self, cr, uid, vals, context=None):
1501 if vals.get('product_id') and not vals.get('price_unit'):
1502 prod_obj = self.pool.get('product.product')
1503 vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price
1504 return super(stock_move, self).create(cr, uid, vals, context=context)
1506 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1507 uom_obj = self.pool.get('product.uom')
1509 for m in self.browse(cr, uid, ids, context=context):
1510 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)
1513 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1514 uom_obj = self.pool.get('product.uom')
1516 for move in self.browse(cr, uid, ids, context=context):
1517 qty = move.product_qty
1518 for record in move.linked_move_operation_ids:
1520 #converting the remaining quantity in the move UoM
1521 res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context)
1524 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1525 res = dict.fromkeys(ids, False)
1526 for move in self.browse(cr, uid, ids, context=context):
1527 if move.state == 'done':
1528 res[move.id] = [q.lot_id.id for q in move.quant_ids if q.lot_id]
1530 res[move.id] = [q.lot_id.id for q in move.reserved_quant_ids if q.lot_id]
1533 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1534 quant_obj = self.pool.get('stock.quant')
1535 res = dict.fromkeys(ids, False)
1536 for move in self.browse(cr, uid, ids, context=context):
1537 if move.state == 'done':
1538 res[move.id] = move.product_qty
1540 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1541 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1543 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1544 availability += quant.qty
1545 res[move.id] = min(move.product_qty, availability)
1548 def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
1549 settings_obj = self.pool.get('stock.config.settings')
1550 uom_obj = self.pool.get('product.uom')
1551 res = dict.fromkeys(ids, '')
1552 for move in self.browse(cr, uid, ids, context=context):
1553 if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
1554 res[move.id] = '' # 'not applicable' or 'n/a' could work too
1556 total_available = min(move.product_qty, move.reserved_availability + move.availability)
1557 total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
1558 info = str(total_available)
1559 #look in the settings if we need to display the UoM name or not
1560 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1562 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1563 if stock_settings.group_uom:
1564 info += ' ' + move.product_uom.name
1565 if move.reserved_availability:
1566 if move.reserved_availability != total_available:
1567 #some of the available quantity is assigned and some are available but not reserved
1568 reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
1569 info += _(' (%s reserved)') % str(reserved_available)
1571 #all available quantity is assigned
1572 info += _(' (reserved)')
1576 def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
1577 res = dict.fromkeys(ids, 0)
1578 for move in self.browse(cr, uid, ids, context=context):
1579 res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
1582 def _get_move(self, cr, uid, ids, context=None):
1584 for quant in self.browse(cr, uid, ids, context=context):
1585 if quant.reservation_id:
1586 res.add(quant.reservation_id.id)
1589 def _get_move_ids(self, cr, uid, ids, context=None):
1591 for picking in self.browse(cr, uid, ids, context=context):
1592 res += [x.id for x in picking.move_lines]
1595 def _get_moves_from_prod(self, cr, uid, ids, context=None):
1597 return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context)
1600 def _set_product_qty(self, cr, uid, id, field, value, arg, context=None):
1601 """ The meaning of product_qty field changed lately and is now a functional field computing the quantity
1602 in the default product UoM. This code has been added to raise an error if a write is made given a value
1603 for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
1606 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`.'))
1609 'name': fields.char('Description', required=True, select=True),
1610 'priority': fields.selection(procurement.PROCUREMENT_PRIORITIES, 'Priority'),
1611 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1612 '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)]}),
1613 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1614 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1615 'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, _type='float', store={
1616 'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_id', 'product_uom_qty', 'product_uom'], 20),
1617 'product.product': (_get_moves_from_prod, ['uom_id'], 20),
1618 }, string='Quantity',
1619 digits_compute=dp.get_precision('Product Unit of Measure'),
1620 help='Quantity in the default UoM of the product'),
1621 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1622 required=True, states={'done': [('readonly', True)]},
1623 help="This is the quantity of products from an inventory "
1624 "point of view. For moves in the state 'done', this is the "
1625 "quantity of products that were actually moved. For other "
1626 "moves, this is the quantity of product that is planned to "
1627 "be moved. Lowering this quantity does not generate a "
1628 "backorder. Changing this quantity on assigned moves affects "
1629 "the product reservation, and should be done with care."
1631 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1632 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1633 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1635 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1637 '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."),
1638 '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."),
1640 '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"),
1643 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1644 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1646 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1647 'note': fields.text('Notes'),
1648 'state': fields.selection([('draft', 'New'),
1649 ('cancel', 'Cancelled'),
1650 ('waiting', 'Waiting Another Move'),
1651 ('confirmed', 'Waiting Availability'),
1652 ('assigned', 'Available'),
1654 ], 'Status', readonly=True, select=True,
1655 help= "* New: When the stock move is created and not yet confirmed.\n"\
1656 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1657 "* 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"\
1658 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1659 "* Done: When the shipment is processed, the state is \'Done\'."),
1660 'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved"),
1661 '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
1663 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1664 '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"),
1665 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1666 'origin': fields.char("Source"),
1667 'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True,
1668 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."""),
1670 # used for colors in tree views:
1671 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1673 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1674 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1675 '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'),
1676 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1677 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1678 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1679 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1680 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1681 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1682 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1683 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1684 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1685 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.production.lot', string='Lots'),
1686 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1687 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1688 'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
1689 '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'),
1690 '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'),
1691 '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'"),
1692 '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'"),
1693 '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"),
1694 '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)."),
1697 def _default_location_destination(self, cr, uid, context=None):
1698 context = context or {}
1699 if context.get('default_picking_type_id', False):
1700 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1701 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1704 def _default_location_source(self, cr, uid, context=None):
1705 context = context or {}
1706 if context.get('default_picking_type_id', False):
1707 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1708 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1711 def _default_destination_address(self, cr, uid, context=None):
1712 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1713 return user.company_id.partner_id.id
1716 'location_id': _default_location_source,
1717 'location_dest_id': _default_location_destination,
1718 'partner_id': _default_destination_address,
1721 'product_uom_qty': 1.0,
1723 'date': fields.datetime.now,
1724 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1725 'date_expected': fields.datetime.now,
1726 'procure_method': 'make_to_stock',
1730 def _check_uom(self, cr, uid, ids, context=None):
1731 for move in self.browse(cr, uid, ids, context=context):
1732 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1738 '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.',
1742 def copy_data(self, cr, uid, id, default=None, context=None):
1745 default = default.copy()
1746 default['move_orig_ids'] = []
1747 default['quant_ids'] = []
1748 default['move_dest_id'] = False
1749 default['reserved_quant_ids'] = []
1750 default['returned_move_ids'] = []
1751 default['linked_move_operation_ids'] = []
1752 default['partially_available'] = False
1753 if not default.get('origin_returned_move_id'):
1754 default['origin_returned_move_id'] = False
1755 default['state'] = 'draft'
1756 return super(stock_move, self).copy_data(cr, uid, id, default, context)
1758 def do_unreserve(self, cr, uid, move_ids, context=None):
1759 quant_obj = self.pool.get("stock.quant")
1760 for move in self.browse(cr, uid, move_ids, context=context):
1761 if move.state in ('done', 'cancel'):
1762 raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
1763 quant_obj.quants_unreserve(cr, uid, move, context=context)
1764 if self.find_move_ancestors(cr, uid, move, context=context):
1765 self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context)
1767 self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
1769 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1770 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1771 group_id = move.group_id and move.group_id.id or False
1773 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1774 group_id = move.rule_id.group_id.id
1775 elif move.rule_id.group_propagation_option == 'none':
1778 'name': move.rule_id and move.rule_id.name or "/",
1780 'company_id': move.company_id and move.company_id.id or False,
1781 'date_planned': move.date,
1782 'product_id': move.product_id.id,
1783 'product_qty': move.product_qty,
1784 'product_uom': move.product_uom.id,
1785 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1786 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1787 'location_id': move.location_id.id,
1788 'move_dest_id': move.id,
1789 'group_id': group_id,
1790 'route_ids': [(4, x.id) for x in move.route_ids],
1791 'warehouse_id': move.warehouse_id.id or (move.picking_type_id and move.picking_type_id.warehouse_id.id or False),
1792 'priority': move.priority,
1795 def _push_apply(self, cr, uid, moves, context=None):
1796 push_obj = self.pool.get("stock.location.path")
1798 #1) if the move is already chained, there is no need to check push rules
1799 #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
1800 # to receive goods without triggering the push rules again (which would duplicate chained operations)
1801 if not move.move_dest_id and not move.origin_returned_move_id:
1802 domain = [('location_from_id', '=', move.location_dest_id.id)]
1803 #priority goes to the route defined on the product and product category
1804 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1805 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1807 #then we search on the warehouse if a rule can apply
1809 if move.warehouse_id:
1810 wh_route_ids = [x.id for x in move.warehouse_id.route_ids]
1811 elif move.picking_type_id and move.picking_type_id.warehouse_id:
1812 wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids]
1814 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context)
1816 #if no specialized push rule has been found yet, we try to find a general one
1817 rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context)
1819 rule = push_obj.browse(cr, uid, rules[0], context=context)
1820 push_obj._apply(cr, uid, rule, move, context=context)
1823 def _create_procurement(self, cr, uid, move, context=None):
1824 """ This will create a procurement order """
1825 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1827 def write(self, cr, uid, ids, vals, context=None):
1830 if isinstance(ids, (int, long)):
1832 # Check that we do not modify a stock.move which is done
1833 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1834 for move in self.browse(cr, uid, ids, context=context):
1835 if move.state == 'done':
1836 if frozen_fields.intersection(vals):
1837 raise osv.except_osv(_('Operation Forbidden!'),
1838 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1839 propagated_changes_dict = {}
1840 #propagation of quantity change
1841 if vals.get('product_uom_qty'):
1842 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1843 if vals.get('product_uom_id'):
1844 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1845 #propagation of expected date:
1846 propagated_date_field = False
1847 if vals.get('date_expected'):
1848 #propagate any manual change of the expected date
1849 propagated_date_field = 'date_expected'
1850 elif (vals.get('state', '') == 'done' and vals.get('date')):
1851 #propagate also any delta observed when setting the move as done
1852 propagated_date_field = 'date'
1854 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1855 #any propagation is (maybe) needed
1856 for move in self.browse(cr, uid, ids, context=context):
1857 if move.move_dest_id and move.propagate:
1858 if 'date_expected' in propagated_changes_dict:
1859 propagated_changes_dict.pop('date_expected')
1860 if propagated_date_field:
1861 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1862 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1863 delta = new_date - current_date
1864 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1865 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1866 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1867 propagated_changes_dict['date_expected'] = new_move_date
1868 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1869 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1870 if propagated_changes_dict:
1871 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1872 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1874 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1875 """ On change of product quantity finds UoM and UoS quantities
1876 @param product_id: Product id
1877 @param product_qty: Changed Quantity of product
1878 @param product_uom: Unit of measure of product
1879 @param product_uos: Unit of sale of product
1880 @return: Dictionary of values
1883 'product_uos_qty': 0.00
1887 if (not product_id) or (product_qty <= 0.0):
1888 result['product_qty'] = 0.0
1889 return {'value': result}
1891 product_obj = self.pool.get('product.product')
1892 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1894 # Warn if the quantity was decreased
1896 for move in self.read(cr, uid, ids, ['product_qty']):
1897 if product_qty < move['product_qty']:
1899 'title': _('Information'),
1900 'message': _("By changing this quantity here, you accept the "
1901 "new quantity as complete: OpenERP will not "
1902 "automatically generate a back order.")})
1905 if product_uos and product_uom and (product_uom != product_uos):
1906 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1908 result['product_uos_qty'] = product_qty
1910 return {'value': result, 'warning': warning}
1912 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1913 product_uos, product_uom):
1914 """ On change of product quantity finds UoM and UoS quantities
1915 @param product_id: Product id
1916 @param product_uos_qty: Changed UoS Quantity of product
1917 @param product_uom: Unit of measure of product
1918 @param product_uos: Unit of sale of product
1919 @return: Dictionary of values
1922 'product_uom_qty': 0.00
1925 if (not product_id) or (product_uos_qty <= 0.0):
1926 result['product_uos_qty'] = 0.0
1927 return {'value': result}
1929 product_obj = self.pool.get('product.product')
1930 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1932 # No warning if the quantity was decreased to avoid double warnings:
1933 # The clients should call onchange_quantity too anyway
1935 if product_uos and product_uom and (product_uom != product_uos):
1936 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1938 result['product_uom_qty'] = product_uos_qty
1939 return {'value': result}
1941 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1942 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1943 @param prod_id: Changed Product id
1944 @param loc_id: Source location id
1945 @param loc_dest_id: Destination location id
1946 @param partner_id: Address id of partner
1947 @return: Dictionary of values
1951 user = self.pool.get('res.users').browse(cr, uid, uid)
1952 lang = user and user.lang or False
1954 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1956 lang = addr_rec and addr_rec.lang or False
1957 ctx = {'lang': lang}
1959 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1960 uos_id = product.uos_id and product.uos_id.id or False
1962 'product_uom': product.uom_id.id,
1963 'product_uos': uos_id,
1964 'product_uom_qty': 1.00,
1965 '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'],
1968 result['name'] = product.partner_ref
1970 result['location_id'] = loc_id
1972 result['location_dest_id'] = loc_dest_id
1973 return {'value': result}
1975 def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
1976 """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
1977 (and company). Those attributes are also given as parameters.
1979 pick_obj = self.pool.get("stock.picking")
1980 picks = pick_obj.search(cr, uid, [
1981 ('group_id', '=', procurement_group),
1982 ('location_id', '=', location_from),
1983 ('location_dest_id', '=', location_to),
1984 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1988 move = self.browse(cr, uid, move_ids, context=context)[0]
1990 'origin': move.origin,
1991 'company_id': move.company_id and move.company_id.id or False,
1992 'move_type': move.group_id and move.group_id.move_type or 'direct',
1993 'partner_id': move.partner_id.id or False,
1994 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1996 pick = pick_obj.create(cr, uid, values, context=context)
1997 return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
1999 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
2000 """ On change of Scheduled Date gives a Move date.
2001 @param date_expected: Scheduled Date
2002 @param date: Move Date
2005 if not date_expected:
2006 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
2007 return {'value': {'date': date_expected}}
2010 def action_confirm(self, cr, uid, ids, context=None):
2011 """ Confirms stock move or put it in waiting if it's linked to another move.
2012 @return: List of ids.
2014 if isinstance(ids, (int, long)):
2021 for move in self.browse(cr, uid, ids, context=context):
2023 #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)
2024 if move.move_orig_ids:
2026 #if the move is split and some of the ancestor was preceeded, then it's waiting as well
2027 elif move.split_from:
2028 move2 = move.split_from
2029 while move2 and state != 'waiting':
2030 if move2.move_orig_ids:
2032 move2 = move2.split_from
2033 states[state].append(move.id)
2035 if not move.picking_id and move.picking_type_id:
2036 key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
2037 if key not in to_assign:
2039 to_assign[key].append(move.id)
2041 for move in self.browse(cr, uid, states['confirmed'], context=context):
2042 if move.procure_method == 'make_to_order':
2043 self._create_procurement(cr, uid, move, context=context)
2044 states['waiting'].append(move.id)
2045 states['confirmed'].remove(move.id)
2047 for state, write_ids in states.items():
2049 self.write(cr, uid, write_ids, {'state': state})
2050 #assign picking in batch for all confirmed move that share the same details
2051 for key, move_ids in to_assign.items():
2052 procurement_group, location_from, location_to = key
2053 self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
2054 moves = self.browse(cr, uid, ids, context=context)
2055 self._push_apply(cr, uid, moves, context=context)
2058 def force_assign(self, cr, uid, ids, context=None):
2059 """ Changes the state to assigned.
2062 return self.write(cr, uid, ids, {'state': 'assigned'}, context=context)
2064 def check_tracking(self, cr, uid, move, lot_id, context=None):
2065 """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
2068 if move.product_id.track_all and not move.location_dest_id.usage == 'inventory':
2070 elif move.product_id.track_incoming and move.location_id.usage in ('supplier', 'transit', 'inventory') and move.location_dest_id.usage == 'internal':
2072 elif move.product_id.track_outgoing and move.location_dest_id.usage in ('customer', 'transit') and move.location_id.usage == 'internal':
2074 if check and not lot_id:
2075 raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name))
2077 def action_assign(self, cr, uid, ids, context=None):
2078 """ Checks the product type and accordingly writes the state.
2080 context = context or {}
2081 quant_obj = self.pool.get("stock.quant")
2082 to_assign_moves = []
2086 for move in self.browse(cr, uid, ids, context=context):
2087 if move.state not in ('confirmed', 'waiting', 'assigned'):
2089 if move.location_id.usage in ('supplier', 'inventory', 'production'):
2090 to_assign_moves.append(move.id)
2091 #in case the move is returned, we want to try to find quants before forcing the assignment
2092 if not move.origin_returned_move_id:
2094 if move.product_id.type == 'consu':
2095 to_assign_moves.append(move.id)
2098 todo_moves.append(move)
2100 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
2101 main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
2103 #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
2104 ancestors = self.find_move_ancestors(cr, uid, move, context=context)
2105 if move.state == 'waiting' and not ancestors:
2106 #if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock
2107 main_domain[move.id] += [('id', '=', False)]
2109 main_domain[move.id] += [('history_ids', 'in', ancestors)]
2111 #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
2112 if move.origin_returned_move_id:
2113 main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
2114 for link in move.linked_move_operation_ids:
2115 operations.add(link.operation_id)
2116 # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
2117 operations = list(operations)
2118 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))
2119 for ops in operations:
2120 #first try to find quants based on specific domains given by linked operations
2121 for record in ops.linked_move_operation_ids:
2122 move = record.move_id
2123 if move.id in main_domain:
2124 domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2127 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)
2128 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
2129 for move in todo_moves:
2131 #then if the move isn't totally assigned, try to find quants without any specific domain
2132 if move.state != 'assigned':
2133 qty_already_assigned = move.reserved_availability
2134 qty = move.product_qty - qty_already_assigned
2135 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)
2136 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
2138 #force assignation of consumable products and incoming from supplier/inventory/production
2140 self.force_assign(cr, uid, to_assign_moves, context=context)
2142 def action_cancel(self, cr, uid, ids, context=None):
2143 """ Cancels the moves and if all moves are cancelled it cancels the picking.
2146 procurement_obj = self.pool.get('procurement.order')
2147 context = context or {}
2148 for move in self.browse(cr, uid, ids, context=context):
2149 if move.state == 'done':
2150 raise osv.except_osv(_('Operation Forbidden!'),
2151 _('You cannot cancel a stock move that has been set to \'Done\'.'))
2152 if move.reserved_quant_ids:
2153 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
2154 if context.get('cancel_procurement'):
2156 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
2157 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
2158 elif move.move_dest_id:
2159 #cancel chained moves
2161 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
2162 # If we have a long chain of moves to be cancelled, it is easier for the user to handle
2163 # only the last procurement which will go into exception, instead of all procurements
2164 # along the chain going into exception. We need to check if there are no split moves not cancelled however
2165 if move.procurement_id:
2166 proc = move.procurement_id
2167 if all([x.state == 'cancel' for x in proc.move_ids if x.id != move.id]):
2168 procurement_obj.write(cr, uid, [proc.id], {'state': 'cancel'})
2170 elif move.move_dest_id.state == 'waiting':
2171 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2172 return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2174 def _check_package_from_moves(self, cr, uid, ids, context=None):
2175 pack_obj = self.pool.get("stock.quant.package")
2177 for move in self.browse(cr, uid, ids, context=context):
2178 packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0])
2179 return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
2181 def find_move_ancestors(self, cr, uid, move, context=None):
2182 '''Find the first level ancestors of given move '''
2186 ancestors += [x.id for x in move2.move_orig_ids]
2187 #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
2188 move2 = not move2.move_orig_ids and move2.split_from or False
2191 def recalculate_move_state(self, cr, uid, move_ids, context=None):
2192 '''Recompute the state of moves given because their reserved quants were used to fulfill another operation'''
2193 for move in self.browse(cr, uid, move_ids, context=context):
2195 reserved_quant_ids = move.reserved_quant_ids
2196 if len(reserved_quant_ids) > 0 and not move.partially_available:
2197 vals['partially_available'] = True
2198 if len(reserved_quant_ids) == 0 and move.partially_available:
2199 vals['partially_available'] = False
2200 if move.state == 'assigned':
2201 if self.find_move_ancestors(cr, uid, move, context=context):
2202 vals['state'] = 'waiting'
2204 vals['state'] = 'confirmed'
2206 self.write(cr, uid, [move.id], vals, context=context)
2208 def action_done(self, cr, uid, ids, context=None):
2209 """ Process completly the moves given as ids and if all moves are done, it will finish the picking.
2211 context = context or {}
2212 picking_obj = self.pool.get("stock.picking")
2213 quant_obj = self.pool.get("stock.quant")
2214 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
2216 ids = self.action_confirm(cr, uid, todo, context=context)
2218 procurement_ids = []
2219 #Search operations that are linked to the moves
2222 for move in self.browse(cr, uid, ids, context=context):
2223 move_qty[move.id] = move.product_qty
2224 for link in move.linked_move_operation_ids:
2225 operations.add(link.operation_id)
2227 #Sort operations according to entire packages first, then package + lot, package only, lot only
2228 operations = list(operations)
2229 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))
2231 for ops in operations:
2233 pickings.add(ops.picking_id.id)
2234 main_domain = [('qty', '>', 0)]
2235 for record in ops.linked_move_operation_ids:
2236 move = record.move_id
2237 self.check_tracking(cr, uid, move, ops.package_id.id or ops.lot_id.id, context=context)
2238 prefered_domain = [('reservation_id', '=', move.id)]
2239 fallback_domain = [('reservation_id', '=', False)]
2240 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2241 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2242 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2243 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,
2244 restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2245 if ops.result_package_id.id:
2246 #if a result package is given, all quants go there
2247 quant_dest_package_id = ops.result_package_id.id
2248 elif ops.product_id and ops.package_id:
2249 #if a package and a product is given, we will remove quants from the pack.
2250 quant_dest_package_id = False
2252 #otherwise we keep the current pack of the quant, which may mean None
2253 quant_dest_package_id = ops.package_id.id
2254 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)
2255 # Handle pack in pack
2256 if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
2257 self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
2258 move_qty[move.id] -= record.qty
2259 #Check for remaining qtys and unreserve/check move_dest_id in
2260 for move in self.browse(cr, uid, ids, context=context):
2261 if move_qty[move.id] > 0: # (=In case no pack operations in picking)
2262 main_domain = [('qty', '>', 0)]
2263 prefered_domain = [('reservation_id', '=', move.id)]
2264 fallback_domain = [('reservation_id', '=', False)]
2265 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2266 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2267 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
2268 qty = move_qty[move.id]
2269 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)
2270 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)
2271 #unreserve the quants and make them available for other operations/moves
2272 quant_obj.quants_unreserve(cr, uid, move, context=context)
2274 #Check moves that were pushed
2275 if move.move_dest_id.state in ('waiting', 'confirmed'):
2276 # FIXME is opw 607970 still present with new WMS?
2277 # (see commits 1ef2c181033bd200906fb1e5ce35e234bf566ac6
2278 # and 41c5ceb8ebb95c1b4e98d8dd1f12b8e547a24b1d)
2279 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
2280 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
2281 #If no other moves for the move that got pushed:
2282 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
2283 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
2284 if move.procurement_id:
2285 procurement_ids.append(move.procurement_id.id)
2287 # Check the packages have been placed in the correct locations
2288 self._check_package_from_moves(cr, uid, ids, context=context)
2289 #set the move as done
2290 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2291 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
2292 #check picking state to set the date_done is needed
2294 for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
2295 if picking.state == 'done' and not picking.date_done:
2296 done_picking.append(picking.id)
2298 picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2301 def unlink(self, cr, uid, ids, context=None):
2302 context = context or {}
2303 for move in self.browse(cr, uid, ids, context=context):
2304 if move.state not in ('draft', 'cancel'):
2305 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2306 return super(stock_move, self).unlink(cr, uid, ids, context=context)
2308 def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
2309 """ Move the scrap/damaged product into scrap location
2310 @param cr: the database cursor
2311 @param uid: the user id
2312 @param ids: ids of stock move object to be scrapped
2313 @param quantity : specify scrap qty
2314 @param location_id : specify scrap location
2315 @param context: context arguments
2316 @return: Scraped lines
2318 #quantity should be given in MOVE UOM
2320 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2322 for move in self.browse(cr, uid, ids, context=context):
2323 source_location = move.location_id
2324 if move.state == 'done':
2325 source_location = move.location_dest_id
2326 #Previously used to prevent scraping from virtual location but not necessary anymore
2327 #if source_location.usage != 'internal':
2328 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2329 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2330 move_qty = move.product_qty
2331 uos_qty = quantity / move_qty * move.product_uos_qty
2333 'location_id': source_location.id,
2334 'product_uom_qty': quantity,
2335 'product_uos_qty': uos_qty,
2336 'state': move.state,
2338 'location_dest_id': location_id,
2339 'restrict_lot_id': restrict_lot_id,
2340 'restrict_partner_id': restrict_partner_id,
2342 new_move = self.copy(cr, uid, move.id, default_val)
2345 product_obj = self.pool.get('product.product')
2346 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2348 uom = product.uom_id.name if product.uom_id else ''
2349 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2350 move.picking_id.message_post(body=message)
2352 self.action_done(cr, uid, res, context=context)
2355 def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
2356 """ Splits qty from move move into a new move
2357 :param move: browse record
2358 :param qty: float. quantity to split (given in product UoM)
2359 :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.
2360 :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.
2361 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
2363 returns the ID of the backorder move created
2365 if move.state in ('done', 'cancel'):
2366 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
2367 if move.state == 'draft':
2368 #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
2369 #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
2370 raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
2372 if move.product_qty <= qty or qty == 0:
2375 uom_obj = self.pool.get('product.uom')
2376 context = context or {}
2378 uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom)
2379 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
2382 'product_uom_qty': uom_qty,
2383 'product_uos_qty': uos_qty,
2384 'state': move.state,
2385 'procure_method': 'make_to_stock',
2386 'restrict_lot_id': restrict_lot_id,
2387 'restrict_partner_id': restrict_partner_id,
2388 'split_from': move.id,
2389 'move_dest_id': move.move_dest_id.id,
2391 if context.get('source_location_id'):
2392 defaults['location_id'] = context['source_location_id']
2393 new_move = self.copy(cr, uid, move.id, defaults)
2395 ctx = context.copy()
2396 ctx['do_not_propagate'] = True
2397 self.write(cr, uid, [move.id], {
2398 'product_uom_qty': move.product_uom_qty - uom_qty,
2399 'product_uos_qty': move.product_uos_qty - uos_qty,
2402 if move.move_dest_id and move.propagate:
2403 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2404 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2405 #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
2406 #thus the result of action_confirm should always be a list of 1 element length)
2407 return self.action_confirm(cr, uid, [new_move], context=context)[0]
2410 class stock_inventory(osv.osv):
2411 _name = "stock.inventory"
2412 _description = "Inventory"
2414 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2416 for inv in self.browse(cr, uid, ids, context=context):
2422 def _get_available_filters(self, cr, uid, context=None):
2424 This function will return the list of filter allowed according to the options checked
2425 in 'Settings\Warehouse'.
2427 :rtype: list of tuple
2429 #default available choices
2430 res_filter = [('none', _('All products')), ('product', _('One product only'))]
2431 settings_obj = self.pool.get('stock.config.settings')
2432 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2433 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2437 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2438 if stock_settings.group_stock_tracking_owner:
2439 res_filter.append(('owner', _('One owner only')))
2440 res_filter.append(('product_owner', _('One product for a specific owner')))
2441 if stock_settings.group_stock_tracking_lot:
2442 res_filter.append(('lot', _('One Lot/Serial Number')))
2443 if stock_settings.group_stock_packaging:
2444 res_filter.append(('pack', _('A Pack')))
2447 def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
2449 for inv in self.browse(cr, uid, ids, context=context):
2450 res[inv.id] = sum([x.product_qty for x in inv.line_ids])
2453 INVENTORY_STATE_SELECTION = [
2455 ('cancel', 'Cancelled'),
2456 ('confirm', 'In Progress'),
2457 ('done', 'Validated'),
2461 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2462 '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."),
2463 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
2464 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
2465 'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True),
2466 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2467 'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2468 '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."),
2469 '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."),
2470 '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."),
2471 '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."),
2472 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2473 'filter': fields.selection(_get_available_filters, 'Selection Filter', required=True),
2474 'total_qty': fields.function(_get_total_qty, type="float"),
2477 def _default_stock_location(self, cr, uid, context=None):
2479 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2480 return warehouse.lot_stock_id.id
2485 'date': fields.datetime.now,
2487 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2488 'location_id': _default_stock_location,
2492 def reset_real_qty(self, cr, uid, ids, context=None):
2493 inventory = self.browse(cr, uid, ids[0], context=context)
2494 line_ids = [line.id for line in inventory.line_ids]
2495 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2498 def copy(self, cr, uid, id, default=None, context=None):
2501 default = default.copy()
2502 default.update({'move_ids': []})
2503 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2505 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2506 """ Creates a stock move from an inventory line
2507 @param inventory_line:
2511 return self.pool.get('stock.move').create(cr, uid, move_vals)
2513 def action_done(self, cr, uid, ids, context=None):
2514 """ Finish the inventory
2517 for inv in self.browse(cr, uid, ids, context=context):
2518 for inventory_line in inv.line_ids:
2519 if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty:
2520 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)))
2521 self.action_check(cr, uid, [inv.id], context=context)
2523 self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
2524 self.post_inventory(cr, uid, inv, context=context)
2527 def post_inventory(self, cr, uid, inv, context=None):
2528 #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
2529 #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
2530 #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
2531 move_obj = self.pool.get('stock.move')
2532 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2534 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2535 stock_move_obj = self.pool.get('stock.move')
2536 product_obj = self.pool.get('product.product')
2537 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2539 'name': _('INV:') + (inventory.name or ''),
2540 'product_id': todo_line['product_id'],
2541 'product_uom': todo_line['product_uom_id'],
2542 'date': inventory.date,
2543 'company_id': inventory.company_id.id,
2544 'inventory_id': inventory.id,
2545 'state': 'assigned',
2546 'restrict_lot_id': todo_line.get('prod_lot_id'),
2547 'restrict_partner_id': todo_line.get('partner_id'),
2550 if todo_line['product_qty'] < 0:
2551 #found more than expected
2552 vals['location_id'] = inventory_location_id
2553 vals['location_dest_id'] = todo_line['location_id']
2554 vals['product_uom_qty'] = -todo_line['product_qty']
2556 #found less than expected
2557 vals['location_id'] = todo_line['location_id']
2558 vals['location_dest_id'] = inventory_location_id
2559 vals['product_uom_qty'] = todo_line['product_qty']
2560 return stock_move_obj.create(cr, uid, vals, context=context)
2562 def action_check(self, cr, uid, ids, context=None):
2563 """ Checks the inventory and computes the stock move to do
2566 inventory_line_obj = self.pool.get('stock.inventory.line')
2567 stock_move_obj = self.pool.get('stock.move')
2568 for inventory in self.browse(cr, uid, ids, context=context):
2569 #first remove the existing stock moves linked to this inventory
2570 move_ids = [move.id for move in inventory.move_ids]
2571 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2572 for line in inventory.line_ids:
2573 #compare the checked quantities on inventory lines to the theorical one
2574 inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context)
2576 def action_cancel_draft(self, cr, uid, ids, context=None):
2577 """ Cancels the stock move and change inventory state to draft.
2580 for inv in self.browse(cr, uid, ids, context=context):
2581 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2582 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2585 def action_cancel_inventory(self, cr, uid, ids, context=None):
2586 self.action_cancel_draft(cr, uid, ids, context=context)
2588 def prepare_inventory(self, cr, uid, ids, context=None):
2589 inventory_line_obj = self.pool.get('stock.inventory.line')
2590 for inventory in self.browse(cr, uid, ids, context=context):
2591 #clean the existing inventory lines before redoing an inventory proposal
2592 line_ids = [line.id for line in inventory.line_ids]
2593 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2594 #compute the inventory lines and create them
2595 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2596 for product_line in vals:
2597 inventory_line_obj.create(cr, uid, product_line, context=context)
2598 return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
2600 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2601 location_obj = self.pool.get('stock.location')
2602 product_obj = self.pool.get('product.product')
2603 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2604 domain = ' location_id in %s'
2605 args = (tuple(location_ids),)
2606 if inventory.partner_id:
2607 domain += ' and owner_id = %s'
2608 args += (inventory.partner_id.id,)
2609 if inventory.lot_id:
2610 domain += ' and lot_id = %s'
2611 args += (inventory.lot_id.id,)
2612 if inventory.product_id:
2613 domain += 'and product_id = %s'
2614 args += (inventory.product_id.id,)
2615 if inventory.package_id:
2616 domain += ' and package_id = %s'
2617 args += (inventory.package_id.id,)
2620 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2621 FROM stock_quant WHERE''' + domain + '''
2622 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2625 for product_line in cr.dictfetchall():
2626 #replace the None the dictionary by False, because falsy values are tested later on
2627 for key, value in product_line.items():
2629 product_line[key] = False
2630 product_line['inventory_id'] = inventory.id
2631 product_line['theoretical_qty'] = product_line['product_qty']
2632 if product_line['product_id']:
2633 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2634 product_line['product_uom_id'] = product.uom_id.id
2635 vals.append(product_line)
2639 class stock_inventory_line(osv.osv):
2640 _name = "stock.inventory.line"
2641 _description = "Inventory Line"
2642 _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2644 def _get_product_name_change(self, cr, uid, ids, context=None):
2645 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2647 def _get_location_change(self, cr, uid, ids, context=None):
2648 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2650 def _get_prodlot_change(self, cr, uid, ids, context=None):
2651 return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2654 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2655 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2656 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2657 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2658 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2659 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2660 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2661 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2662 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2663 'theoretical_qty': fields.float('Theoretical Quantity', readonly=True),
2664 'partner_id': fields.many2one('res.partner', 'Owner'),
2665 'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
2666 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2667 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2668 'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
2669 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2670 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2671 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
2672 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2673 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2674 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
2675 'stock.production.lot': (_get_prodlot_change, ['name'], 20),
2676 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
2683 def _resolve_inventory_line(self, cr, uid, inventory_line, context=None):
2684 stock_move_obj = self.pool.get('stock.move')
2685 diff = inventory_line.theoretical_qty - inventory_line.product_qty
2688 #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
2690 'name': _('INV:') + (inventory_line.inventory_id.name or ''),
2691 'product_id': inventory_line.product_id.id,
2692 'product_uom': inventory_line.product_uom_id.id,
2693 'date': inventory_line.inventory_id.date,
2694 'company_id': inventory_line.inventory_id.company_id.id,
2695 'inventory_id': inventory_line.inventory_id.id,
2696 'state': 'confirmed',
2697 'restrict_lot_id': inventory_line.prod_lot_id.id,
2698 'restrict_partner_id': inventory_line.partner_id.id,
2700 inventory_location_id = inventory_line.product_id.property_stock_inventory.id
2702 #found more than expected
2703 vals['location_id'] = inventory_location_id
2704 vals['location_dest_id'] = inventory_line.location_id.id
2705 vals['product_uom_qty'] = -diff
2707 #found less than expected
2708 vals['location_id'] = inventory_line.location_id.id
2709 vals['location_dest_id'] = inventory_location_id
2710 vals['product_uom_qty'] = diff
2711 return stock_move_obj.create(cr, uid, vals, context=context)
2713 def restrict_change(self, cr, uid, ids, theoretical_qty, context=None):
2714 if ids and theoretical_qty:
2715 #if the user try to modify a line prepared by openerp, reject the change and display an error message explaining how he should do
2716 old_value = self.browse(cr, uid, ids[0], context=context)
2719 'product_id': old_value.product_id.id,
2720 'product_uom_id': old_value.product_uom_id.id,
2721 'location_id': old_value.location_id.id,
2722 'prod_lot_id': old_value.prod_lot_id.id,
2723 'package_id': old_value.package_id.id,
2724 'partner_id': old_value.partner_id.id,
2727 'title': _('Error'),
2728 '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.')
2733 def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None):
2735 @param location_id: Location id
2736 @param product: Changed product_id
2737 @param uom: UoM product
2738 @return: Dictionary of changed values
2740 if ids and theoretical_qty:
2741 return self.restrict_change(cr, uid, ids, theoretical_qty, context=context)
2743 return {'value': {'product_uom_id': False}}
2744 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context)
2745 return {'value': {'product_uom_id': uom or obj_product.uom_id.id}}
2748 #----------------------------------------------------------
2750 #----------------------------------------------------------
2751 class stock_warehouse(osv.osv):
2752 _name = "stock.warehouse"
2753 _description = "Warehouse"
2756 'name': fields.char('Warehouse Name', size=128, required=True, select=True),
2757 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, select=True),
2758 'partner_id': fields.many2one('res.partner', 'Address'),
2759 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2760 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2761 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2762 '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'),
2763 'reception_steps': fields.selection([
2764 ('one_step', 'Receive goods directly in stock (1 step)'),
2765 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2766 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments',
2767 help="Default incoming route to follow", required=True),
2768 'delivery_steps': fields.selection([
2769 ('ship_only', 'Ship directly from stock (Ship only)'),
2770 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2771 ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings',
2772 help="Default outgoing route to follow", required=True),
2773 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2774 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2775 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2776 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2777 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2778 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2779 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2780 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2781 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2782 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2783 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2784 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2785 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2786 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2787 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2788 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes',
2789 help="Routes will be created for these resupply warehouses and you can select them on products and product categories"),
2790 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"),
2793 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2794 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2795 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2796 resupply_wh_ids.add(default_resupply_wh_id)
2797 resupply_wh_ids = list(resupply_wh_ids)
2798 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2800 def _get_external_transit_location(self, cr, uid, warehouse, context=None):
2801 ''' returns browse record of inter company transit location, if found'''
2802 data_obj = self.pool.get('ir.model.data')
2803 location_obj = self.pool.get('stock.location')
2805 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2808 return location_obj.browse(cr, uid, inter_wh_loc, context=context)
2810 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2812 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2813 'warehouse_selectable': False,
2814 'product_selectable': True,
2815 'product_categ_selectable': True,
2816 'supplied_wh_id': warehouse.id,
2817 'supplier_wh_id': wh.id,
2820 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2821 route_obj = self.pool.get('stock.location.route')
2822 pull_obj = self.pool.get('procurement.rule')
2823 #create route selectable on the product to resupply the warehouse from another one
2824 external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context)
2825 internal_transit_location = warehouse.company_id.internal_transit_location_id
2826 input_loc = warehouse.wh_input_stock_loc_id
2827 if warehouse.reception_steps == 'one_step':
2828 input_loc = warehouse.lot_stock_id
2829 for wh in supplier_warehouses:
2830 transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location
2831 if transit_location:
2832 output_loc = wh.wh_output_stock_loc_id
2833 if wh.delivery_steps == 'ship_only':
2834 output_loc = wh.lot_stock_id
2835 # Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
2836 mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context)
2837 pull_obj.create(cr, uid, mto_pull_vals, context=context)
2838 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2839 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2840 values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)]
2841 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2842 for pull_rule in pull_rules_list:
2843 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2844 #if the warehouse is also set as default resupply method, assign this route automatically to the warehouse
2845 if default_resupply_wh and default_resupply_wh.id == wh.id:
2846 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2848 def _default_stock_id(self, cr, uid, context=None):
2849 #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2851 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2852 return warehouse.lot_stock_id.id
2857 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2858 'lot_stock_id': _default_stock_id,
2859 'reception_steps': 'one_step',
2860 'delivery_steps': 'ship_only',
2862 _sql_constraints = [
2863 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2864 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2867 def _get_partner_locations(self, cr, uid, ids, context=None):
2868 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2869 data_obj = self.pool.get('ir.model.data')
2870 location_obj = self.pool.get('stock.location')
2872 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2873 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2875 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2876 customer_loc = customer_loc and customer_loc[0] or False
2877 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2878 supplier_loc = supplier_loc and supplier_loc[0] or False
2879 if not (customer_loc and supplier_loc):
2880 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2881 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2883 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2884 location_obj = self.pool.get('stock.location')
2886 new_reception_step = new_reception_step or warehouse.reception_steps
2887 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2888 if warehouse.reception_steps != new_reception_step:
2889 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2890 if new_reception_step != 'one_step':
2891 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2892 if new_reception_step == 'three_steps':
2893 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2895 if warehouse.delivery_steps != new_delivery_step:
2896 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2897 if new_delivery_step != 'ship_only':
2898 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2899 if new_delivery_step == 'pick_pack_ship':
2900 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2903 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2905 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2906 'product_categ_selectable': True,
2907 'product_selectable': False,
2911 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2912 pull_rules_list = []
2913 for from_loc, dest_loc, pick_type_id, warehouse in values:
2914 pull_rules_list.append({
2915 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2916 'location_src_id': from_loc.id,
2917 'location_id': dest_loc.id,
2918 'route_id': new_route_id,
2920 'picking_type_id': pick_type_id,
2921 '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
2922 'warehouse_id': supplied_warehouse.id,
2923 'propagate_warehouse_id': warehouse.id,
2925 return pull_rules_list
2927 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2929 push_rules_list = []
2930 pull_rules_list = []
2931 for from_loc, dest_loc, pick_type_id in values:
2932 push_rules_list.append({
2933 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2934 'location_from_id': from_loc.id,
2935 'location_dest_id': dest_loc.id,
2936 'route_id': new_route_id,
2938 'picking_type_id': pick_type_id,
2940 'warehouse_id': warehouse.id,
2942 pull_rules_list.append({
2943 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2944 'location_src_id': from_loc.id,
2945 'location_id': dest_loc.id,
2946 'route_id': new_route_id,
2948 'picking_type_id': pick_type_id,
2949 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2951 'warehouse_id': warehouse.id,
2954 return push_rules_list, pull_rules_list
2956 def _get_mto_route(self, cr, uid, context=None):
2957 route_obj = self.pool.get('stock.location.route')
2958 data_obj = self.pool.get('ir.model.data')
2960 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2962 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2963 mto_route_id = mto_route_id and mto_route_id[0] or False
2964 if not mto_route_id:
2965 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
2968 def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None):
2969 """ Checks that the moves from the different """
2970 pull_obj = self.pool.get('procurement.rule')
2971 mto_route_id = self._get_mto_route(cr, uid, context=context)
2972 rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context)
2973 pull_obj.unlink(cr, uid, rules, context=context)
2975 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2976 mto_route_id = self._get_mto_route(cr, uid, context=context)
2977 from_loc, dest_loc, pick_type_id = values[0]
2979 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2980 'location_src_id': from_loc.id,
2981 'location_id': dest_loc.id,
2982 'route_id': mto_route_id,
2984 'picking_type_id': pick_type_id,
2985 'procure_method': 'make_to_order',
2987 'warehouse_id': warehouse.id,
2990 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2992 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2993 'warehouse_selectable': False,
2994 'product_selectable': True,
2995 'product_categ_selectable': True,
2996 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
3000 def create_routes(self, cr, uid, ids, warehouse, context=None):
3002 route_obj = self.pool.get('stock.location.route')
3003 pull_obj = self.pool.get('procurement.rule')
3004 push_obj = self.pool.get('stock.location.path')
3005 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3006 #create reception route and rules
3007 route_name, values = routes_dict[warehouse.reception_steps]
3008 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3009 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
3010 wh_route_ids.append((4, reception_route_id))
3011 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
3012 #create the push/pull rules
3013 for push_rule in push_rules_list:
3014 push_obj.create(cr, uid, vals=push_rule, context=context)
3015 for pull_rule in pull_rules_list:
3016 #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
3017 pull_rule['procure_method'] = 'make_to_order'
3018 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3020 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
3021 route_name, values = routes_dict[warehouse.delivery_steps]
3022 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3023 #create the route and its pull rules
3024 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
3025 wh_route_ids.append((4, delivery_route_id))
3026 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
3027 for pull_rule in pull_rules_list:
3028 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3029 #create MTO pull rule and link it to the generic MTO route
3030 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
3031 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
3033 #create a route for cross dock operations, that can be set on products and product categories
3034 route_name, values = routes_dict['crossdock']
3035 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
3036 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
3037 wh_route_ids.append((4, crossdock_route_id))
3038 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)
3039 for pull_rule in pull_rules_list:
3040 # Fixed cross-dock is logically mto
3041 pull_rule['procure_method'] = 'make_to_order'
3042 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3044 #create route selectable on the product to resupply the warehouse from another one
3045 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
3047 #return routes and mto pull rule to store on the warehouse
3049 'route_ids': wh_route_ids,
3050 'mto_pull_id': mto_pull_id,
3051 'reception_route_id': reception_route_id,
3052 'delivery_route_id': delivery_route_id,
3053 'crossdock_route_id': crossdock_route_id,
3056 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
3057 picking_type_obj = self.pool.get('stock.picking.type')
3058 pull_obj = self.pool.get('procurement.rule')
3059 push_obj = self.pool.get('stock.location.path')
3060 route_obj = self.pool.get('stock.location.route')
3061 new_reception_step = new_reception_step or warehouse.reception_steps
3062 new_delivery_step = new_delivery_step or warehouse.delivery_steps
3064 #change the default source and destination location and (de)activate picking types
3065 input_loc = warehouse.wh_input_stock_loc_id
3066 if new_reception_step == 'one_step':
3067 input_loc = warehouse.lot_stock_id
3068 output_loc = warehouse.wh_output_stock_loc_id
3069 if new_delivery_step == 'ship_only':
3070 output_loc = warehouse.lot_stock_id
3071 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
3072 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
3073 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
3074 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
3076 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3077 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
3078 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
3079 route_name, values = routes_dict[new_delivery_step]
3080 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3081 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
3082 #create the pull rules
3083 for pull_rule in pull_rules_list:
3084 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3086 #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
3087 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
3088 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
3089 route_name, values = routes_dict[new_reception_step]
3090 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3091 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
3092 #create the push/pull rules
3093 for push_rule in push_rules_list:
3094 push_obj.create(cr, uid, vals=push_rule, context=context)
3095 for pull_rule in pull_rules_list:
3096 #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
3097 pull_rule['procure_method'] = 'make_to_order'
3098 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3100 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
3103 dummy, values = routes_dict[new_delivery_step]
3104 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
3105 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
3108 def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):
3109 seq_obj = self.pool.get('ir.sequence')
3110 picking_type_obj = self.pool.get('stock.picking.type')
3111 #create new sequences
3112 in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence in'), 'prefix': warehouse.code + '/IN/', 'padding': 5}, context=context)
3113 out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence out'), 'prefix': warehouse.code + '/OUT/', 'padding': 5}, context=context)
3114 pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': warehouse.code + '/PACK/', 'padding': 5}, context=context)
3115 pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': warehouse.code + '/PICK/', 'padding': 5}, context=context)
3116 int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': warehouse.code + '/INT/', 'padding': 5}, context=context)
3118 wh_stock_loc = warehouse.lot_stock_id
3119 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
3120 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
3121 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
3123 #fetch customer and supplier locations, for references
3124 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)
3126 #create in, out, internal picking types for warehouse
3127 input_loc = wh_input_stock_loc
3128 if warehouse.reception_steps == 'one_step':
3129 input_loc = wh_stock_loc
3130 output_loc = wh_output_stock_loc
3131 if warehouse.delivery_steps == 'ship_only':
3132 output_loc = wh_stock_loc
3134 #choose the next available color for the picking types of this warehouse
3136 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
3137 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
3138 #don't use sets to preserve the list order
3139 for x in all_used_colors:
3140 if x['color'] in available_colors:
3141 available_colors.remove(x['color'])
3142 if available_colors:
3143 color = available_colors[0]
3145 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
3146 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
3147 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
3149 in_type_id = picking_type_obj.create(cr, uid, vals={
3150 'name': _('Receptions'),
3151 'warehouse_id': warehouse.id,
3153 'sequence_id': in_seq_id,
3154 'default_location_src_id': supplier_loc.id,
3155 'default_location_dest_id': input_loc.id,
3156 'sequence': max_sequence + 1,
3157 'color': color}, context=context)
3158 out_type_id = picking_type_obj.create(cr, uid, vals={
3159 'name': _('Delivery Orders'),
3160 'warehouse_id': warehouse.id,
3162 'sequence_id': out_seq_id,
3163 'return_picking_type_id': in_type_id,
3164 'default_location_src_id': output_loc.id,
3165 'default_location_dest_id': customer_loc.id,
3166 'sequence': max_sequence + 4,
3167 'color': color}, context=context)
3168 picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
3169 int_type_id = picking_type_obj.create(cr, uid, vals={
3170 'name': _('Internal Transfers'),
3171 'warehouse_id': warehouse.id,
3173 'sequence_id': int_seq_id,
3174 'default_location_src_id': wh_stock_loc.id,
3175 'default_location_dest_id': wh_stock_loc.id,
3177 'sequence': max_sequence + 2,
3178 'color': color}, context=context)
3179 pack_type_id = picking_type_obj.create(cr, uid, vals={
3181 'warehouse_id': warehouse.id,
3183 'sequence_id': pack_seq_id,
3184 'default_location_src_id': wh_pack_stock_loc.id,
3185 'default_location_dest_id': output_loc.id,
3186 'active': warehouse.delivery_steps == 'pick_pack_ship',
3187 'sequence': max_sequence + 3,
3188 'color': color}, context=context)
3189 pick_type_id = picking_type_obj.create(cr, uid, vals={
3191 'warehouse_id': warehouse.id,
3193 'sequence_id': pick_seq_id,
3194 'default_location_src_id': wh_stock_loc.id,
3195 'default_location_dest_id': wh_pack_stock_loc.id,
3196 'active': warehouse.delivery_steps != 'ship_only',
3197 'sequence': max_sequence + 2,
3198 'color': color}, context=context)
3200 #write picking types on WH
3202 'in_type_id': in_type_id,
3203 'out_type_id': out_type_id,
3204 'pack_type_id': pack_type_id,
3205 'pick_type_id': pick_type_id,
3206 'int_type_id': int_type_id,
3208 super(stock_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)
3211 def create(self, cr, uid, vals, context=None):
3216 data_obj = self.pool.get('ir.model.data')
3217 seq_obj = self.pool.get('ir.sequence')
3218 picking_type_obj = self.pool.get('stock.picking.type')
3219 location_obj = self.pool.get('stock.location')
3221 #create view location for warehouse
3222 wh_loc_id = location_obj.create(cr, uid, {
3223 'name': _(vals.get('code')),
3225 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
3227 vals['view_location_id'] = wh_loc_id
3228 #create all location
3229 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
3230 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
3231 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
3232 context_with_inactive = context.copy()
3233 context_with_inactive['active_test'] = False
3235 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
3236 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
3237 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
3238 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
3239 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
3241 for values in sub_locations:
3242 location_id = location_obj.create(cr, uid, {
3243 'name': values['name'],
3244 'usage': 'internal',
3245 'location_id': wh_loc_id,
3246 'active': values['active'],
3247 }, context=context_with_inactive)
3248 vals[values['field']] = location_id
3251 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
3252 warehouse = self.browse(cr, uid, new_id, context=context)
3253 self.create_sequences_and_picking_types(cr, uid, warehouse, context=context)
3256 #create routes and push/pull rules
3257 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
3258 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
3261 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
3262 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
3264 def _format_routename(self, cr, uid, obj, name, context=None):
3265 return obj.name + ': ' + name
3267 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
3268 #fetch customer and supplier locations, for references
3269 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
3272 'one_step': (_('Reception in 1 step'), []),
3273 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3274 'three_steps': (_('Reception in 3 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.wh_qc_stock_loc_id, warehouse.int_type_id.id), (warehouse.wh_qc_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3275 '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)]),
3276 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
3277 '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)]),
3278 '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)]),
3281 def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
3282 location_obj = self.pool.get('stock.location')
3283 route_obj = self.pool.get('stock.location.route')
3284 pull_obj = self.pool.get('procurement.rule')
3285 push_obj = self.pool.get('stock.location.path')
3287 location_id = warehouse.lot_stock_id.location_id.id
3288 location_obj.write(cr, uid, location_id, {'name': code}, context=context)
3289 #rename route and push-pull rules
3290 for route in warehouse.route_ids:
3291 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
3292 for pull in route.pull_ids:
3293 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3294 for push in route.push_ids:
3295 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3296 #change the mto pull rule name
3297 if warehouse.mto_pull_id.id:
3298 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
3300 def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None):
3301 """ Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """
3302 #Check routes that are being delivered by this warehouse and change the rule going to transit location
3303 route_obj = self.pool.get("stock.location.route")
3304 pull_obj = self.pool.get("procurement.rule")
3305 routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context)
3306 pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context)
3308 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)
3309 # Create or clean MTO rules
3310 mto_route_id = self._get_mto_route(cr, uid, context=context)
3311 if not change_to_multiple:
3312 # If single delivery we should create the necessary MTO rules for the resupply
3313 # 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)
3314 pull_recs = pull_obj.browse(cr, uid, pulls, context=context)
3315 transfer_locs = list(set([x.location_id for x in pull_recs]))
3316 vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs]
3317 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context)
3318 pull_obj.create(cr, uid, mto_pull_vals, context=context)
3320 # We need to delete all the MTO pull rules, otherwise they risk to be used in the system
3321 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)
3323 pull_obj.unlink(cr, uid, pulls, context=context)
3325 def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None):
3327 Will check if the resupply routes to this warehouse follow the changes of number of reception steps
3329 #Check routes that are being delivered by this warehouse and change the rule coming from transit location
3330 route_obj = self.pool.get("stock.location.route")
3331 pull_obj = self.pool.get("procurement.rule")
3332 routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context)
3333 pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')])
3335 pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context)
3337 def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None):
3339 old_val = warehouse.reception_steps
3340 new_val = reception_new
3341 change_to_one = (old_val != 'one_step' and new_val == 'one_step')
3342 change_to_multiple = (old_val == 'one_step' and new_val != 'one_step')
3343 if change_to_one or change_to_multiple:
3344 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id
3345 self._check_reception_resupply(cr, uid, warehouse, new_location, context=context)
3347 old_val = warehouse.delivery_steps
3348 new_val = delivery_new
3349 change_to_one = (old_val != 'ship_only' and new_val == 'ship_only')
3350 change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only')
3351 if change_to_one or change_to_multiple:
3352 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id
3353 self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context)
3355 def write(self, cr, uid, ids, vals, context=None):
3358 if isinstance(ids, (int, long)):
3360 seq_obj = self.pool.get('ir.sequence')
3361 route_obj = self.pool.get('stock.location.route')
3362 context_with_inactive = context.copy()
3363 context_with_inactive['active_test'] = False
3364 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
3365 #first of all, check if we need to delete and recreate route
3366 if vals.get('reception_steps') or vals.get('delivery_steps'):
3367 #activate and deactivate location according to reception and delivery option
3368 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
3369 # switch between route
3370 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
3371 # Check if we need to change something to resupply warehouses and associated MTO rules
3372 self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context)
3374 if vals.get('code') or vals.get('name'):
3375 name = warehouse.name
3377 if vals.get('name'):
3378 name = vals.get('name', warehouse.name)
3379 self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
3380 if warehouse.in_type_id:
3381 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)
3382 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)
3383 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)
3384 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)
3385 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)
3386 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
3387 for cmd in vals.get('resupply_wh_ids'):
3389 new_ids = set(cmd[2])
3390 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
3391 to_add_wh_ids = new_ids - old_ids
3393 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
3394 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
3395 to_remove_wh_ids = old_ids - new_ids
3396 if to_remove_wh_ids:
3397 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)
3398 if to_remove_route_ids:
3399 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
3403 if 'default_resupply_wh_id' in vals:
3404 if vals.get('default_resupply_wh_id') == warehouse.id:
3405 raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
3406 if warehouse.default_resupply_wh_id:
3407 #remove the existing resupplying route on the warehouse
3408 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)
3409 for inter_wh_route_id in to_remove_route_ids:
3410 self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]})
3411 if vals.get('default_resupply_wh_id'):
3412 #assign the new resupplying route on all products
3413 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)
3414 for inter_wh_route_id in to_assign_route_ids:
3415 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]})
3417 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
3419 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
3420 route_obj = self.pool.get("stock.location.route")
3421 all_routes = [route.id for route in warehouse.route_ids]
3422 all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context)
3423 all_routes += [warehouse.mto_pull_id.route_id.id]
3426 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
3428 for wh in self.browse(cr, uid, ids, context=context):
3429 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
3431 domain = [('id', 'in', all_routes)]
3433 'name': _('Warehouse\'s Routes'),
3435 'res_model': 'stock.location.route',
3436 'type': 'ir.actions.act_window',
3438 'view_mode': 'tree,form',
3439 'view_type': 'form',
3443 class stock_location_path(osv.osv):
3444 _name = "stock.location.path"
3445 _description = "Pushed Flows"
3448 def _get_rules(self, cr, uid, ids, context=None):
3450 for route in self.browse(cr, uid, ids, context=context):
3451 res += [x.id for x in route.push_ids]
3455 'name': fields.char('Operation Name', size=64, required=True),
3456 'company_id': fields.many2one('res.company', 'Company'),
3457 'route_id': fields.many2one('stock.location.route', 'Route'),
3458 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
3459 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
3460 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
3461 '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"),
3462 'auto': fields.selection(
3463 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
3465 required=True, select=1,
3466 help="This is used to define paths the product has to follow within the location tree.\n" \
3467 "The 'Automatic Move' value will create a stock move after the current one that will be "\
3468 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
3469 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
3471 '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'),
3472 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."),
3473 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3474 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3476 'stock.location.route': (_get_rules, ['sequence'], 10),
3477 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3479 'sequence': fields.integer('Sequence'),
3484 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3489 def _apply(self, cr, uid, rule, move, context=None):
3490 move_obj = self.pool.get('stock.move')
3491 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3492 if rule.auto == 'transparent':
3493 old_dest_location = move.location_dest_id.id
3494 move_obj.write(cr, uid, [move.id], {
3496 'date_expected': newdate,
3497 'location_dest_id': rule.location_dest_id.id
3500 #avoid looping if a push rule is not well configured
3501 if rule.location_dest_id.id != old_dest_location:
3502 #call again push_apply to see if a next step is defined
3503 move_obj._push_apply(cr, uid, [move], context=context)
3505 move_id = move_obj.copy(cr, uid, move.id, {
3506 'location_id': move.location_dest_id.id,
3507 'location_dest_id': rule.location_dest_id.id,
3509 'company_id': rule.company_id and rule.company_id.id or False,
3510 'date_expected': newdate,
3511 'picking_id': False,
3512 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3513 'propagate': rule.propagate,
3514 'push_rule_id': rule.id,
3515 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3517 move_obj.write(cr, uid, [move.id], {
3518 'move_dest_id': move_id,
3520 move_obj.action_confirm(cr, uid, [move_id], context=None)
3523 # -------------------------
3524 # Packaging related stuff
3525 # -------------------------
3527 from openerp.report import report_sxw
3528 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
3530 class stock_package(osv.osv):
3532 These are the packages, containing quants and/or other packages
3534 _name = "stock.quant.package"
3535 _description = "Physical Packages"
3536 _parent_name = "parent_id"
3537 _parent_store = True
3538 _parent_order = 'name'
3539 _order = 'parent_left'
3541 def name_get(self, cr, uid, ids, context=None):
3542 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3545 def _complete_name(self, cr, uid, ids, name, args, context=None):
3546 """ Forms complete name of location from parent location to child location.
3547 @return: Dictionary of values
3550 for m in self.browse(cr, uid, ids, context=context):
3552 parent = m.parent_id
3554 res[m.id] = parent.name + ' / ' + res[m.id]
3555 parent = parent.parent_id
3558 def _get_packages(self, cr, uid, ids, context=None):
3559 """Returns packages from quants for store"""
3561 for quant in self.browse(cr, uid, ids, context=context):
3562 if quant.package_id:
3563 res.add(quant.package_id.id)
3566 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3568 for pack in self.browse(cr, uid, ids, context=context):
3571 res.add(pack.parent_id.id)
3574 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3575 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3576 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id, 'owner_id': False})
3577 for pack in self.browse(cr, uid, ids, context=context):
3579 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3580 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3581 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3582 elif pack.children_ids:
3583 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3584 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3585 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3589 'name': fields.char('Package Reference', size=64, select=True),
3590 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3591 'parent_left': fields.integer('Left Parent', select=1),
3592 'parent_right': fields.integer('Right Parent', select=1),
3593 '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."),
3594 'ul_id': fields.many2one('product.ul', 'Logistic Unit'),
3595 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3597 'stock.quant': (_get_packages, ['location_id'], 10),
3598 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3600 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
3601 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
3602 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
3603 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3605 'stock.quant': (_get_packages, ['company_id'], 10),
3606 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3608 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3610 'stock.quant': (_get_packages, ['owner_id'], 10),
3611 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3615 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3618 def _check_location_constraint(self, cr, uid, packs, context=None):
3619 '''checks that all quants in a package are stored in the same location. This function cannot be used
3620 as a constraint because it needs to be checked on pack operations (they may not call write on the
3623 quant_obj = self.pool.get('stock.quant')
3626 while parent.parent_id:
3627 parent = parent.parent_id
3628 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3629 quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0]
3630 location_id = quants and quants[0].location_id.id or False
3631 if not [quant.location_id.id == location_id for quant in quants]:
3632 raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
3635 def action_print(self, cr, uid, ids, context=None):
3636 context = context or {}
3637 context['active_ids'] = ids
3638 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_package_barcode', context=context)
3641 def unpack(self, cr, uid, ids, context=None):
3642 quant_obj = self.pool.get('stock.quant')
3643 for package in self.browse(cr, uid, ids, context=context):
3644 quant_ids = [quant.id for quant in package.quant_ids]
3645 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3646 children_package_ids = [child_package.id for child_package in package.children_ids]
3647 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3648 #delete current package since it contains nothing anymore
3649 self.unlink(cr, uid, ids, context=context)
3650 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3652 def get_content(self, cr, uid, ids, context=None):
3653 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3654 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3656 def get_content_package(self, cr, uid, ids, context=None):
3657 quants_ids = self.get_content(cr, uid, ids, context=context)
3658 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3659 res['domain'] = [('id', 'in', quants_ids)]
3662 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3663 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3664 quant_obj = self.pool.get('stock.quant')
3665 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3667 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3668 if quant.product_id.id == product_id:
3672 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3673 '''This function computes the different product quantities for the given package
3675 quant_obj = self.pool.get('stock.quant')
3677 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3678 if quant.product_id.id not in res:
3679 res[quant.product_id.id] = 0
3680 res[quant.product_id.id] += quant.qty
3683 def copy(self, cr, uid, id, default=None, context=None):
3686 if not default.get('name'):
3687 default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3688 default['quant_ids'] = []
3689 default['children_ids'] = []
3690 return super(stock_package, self).copy(cr, uid, id, default, context=context)
3692 def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
3693 stock_pack_operation_obj = self.pool.get('stock.pack.operation')
3696 new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
3697 default['result_package_id'] = new_package_id
3698 op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
3699 for op_id in op_ids:
3700 stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
3703 class stock_pack_operation(osv.osv):
3704 _name = "stock.pack.operation"
3705 _description = "Packing Operation"
3707 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3708 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3709 #if the operation doesn't concern a package, it's not relevant to call this function
3710 if not operation.package_id or operation.product_id:
3711 return {operation.product_id.id: operation.remaining_qty}
3712 #get the total of products the package contains
3713 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3714 #reduce by the quantities linked to a move
3715 for record in operation.linked_move_operation_ids:
3716 if record.move_id.product_id.id not in res:
3717 res[record.move_id.product_id.id] = 0
3718 res[record.move_id.product_id.id] -= record.qty
3721 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3722 uom_obj = self.pool.get('product.uom')
3724 for ops in self.browse(cr, uid, ids, context=context):
3726 if ops.package_id and not ops.product_id:
3727 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3728 #should use _get_remaining_prod_quantities instead
3731 qty = ops.product_qty
3732 if ops.product_uom_id:
3733 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
3734 for record in ops.linked_move_operation_ids:
3736 #converting the remaining quantity in the pack operation UoM
3737 if ops.product_uom_id:
3738 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context)
3742 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3743 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3744 if product_id and not product_uom_id:
3745 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3746 res['value']['product_uom_id'] = product.uom_id.id
3749 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3751 uom_obj = self.pool.get('product.uom')
3753 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3754 product_uom_id = product_uom_id or product.uom_id.id
3755 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3756 if selected_uom.category_id.id != product.uom_id.category_id.id:
3758 'title': _('Warning: wrong UoM!'),
3759 '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)
3761 if product_qty and 'warning' not in res:
3762 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3763 if rounded_qty != product_qty:
3765 'title': _('Warning: wrong quantity!'),
3766 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3771 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3772 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3773 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3774 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3775 'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
3776 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2
3777 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3778 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3779 'date': fields.datetime('Date', required=True),
3780 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3781 #'update_cost': fields.boolean('Need cost update'),
3782 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3783 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3784 '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'),
3785 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3786 'location_id': fields.many2one('stock.location', 'Location From', required=True),
3787 'location_dest_id': fields.many2one('stock.location', 'Location To', required=True),
3788 'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
3792 'date': fields.date.context_today,
3794 'processed': lambda *a: 'false',
3797 def write(self, cr, uid, ids, vals, context=None):
3798 context = context or {}
3799 res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
3800 if isinstance(ids, (int, long)):
3802 if not context.get("no_recompute"):
3803 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)]))
3804 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
3807 def create(self, cr, uid, vals, context=None):
3808 context = context or {}
3809 res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
3810 if vals.get("picking_id") and not context.get("no_recompute"):
3811 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
3814 def action_drop_down(self, cr, uid, ids, context=None):
3815 ''' Used by barcode interface to say that pack_operation has been moved from src location
3816 to destination location, if qty_done is less than product_qty than we have to split the
3817 operation in two to process the one with the qty moved
3820 for pack_op in self.browse(cr, uid, ids, context=None):
3822 if pack_op.qty_done < pack_op.product_qty:
3823 # we split the operation in two
3824 op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
3825 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)
3826 processed_ids.append(op)
3827 self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
3829 def create_and_assign_lot(self, cr, uid, id, name, context=None):
3830 ''' Used by barcode interface to create a new lot and assign it to the operation
3832 obj = self.browse(cr,uid,id,context)
3833 product_id = obj.product_id.id
3834 val = {'product_id': product_id}
3837 lots = self.pool.get('stock.production.lot').search(cr, uid, ['&', ('name', '=', name), ('product_id', '=', product_id)], context=context)
3839 new_lot_id = lots[0]
3840 val.update({'name': name})
3844 new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context)
3845 self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
3847 def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, increment=True, context=None):
3848 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3850 :param domain: list of tuple directly reusable as a domain
3851 context can receive a key 'current_package_id' with the package to consider for this operation
3857 #if current_package_id is given in the context, we increase the number of items in this package
3858 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3859 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3860 todo_operation_ids = []
3861 if existing_operation_ids:
3863 todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
3865 todo_operation_ids = existing_operation_ids
3866 if todo_operation_ids:
3867 #existing operation found for the given domain and picking => increment its quantity
3868 operation_id = todo_operation_ids[0]
3869 op_obj = self.browse(cr, uid, operation_id, context=context)
3870 qty = op_obj.qty_done
3874 qty -= 1 if qty >= 1 else 0
3875 if qty == 0 and op_obj.product_qty == 0:
3876 #we have a line with 0 qty set, so delete it
3877 self.unlink(cr, uid, [operation_id], context=context)
3879 self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
3881 #no existing operation found for the given domain and picking => create a new one
3882 picking_obj = self.pool.get("stock.picking")
3883 picking = picking_obj.browse(cr, uid, picking_id, context=context)
3885 'picking_id': picking_id,
3887 'location_id': picking.location_id.id,
3888 'location_dest_id': picking.location_dest_id.id,
3892 var_name, dummy, value = key
3894 if var_name == 'product_id':
3895 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3896 update_dict = {var_name: value}
3898 update_dict['product_uom_id'] = uom_id
3899 values.update(update_dict)
3900 operation_id = self.create(cr, uid, values, context=context)
3904 class stock_move_operation_link(osv.osv):
3906 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3908 _name = "stock.move.operation.link"
3909 _description = "Link between stock moves and pack operations"
3912 '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."),
3913 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3914 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3915 '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"),
3918 def get_specific_domain(self, cr, uid, record, context=None):
3919 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3920 having the record given as parameter making the link between the stock move and a pack operation'''
3922 op = record.operation_id
3924 if op.package_id and op.product_id:
3925 #if removing a product from a box, we restrict the choice of quants to this box
3926 domain.append(('package_id', '=', op.package_id.id))
3928 #if moving a box, we allow to take everything from inside boxes as well
3929 domain.append(('package_id', 'child_of', [op.package_id.id]))
3931 #if not given any information about package, we don't open boxes
3932 domain.append(('package_id', '=', False))
3933 #if lot info is given, we restrict choice to this lot otherwise we can take any
3935 domain.append(('lot_id', '=', op.lot_id.id))
3936 #if owner info is given, we restrict to this owner otherwise we restrict to no owner
3938 domain.append(('owner_id', '=', op.owner_id.id))
3940 domain.append(('owner_id', '=', False))
3943 class stock_warehouse_orderpoint(osv.osv):
3945 Defines Minimum stock rules.
3947 _name = "stock.warehouse.orderpoint"
3948 _description = "Minimum Inventory Rule"
3950 def subtract_procurements(self, cr, uid, orderpoint, context=None):
3951 '''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.
3954 uom_obj = self.pool.get("product.uom")
3955 for procurement in orderpoint.procurement_ids:
3956 if procurement.state in ('cancel', 'done'):
3958 procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context)
3959 for move in procurement.move_ids:
3960 if move.state not in ('draft', 'cancel'):
3961 #if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted
3962 procurement_qty -= move.product_qty
3963 qty += procurement_qty
3966 def _check_product_uom(self, cr, uid, ids, context=None):
3968 Check if the UoM has the same category as the product standard UoM
3973 for rule in self.browse(cr, uid, ids, context=context):
3974 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3979 def action_view_proc_to_process(self, cr, uid, ids, context=None):
3980 act_obj = self.pool.get('ir.actions.act_window')
3981 mod_obj = self.pool.get('ir.model.data')
3982 proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context)
3983 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3987 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3988 result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]"
3992 'name': fields.char('Name', size=32, required=True),
3993 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3994 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3995 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3996 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3997 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]),
3998 'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True),
3999 'product_min_qty': fields.float('Minimum Quantity', required=True,
4000 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
4001 "a procurement to bring the forecasted quantity to the Max Quantity."),
4002 'product_max_qty': fields.float('Maximum Quantity', required=True,
4003 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
4004 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
4005 'qty_multiple': fields.integer('Qty Multiple', required=True,
4006 help="The procurement quantity will be rounded up to this multiple."),
4007 'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'),
4008 '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."),
4009 'company_id': fields.many2one('res.company', 'Company', required=True),
4012 'active': lambda *a: 1,
4013 'logic': lambda *a: 'max',
4014 'qty_multiple': lambda *a: 1,
4015 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
4016 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
4017 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
4019 _sql_constraints = [
4020 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
4023 (_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']),
4026 def default_get(self, cr, uid, fields, context=None):
4027 warehouse_obj = self.pool.get('stock.warehouse')
4028 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
4029 # default 'warehouse_id' and 'location_id'
4030 if 'warehouse_id' not in res:
4031 warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or []
4032 res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False
4033 if 'location_id' not in res:
4034 res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False
4037 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
4038 """ Finds location id for changed warehouse.
4039 @param warehouse_id: Changed id of warehouse.
4040 @return: Dictionary of values.
4043 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
4044 v = {'location_id': w.lot_stock_id.id}
4048 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
4049 """ Finds UoM for changed product.
4050 @param product_id: Changed id of product.
4051 @return: Dictionary of values.
4054 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
4055 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
4056 v = {'product_uom': prod.uom_id.id}
4057 return {'value': v, 'domain': d}
4058 return {'domain': {'product_uom': []}}
4060 def copy_data(self, cr, uid, id, default=None, context=None):
4064 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
4065 'procurement_ids': [],
4068 return super(stock_warehouse_orderpoint, self).copy_data(cr, uid, id, default, context=context)
4071 class stock_picking_type(osv.osv):
4072 _name = "stock.picking.type"
4073 _description = "The picking type determines the picking view"
4076 def open_barcode_interface(self, cr, uid, ids, context=None):
4077 final_url = "/barcode/web/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0'
4078 return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'}
4080 def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
4081 picking_obj = self.pool.get('stock.picking')
4082 res = dict.fromkeys(ids, [])
4083 for picking_type_id in ids:
4084 #get last 10 pickings of this type
4085 picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
4087 for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
4088 if picking.date_done > picking.date:
4089 tristates.insert(0, {'tooltip': picking.name or '' + _(': Late'), 'value': -1})
4090 elif picking.backorder_id:
4091 tristates.insert(0, {'tooltip': picking.name or '' + _(': Backorder exists'), 'value': 0})
4093 tristates.insert(0, {'tooltip': picking.name or '' + _(': OK'), 'value': 1})
4094 res[picking_type_id] = json.dumps(tristates)
4097 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
4098 obj = self.pool.get('stock.picking')
4100 'count_picking_draft': [('state', '=', 'draft')],
4101 'count_picking_waiting': [('state', '=', 'confirmed')],
4102 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
4103 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4104 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4105 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
4108 for field in domains:
4109 data = obj.read_group(cr, uid, domains[field] +
4110 [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
4111 ['picking_type_id'], ['picking_type_id'], context=context)
4112 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
4114 result.setdefault(tid, {})[field] = count.get(tid, 0)
4116 if result[tid]['count_picking']:
4117 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
4118 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
4120 result[tid]['rate_picking_late'] = 0
4121 result[tid]['rate_picking_backorders'] = 0
4124 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
4125 if not picking_code:
4128 obj_data = self.pool.get('ir.model.data')
4129 stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock')
4132 'default_location_src_id': stock_loc,
4133 'default_location_dest_id': stock_loc,
4135 if picking_code == 'incoming':
4136 result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers')
4137 elif picking_code == 'outgoing':
4138 result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers')
4139 return {'value': result}
4141 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
4142 return dict(self.name_get(cr, uid, ids, context=context))
4144 def name_get(self, cr, uid, ids, context=None):
4145 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
4148 if not isinstance(ids, list):
4153 for record in self.browse(cr, uid, ids, context=context):
4155 if record.warehouse_id:
4156 name = record.warehouse_id.name + ': ' +name
4157 if context.get('special_shortened_wh_name'):
4158 if record.warehouse_id:
4159 name = record.warehouse_id.name
4161 name = _('Customer') + ' (' + record.name + ')'
4162 res.append((record.id, name))
4165 def _default_warehouse(self, cr, uid, context=None):
4166 user = self.pool.get('res.users').browse(cr, uid, uid, context)
4167 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
4168 return res and res[0] or False
4171 'name': fields.char('Picking Type Name', translate=True, required=True),
4172 'complete_name': fields.function(_get_name, type='char', string='Name'),
4173 'color': fields.integer('Color'),
4174 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
4175 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
4176 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
4177 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
4178 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
4179 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
4180 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
4181 'active': fields.boolean('Active'),
4183 # Statistics for the kanban view
4184 'last_done_picking': fields.function(_get_tristate_values,
4186 string='Last 10 Done Pickings'),
4188 'count_picking_draft': fields.function(_get_picking_count,
4189 type='integer', multi='_get_picking_count'),
4190 'count_picking_ready': fields.function(_get_picking_count,
4191 type='integer', multi='_get_picking_count'),
4192 'count_picking': fields.function(_get_picking_count,
4193 type='integer', multi='_get_picking_count'),
4194 'count_picking_waiting': fields.function(_get_picking_count,
4195 type='integer', multi='_get_picking_count'),
4196 'count_picking_late': fields.function(_get_picking_count,
4197 type='integer', multi='_get_picking_count'),
4198 'count_picking_backorders': fields.function(_get_picking_count,
4199 type='integer', multi='_get_picking_count'),
4201 'rate_picking_late': fields.function(_get_picking_count,
4202 type='integer', multi='_get_picking_count'),
4203 'rate_picking_backorders': fields.function(_get_picking_count,
4204 type='integer', multi='_get_picking_count'),
4208 'warehouse_id': _default_warehouse,
4212 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: