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
35 _logger = logging.getLogger(__name__)
36 #----------------------------------------------------------
38 #----------------------------------------------------------
39 class stock_incoterms(osv.osv):
40 _name = "stock.incoterms"
41 _description = "Incoterms"
43 '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."),
44 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
45 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
51 #----------------------------------------------------------
53 #----------------------------------------------------------
55 class stock_location(osv.osv):
56 _name = "stock.location"
57 _description = "Inventory Locations"
58 _parent_name = "location_id"
60 _parent_order = 'name'
61 _order = 'parent_left'
62 _rec_name = 'complete_name'
64 def _location_owner(self, cr, uid, location, context=None):
65 ''' Return the company owning the location if any '''
66 return location and (location.usage == 'internal') and location.company_id or False
68 def _complete_name(self, cr, uid, ids, name, args, context=None):
69 """ Forms complete name of location from parent location to child location.
70 @return: Dictionary of values
73 for m in self.browse(cr, uid, ids, context=context):
75 parent = m.location_id
77 res[m.id] = parent.name + ' / ' + res[m.id]
78 parent = parent.location_id
81 def _get_sublocations(self, cr, uid, ids, context=None):
82 """ return all sublocations of the given stock locations (included) """
85 context_with_inactive = context.copy()
86 context_with_inactive['active_test'] = False
87 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
89 def _name_get(self, cr, uid, location, context=None):
91 while location.location_id and location.usage != 'view':
92 location = location.location_id
93 name = location.name + '/' + name
96 def name_get(self, cr, uid, ids, context=None):
98 for location in self.browse(cr, uid, ids, context=context):
99 res.append((location.id, self._name_get(cr, uid, location, context=context)))
103 'name': fields.char('Location Name', size=64, required=True, translate=True),
104 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
105 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
106 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
107 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
108 \n* Internal Location: Physical locations inside your own warehouses,
109 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
110 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
111 \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.
112 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
115 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
116 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
117 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
118 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
120 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
122 'comment': fields.text('Additional Information'),
123 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
124 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
125 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
127 'parent_left': fields.integer('Left Parent', select=1),
128 'parent_right': fields.integer('Right Parent', select=1),
130 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
131 'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
132 'removal_strategy_ids': fields.one2many('product.removal', 'location_id', 'Removal Strategies'),
133 'putaway_strategy_ids': fields.one2many('product.putaway', 'location_id', 'Put Away Strategies'),
134 'loc_barcode': fields.char('Location barcode'),
139 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
143 'scrap_location': False,
145 _sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')]
147 def create(self, cr, uid, default, context=None):
148 if not default.get('loc_barcode', False):
149 default.update({'loc_barcode': default.get('complete_name', False)})
150 return super(stock_location,self).create(cr, uid, default, context=context)
152 def get_putaway_strategy(self, cr, uid, location, product, context=None):
153 pa = self.pool.get('product.putaway')
154 categ = product.categ_id
155 categs = [categ.id, False]
156 while categ.parent_id:
157 categ = categ.parent_id
158 categs.append(categ.id)
160 result = pa.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
162 return pa.browse(cr, uid, result[0], context=context)
164 def get_removal_strategy(self, cr, uid, location, product, context=None):
165 pr = self.pool.get('product.removal')
166 categ = product.categ_id
167 categs = [categ.id, False]
168 while categ.parent_id:
169 categ = categ.parent_id
170 categs.append(categ.id)
172 result = pr.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
174 return pr.browse(cr, uid, result[0], context=context).method
177 #----------------------------------------------------------
179 #----------------------------------------------------------
181 class stock_location_route(osv.osv):
182 _name = 'stock.location.route'
183 _description = "Inventory Routes"
187 'name': fields.char('Route Name', required=True),
188 'sequence': fields.integer('Sequence'),
189 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'),
190 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
191 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'),
192 'product_selectable': fields.boolean('Applicable on Product'),
193 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
194 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
195 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
196 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
197 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
201 'sequence': lambda self, cr, uid, ctx: 0,
203 'product_selectable': True,
204 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
208 #----------------------------------------------------------
210 #----------------------------------------------------------
212 class stock_quant(osv.osv):
214 Quants are the smallest unit of stock physical instances
216 _name = "stock.quant"
217 _description = "Quants"
219 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
220 """ Forms complete name of location from parent location to child location.
221 @return: Dictionary of values
224 for q in self.browse(cr, uid, ids, context=context):
226 res[q.id] = q.product_id.code or ''
228 res[q.id] = q.lot_id.name
229 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
232 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
234 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
235 for quant in self.browse(cr, uid, ids, context=context):
236 context.pop('force_company', None)
237 if quant.company_id.id != uid_company_id:
238 #if the company of the quant is different than the current user company, force the company in the context
239 #then re-do a browse to read the property fields for the good company.
240 context['force_company'] = quant.company_id.id
241 quant = self.browse(cr, uid, quant.id, context=context)
242 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
245 def _get_inventory_value(self, cr, uid, quant, context=None):
246 return quant.product_id.standard_price * quant.qty
249 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
250 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict"),
251 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict"),
252 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"),
253 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"),
254 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True),
255 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"),
256 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
257 'cost': fields.float('Unit Cost'),
258 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"),
260 'create_date': fields.datetime('Creation Date'),
261 'in_date': fields.datetime('Incoming Date'),
263 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
264 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True),
266 # Used for negative quants to reconcile after compensated by a new positive one
267 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'),
268 '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.'),
269 'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location",
270 help="Technical field used to record the destination location of a move that created a negative quant"),
271 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
275 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
278 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
279 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
280 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
281 if 'inventory_value' in fields:
283 if '__domain' in line:
284 lines = self.search(cr, uid, line['__domain'], context=context)
286 for line2 in self.browse(cr, uid, lines, context=context):
287 inv_value += line2.inventory_value
288 line['inventory_value'] = inv_value
291 def action_view_quant_history(self, cr, uid, ids, context=None):
293 This function returns an action that display the history of the quant, which
294 mean all the stock moves that lead to this quant creation with this quant quantity.
296 mod_obj = self.pool.get('ir.model.data')
297 act_obj = self.pool.get('ir.actions.act_window')
299 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
300 id = result and result[1] or False
301 result = act_obj.read(cr, uid, [id], context={})[0]
304 for quant in self.browse(cr, uid, ids, context=context):
305 move_ids += [move.id for move in quant.history_ids]
307 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
310 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
311 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
312 is also set to 'assigned'
314 :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
315 :param move: browse record
316 :param link: browse record (stock.move.operation.link)
319 reserved_availability = move.reserved_availability
320 #split quants if needed
321 for quant, qty in quants:
322 if qty <= 0.0 or (quant and quant.qty <= 0.0):
323 raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
326 self._quant_split(cr, uid, quant, qty, context=context)
327 toreserve.append(quant.id)
328 reserved_availability += quant.qty
331 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
332 #check if move'state needs to be set as 'assigned'
333 if reserved_availability == move.product_qty and move.state in ('confirmed', 'waiting'):
334 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
335 elif reserved_availability > 0 and not move.partially_available:
336 self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
338 def quants_move(self, cr, uid, quants, move, location_to, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
339 """Moves all given stock.quant in the given destination location.
340 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
341 :param move: browse record (stock.move)
342 :param location_to: browse record (stock.location) depicting where the quants have to be moved
343 :param lot_id: ID of the lot that must be set on the quants to move
344 :param owner_id: ID of the partner that must own the quants to move
345 :param src_package_id: ID of the package that contains the quants to move
346 :param dest_package_id: ID of the package that must be set on the moved quant
348 quants_reconcile = []
350 self._check_location(cr, uid, location_to, context=context)
351 for quant, qty in quants:
353 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
354 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=location_to, context=context)
356 self._quant_split(cr, uid, quant, qty, context=context)
358 to_move_quants.append(quant)
359 quants_reconcile.append(quant)
361 self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
362 if location_to.usage == 'internal':
363 if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context):
364 for quant in quants_reconcile:
366 self._quant_reconcile_negative(cr, uid, quant, move, context=context)
368 def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
369 vals = {'location_id': location_dest_id.id,
370 'history_ids': [(4, move.id)],
371 'package_id': dest_package_id}
372 self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
374 def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain=False, fallback_domain=False, restrict_lot_id=False, restrict_partner_id=False, context=None):
375 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
376 the choice on the quants that match the prefered_domain as well. But if the qty requested is not reached
377 it tries to find the remaining quantity by using the fallback_domain.
379 #don't look for quants in location that are of type production, supplier or inventory.
380 if location.usage in ['inventory', 'production', 'supplier']:
382 if prefered_domain and fallback_domain:
385 quants = self.quants_get(cr, uid, location, product, qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
390 quant_ids.append(quant[0].id)
393 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
395 #make sure the quants aren't found twice (if the prefered_domain and the fallback_domain aren't orthogonal
396 domain += [('id', 'not in', quant_ids)]
397 unprefered_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + fallback_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
398 for quant in unprefered_quants:
401 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)
403 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
405 Use the removal strategies of product to search for the correct quants
406 If you inherit, put the super at the end of your method.
408 :location: browse record of the parent location where the quants have to be found
409 :product: browse record of the product to find
410 :qty in UoM of product
413 domain = domain or [('qty', '>', 0.0)]
414 if restrict_partner_id:
415 domain += [('owner_id', '=', restrict_partner_id)]
417 domain += [('lot_id', '=', restrict_lot_id)]
419 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context) or 'fifo'
420 if removal_strategy == 'fifo':
421 result += self._quants_get_fifo(cr, uid, location, product, qty, domain, context=context)
422 elif removal_strategy == 'lifo':
423 result += self._quants_get_lifo(cr, uid, location, product, qty, domain, context=context)
425 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
428 def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, force_location=False, context=None):
429 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
433 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
434 location = force_location or move.location_dest_id
436 'product_id': move.product_id.id,
437 'location_id': location.id,
440 'history_ids': [(4, move.id)],
441 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
442 'company_id': move.company_id.id,
444 'owner_id': owner_id,
445 'package_id': dest_package_id,
448 if move.location_id.usage == 'internal':
449 #if we were trying to move something from an internal location and reach here (quant creation),
450 #it means that a negative quant has to be created as well.
451 negative_vals = vals.copy()
452 negative_vals['location_id'] = move.location_id.id
453 negative_vals['qty'] = -qty
454 negative_vals['cost'] = price_unit
455 negative_vals['negative_move_id'] = move.id
456 negative_vals['package_id'] = src_package_id
457 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
458 vals.update({'propagated_from_id': negative_quant_id})
460 #create the quant as superuser, because we want to restrict the creation of quant manually: they should always use this method to create quants
461 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
462 return self.browse(cr, uid, quant_id, context=context)
464 def _quant_split(self, cr, uid, quant, qty, context=None):
465 context = context or {}
466 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
468 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
469 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
471 return self.browse(cr, uid, new_quant, context=context)
473 def _get_latest_move(self, cr, uid, quant, context=None):
475 for m in quant.history_ids:
476 if not move or m.date > move.date:
480 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
482 for move in solving_quant.history_ids:
483 path.append((4, move.id))
484 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
486 def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
488 When new quant arrive in a location, try to reconcile it with
489 negative quants. If it's possible, apply the cost of the new
490 quant to the conter-part of the negative quant.
492 solving_quant = quant
493 dom = [('qty', '<', 0)]
495 dom += [('lot_id', '=', quant.lot_id.id)]
496 dom += [('owner_id', '=', quant.owner_id.id)]
497 dom += [('package_id', '=', quant.package_id.id)]
498 if move.move_dest_id:
499 dom += [('negative_move_id', '=', move.move_dest_id.id)]
500 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
501 for quant_neg, qty in quants:
504 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
505 if not to_solve_quant_ids:
508 solved_quant_ids = []
509 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
512 solved_quant_ids.append(to_solve_quant.id)
513 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
514 solving_qty -= min(solving_qty, to_solve_quant.qty)
515 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
516 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
517 #if the reconciliation was not complete, we need to link together the remaining parts
518 if remaining_neg_quant:
519 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
520 if remaining_to_solve_quant_ids:
521 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
522 #delete the reconciled quants, as it is replaced by the solved quants
523 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
524 #price update + accounting entries adjustments
525 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
526 #merge history (and cost?)
527 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
528 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
529 solving_quant = remaining_solving_quant
531 def _price_update(self, cr, uid, ids, newprice, context=None):
532 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
534 def quants_unreserve(self, cr, uid, move, context=None):
535 related_quants = [x.id for x in move.reserved_quant_ids]
537 if move.partially_available:
538 self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
539 return self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
541 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
542 ''' Implementation of removal strategies
543 If it can not reserve, it will return a tuple (None, qty)
547 domain += location and [('location_id', 'child_of', location.id)] or []
548 domain += [('product_id', '=', product.id)]
549 if context.get('force_company'):
550 domain += [('company_id', '=', context.get('force_company'))]
552 domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
556 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
558 res.append((None, quantity))
560 for quant in self.browse(cr, uid, quants, context=context):
561 if quantity >= abs(quant.qty):
562 res += [(quant, abs(quant.qty))]
563 quantity -= abs(quant.qty)
565 res += [(quant, quantity)]
571 def _quants_get_fifo(self, cr, uid, location, product, quantity, domain=[], context=None):
572 order = 'in_date, id'
573 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
575 def _quants_get_lifo(self, cr, uid, location, product, quantity, domain=[], context=None):
576 order = 'in_date desc, id desc'
577 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
579 def _check_location(self, cr, uid, location, context=None):
580 if location.usage == 'view':
581 raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
584 def _check_open_inventory_location(self, cr, uid, ids, context=None):
585 """ Check if there is an inventory running for the locations implied
587 inventory_obj = self.pool.get('stock.inventory')
588 for quant in self.browse(cr, uid, ids, context=context):
589 loc = quant.location_id
590 parent_location_ids = []
592 parent_location_ids.append(loc.id)
593 loc = loc.location_id
594 domain = [('state', '=', 'confirm'), ('location_id', 'in', parent_location_ids), '|', ('product_id', '=', False), ('product_id', '=', quant.product_id.id)]
595 domain += ['|', ('lot_id', '=', False), ('lot_id', '=', quant.lot_id.id)]
596 domain += ['|', ('partner_id', '=', False), ('partner_id', '=', quant.owner_id.id)]
597 domain += ['|', ('package_id', '=', False), ('package_id', '=', quant.package_id.id)]
598 inventory_ids = inventory_obj.search(cr, uid, domain, context=context)
600 inventory = inventory_obj.browse(cr, uid, inventory_ids[0], context=context)
601 raise osv.except_osv(_('Error! Location on inventory'),
602 _('There exists an inventory conflicting with your operation :\n%s') % inventory.name)
606 (_check_open_inventory_location,
607 "A Physical Inventory is being conducted at this location", ['location_id']),
610 def write(self, cr, uid, ids, vals, context=None):
611 #check the inventory constraint before the write
612 if isinstance(ids, (int, long)):
614 if 'owner_id' in vals or 'lot_id' in vals or 'package_id' in vals or 'location_id' in vals or 'product_id' in vals:
615 self._check_open_inventory_location(cr, uid, ids, context=context)
616 return super(stock_quant, self).write(cr, uid, ids, vals, context=context)
619 #----------------------------------------------------------
621 #----------------------------------------------------------
623 class stock_picking(osv.osv):
624 _name = "stock.picking"
625 _inherit = ['mail.thread']
626 _description = "Picking List"
627 _order = "priority desc, date asc, id desc"
629 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
630 move_obj = self.pool.get("stock.move")
632 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
633 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
635 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
636 """ Finds minimum and maximum dates for picking.
637 @return: Dictionary of values
641 res[id] = {'min_date': False, 'max_date': False}
653 picking_id""", (tuple(ids),))
654 for pick, dt1, dt2 in cr.fetchall():
655 res[pick]['min_date'] = dt1
656 res[pick]['max_date'] = dt2
659 def create(self, cr, user, vals, context=None):
660 context = context or {}
661 if ('name' not in vals) or (vals.get('name') in ('/', False)):
662 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
663 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
664 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
665 return super(stock_picking, self).create(cr, user, vals, context)
667 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
668 '''The state of a picking depends on the state of its related stock.move
669 draft: the picking has no line or any one of the lines is draft
670 done, draft, cancel: all lines are done / draft / cancel
671 confirmed, auto, assigned depends on move_type (all at once or direct)
674 for pick in self.browse(cr, uid, ids, context=context):
675 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
676 res[pick.id] = 'draft'
678 if all([x.state == 'cancel' for x in pick.move_lines]):
679 res[pick.id] = 'cancel'
681 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
682 res[pick.id] = 'done'
685 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
686 order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
687 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
688 if pick.move_type == 'one':
689 res[pick.id] = order_inv[min(lst)]
691 #we are in the case of partial delivery, so if all move are assigned, picking
692 #should be assign too, else if one of the move is assigned, or partially available, picking should be
693 #in partially available state, otherwise, picking is in waiting or confirmed state
694 res[pick.id] = order_inv[max(lst)]
695 if not all(x == 2 for x in lst):
696 #if all moves aren't assigned, check if we have one product partially available
697 for move in pick.move_lines:
698 if move.partially_available:
699 res[pick.id] = 'partially_available'
703 def _get_pickings(self, cr, uid, ids, context=None):
705 for move in self.browse(cr, uid, ids, context=context):
707 res.add(move.picking_id.id)
710 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
712 for pick in self.browse(cr, uid, ids, context=context):
714 if pick.pack_operation_ids:
718 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
720 for pick in self.browse(cr, uid, ids, context=context):
722 for move in pick.move_lines:
723 if move.reserved_quant_ids:
728 def action_assign_owner(self, cr, uid, ids, context=None):
729 for picking in self.browse(cr, uid, ids, context=context):
730 packop_ids = [op.id for op in picking.pack_operation_ids]
731 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
734 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
735 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
736 '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),
737 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
738 '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"),
739 'state': fields.function(_state_get, type="selection", store={
740 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
741 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)}, selection=[
743 ('cancel', 'Cancelled'),
744 ('waiting', 'Waiting Another Operation'),
745 ('confirmed', 'Waiting Availability'),
746 ('partially_available', 'Partially Available'),
747 ('assigned', 'Ready to Transfer'),
748 ('done', 'Transferred'),
749 ], string='Status', readonly=True, select=True, track_visibility='onchange', help="""
750 * Draft: not confirmed yet and will not be scheduled until confirmed\n
751 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
752 * Waiting Availability: still waiting for the availability of products\n
753 * Partially Available: some products are available and reserved\n
754 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
755 * Transferred: has been processed, can't be modified or cancelled anymore\n
756 * Cancelled: has been cancelled, can't be confirmed anymore"""
758 'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Priority', required=True),
759 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
760 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'),
761 'max_date': fields.function(get_min_max_date, multi="min_max_date",
762 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"),
763 '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'),
764 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
765 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
766 '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'),
767 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
768 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
769 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
770 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
771 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
772 '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"),
774 'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
775 # Used to search on pickings
776 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
777 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
778 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
779 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
781 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
782 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
787 'name': lambda self, cr, uid, context: '/',
790 'priority': '1', # normal
791 'date': fields.datetime.now,
792 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
795 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
798 def copy(self, cr, uid, id, default=None, context=None):
801 default = default.copy()
802 picking_obj = self.browse(cr, uid, id, context=context)
803 if ('name' not in default) or (picking_obj.name == '/'):
804 default['name'] = '/'
805 if not default.get('backorder_id'):
806 default['backorder_id'] = False
807 default['pack_operation_ids'] = []
808 default['date_done'] = False
809 return super(stock_picking, self).copy(cr, uid, id, default, context)
812 def do_print_picking(self, cr, uid, ids, context=None):
813 '''This function prints the picking list'''
814 return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
816 def action_confirm(self, cr, uid, ids, context=None):
818 todo_force_assign = []
819 for picking in self.browse(cr, uid, ids, context=context):
820 if picking.picking_type_id.auto_force_assign:
821 todo_force_assign.append(picking.id)
822 for r in picking.move_lines:
823 if r.state == 'draft':
826 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
828 if todo_force_assign:
829 self.force_assign(cr, uid, todo_force_assign, context=context)
832 def action_assign(self, cr, uid, ids, context=None):
833 """ Check availability of picking moves.
834 This has the effect of changing the state and reserve quants on available moves, and may
835 also impact the state of the picking as it is computed based on move's states.
838 for pick in self.browse(cr, uid, ids, context=context):
839 if pick.state == 'draft':
840 self.action_confirm(cr, uid, [pick.id], context=context)
842 #skip the moves that don't need to be checked
843 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
845 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
846 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
849 def force_assign(self, cr, uid, ids, context=None):
850 """ Changes state of picking to available if moves are confirmed or waiting.
853 for pick in self.browse(cr, uid, ids, context=context):
854 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
855 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
858 def action_cancel(self, cr, uid, ids, context=None):
859 for pick in self.browse(cr, uid, ids, context=context):
860 ids2 = [move.id for move in pick.move_lines]
861 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
864 def action_done(self, cr, uid, ids, context=None):
865 """Changes picking state to done by processing the Stock Moves of the Picking
867 Normally that happens when the button "Done" is pressed on a Picking view.
870 for pick in self.browse(cr, uid, ids, context=context):
872 for move in pick.move_lines:
873 if move.state == 'draft':
874 todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
875 elif move.state in ('assigned', 'confirmed'):
878 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
881 def unlink(self, cr, uid, ids, context=None):
882 #on picking deletion, cancel its move then unlink them too
883 move_obj = self.pool.get('stock.move')
884 context = context or {}
885 for pick in self.browse(cr, uid, ids, context=context):
886 move_ids = [move.id for move in pick.move_lines]
887 move_obj.action_cancel(cr, uid, move_ids, context=context)
888 move_obj.unlink(cr, uid, move_ids, context=context)
889 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
891 def write(self, cr, uid, ids, vals, context=None):
892 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
893 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
894 if 'move_lines' in vals or 'pack_operation_ids' in vals:
895 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
898 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
899 """ 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.
901 if not backorder_moves:
902 backorder_moves = picking.move_lines
903 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
904 if 'do_only_split' in context and context['do_only_split']:
905 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
907 if backorder_move_ids:
908 backorder_id = self.copy(cr, uid, picking.id, {
911 'pack_operation_ids': [],
912 'backorder_id': picking.id,
914 back_order_name = self.browse(cr, uid, backorder_id, context=context).name
915 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (back_order_name), context=context)
916 move_obj = self.pool.get("stock.move")
917 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
919 self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
920 self.action_confirm(cr, uid, [backorder_id], context=context)
924 def recheck_availability(self, cr, uid, picking_ids, context=None):
925 self.action_assign(cr, uid, picking_ids, context=context)
926 self.do_prepare_partial(cr, uid, picking_ids, context=context)
928 def _picking_putaway_resolution(self, cr, uid, picking, product, putaway, context=None):
929 if putaway.method == 'fixed' and putaway.location_spec_id:
930 return putaway.location_spec_id.id
933 def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
934 """This method searches for the higher level packages that can be moved as a single operation, given a list of quants
935 to move and their suggested destination, and returns the list of matching packages.
937 # Try to find as much as possible top-level packages that can be moved
938 pack_obj = self.pool.get("stock.quant.package")
939 quant_obj = self.pool.get("stock.quant")
940 top_lvl_packages = set()
941 quants_to_compare = quants_suggested_locations.keys()
942 for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
946 pack_destination = False
948 pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
950 for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
951 # If the quant is not in the quants to compare and not in the common location
952 if not quant in quants_to_compare:
956 #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)
957 if not pack_destination:
958 pack_destination = quants_suggested_locations[quant]
959 elif pack_destination != quants_suggested_locations[quant]:
963 good_pack = test_pack
964 if test_pack.parent_id:
965 test_pack = test_pack.parent_id
967 #stop the loop when there's no parent package anymore
970 #stop the loop when the package test_pack is not totally reserved for moves of this picking
971 #(some quants may be reserved for other picking or not reserved at all)
974 top_lvl_packages.add(good_pack)
975 return list(top_lvl_packages)
977 def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
978 """ returns a list of dict, ready to be used in create() of stock.pack.operation.
980 :param picking: browse record (stock.picking)
981 :param quants: browse record list (stock.quant). List of quants associated to the picking
982 :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
984 def _picking_putaway_apply(product):
986 # Search putaway strategy
987 if product_putaway_strats.get(product.id):
988 putaway_strat = product_putaway_strats[product.id]
990 putaway_strat = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
991 product_putaway_strats[product.id] = putaway_strat
993 location = self._picking_putaway_resolution(cr, uid, picking, product, putaway_strat, context=context)
994 return location or picking.picking_type_id.default_location_dest_id.id or picking.location_dest_id.id
996 pack_obj = self.pool.get("stock.quant.package")
997 quant_obj = self.pool.get("stock.quant")
1000 #for each quant of the picking, find the suggested location
1001 quants_suggested_locations = {}
1002 product_putaway_strats = {}
1003 for quant in quants:
1006 suggested_location_id = _picking_putaway_apply(quant.product_id)
1007 quants_suggested_locations[quant] = suggested_location_id
1009 #find the packages we can movei as a whole
1010 top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
1011 # and then create pack operations for the top-level packages found
1012 for pack in top_lvl_packages:
1013 pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
1014 pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
1016 'picking_id': picking.id,
1017 'package_id': pack.id,
1019 'location_id': pack.location_id.id,
1020 'location_dest_id': quants_suggested_locations[pack_quants[0]],
1022 #remove the quants inside the package so that they are excluded from the rest of the computation
1023 for quant in pack_quants:
1024 del quants_suggested_locations[quant]
1026 # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
1027 for quant, dest_location_id in quants_suggested_locations.items():
1028 key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
1029 if qtys_grouped.get(key):
1030 qtys_grouped[key] += quant.qty
1032 qtys_grouped[key] = quant.qty
1034 # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
1035 for product, qty in forced_qties.items():
1038 suggested_location_id = _picking_putaway_apply(product)
1039 key = (product.id, False, False, False, picking.picking_type_id.default_location_src_id.id or picking.location_id.id, suggested_location_id)
1040 if qtys_grouped.get(key):
1041 qtys_grouped[key] += qty
1043 qtys_grouped[key] = qty
1045 # Create the necessary operations for the grouped quants and remaining qtys
1046 for key, qty in qtys_grouped.items():
1048 'picking_id': picking.id,
1050 'product_id': key[0],
1051 'package_id': key[1],
1054 'location_id': key[4],
1055 'location_dest_id': key[5],
1056 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id,
1060 def open_barcode_interface(self, cr, uid, picking_ids, context=None):
1061 final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0])
1062 return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
1064 def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
1065 self.do_prepare_partial(cr, uid, picking_ids, context=context)
1066 return self.open_barcode_interface(cr, uid, picking_ids, context=context)
1068 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
1069 context = context or {}
1070 pack_operation_obj = self.pool.get('stock.pack.operation')
1071 #used to avoid recomputing the remaining quantities at each new pack operation created
1072 ctx = context.copy()
1073 ctx['no_recompute'] = True
1075 #get list of existing operations and delete them
1076 existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
1077 if existing_package_ids:
1078 pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
1079 for picking in self.browse(cr, uid, picking_ids, context=context):
1080 forced_qties = {} # Quantity remaining after calculating reserved quants
1082 #Calculate packages, reserved quants, qtys of this picking's moves
1083 for move in picking.move_lines:
1084 if move.state not in ('assigned', 'confirmed'):
1086 move_quants = move.reserved_quant_ids
1087 picking_quants += move_quants
1088 forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
1089 #if we used force_assign() on the move, or if the move is incomming, forced_qty > 0
1091 if forced_qties.get(move.product_id):
1092 forced_qties[move.product_id] += forced_qty
1094 forced_qties[move.product_id] = forced_qty
1095 for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
1096 pack_operation_obj.create(cr, uid, vals, context=ctx)
1097 #recompute the remaining quantities all at once
1098 self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
1100 def do_unreserve(self, cr, uid, picking_ids, context=None):
1102 Will remove all quants for picking in picking_ids
1104 moves_to_unreserve = []
1105 pack_line_to_unreserve = []
1106 for picking in self.browse(cr, uid, picking_ids, context=context):
1107 moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
1108 pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
1109 if moves_to_unreserve:
1110 if pack_line_to_unreserve:
1111 self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
1112 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
1114 def recompute_remaining_qty(self, cr, uid, picking, context=None):
1115 def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
1116 move_dict = prod2move_ids[product_id][index]
1117 qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
1118 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)
1119 if move_dict['remaining_qty'] == qty_on_link:
1120 prod2move_ids[product_id].pop(index)
1122 move_dict['remaining_qty'] -= qty_on_link
1125 def _create_link_for_quant(operation_id, quant, qty):
1126 """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
1127 if not quant.reservation_id.id:
1128 return _create_link_for_product(operation_id, quant.product_id.id, qty)
1130 for i in range(0, len(prod2move_ids[quant.product_id.id])):
1131 if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
1133 qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
1137 def _create_link_for_product(operation_id, product_id, qty):
1138 '''method that creates the link between a given operation and move(s) of given product, for the given quantity.
1139 Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
1141 if prod2move_ids.get(product_id):
1142 while prod2move_ids[product_id] and qty_to_assign > 0:
1143 qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
1144 qty_to_assign -= qty_on_link
1145 return qty_to_assign == 0
1147 uom_obj = self.pool.get('product.uom')
1148 package_obj = self.pool.get('stock.quant.package')
1149 quant_obj = self.pool.get('stock.quant')
1150 quants_in_package_done = set()
1153 #make a dictionary giving for each product, the moves and related quantity that can be used in operation links
1154 for move in picking.move_lines:
1155 if not prod2move_ids.get(move.product_id.id):
1156 prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
1158 prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
1160 need_rereserve = False
1161 #sort the operations in order to give higher priority to those with a package, then a serial number
1162 operations = picking.pack_operation_ids
1163 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))
1164 #delete existing operations to start again from scratch
1165 cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),))
1167 #1) first, try to create links when quants can be identified without any doubt
1168 for ops in operations:
1169 #for each operation, create the links with the stock move by seeking on the matching reserved quants,
1170 #and deffer the operation if there is some ambiguity on the move to select
1171 if ops.package_id and not ops.product_id:
1173 quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
1174 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1175 remaining_qty_on_quant = quant.qty
1176 if quant.reservation_id:
1177 #avoid quants being counted twice
1178 quants_in_package_done.add(quant.id)
1179 qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
1180 remaining_qty_on_quant -= qty_on_link
1181 if remaining_qty_on_quant:
1182 still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
1183 need_rereserve = True
1184 elif ops.product_id.id:
1185 #Check moves with same product
1186 qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
1187 for move_dict in prod2move_ids.get(ops.product_id.id, []):
1188 move = move_dict['move']
1189 for quant in move.reserved_quant_ids:
1190 if not qty_to_assign > 0:
1192 if quant.id in quants_in_package_done:
1195 #check if the quant is matching the operation details
1197 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
1199 flag = not quant.package_id.id
1200 flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
1201 flag = flag and (ops.owner_id.id == quant.owner_id.id)
1203 max_qty_on_link = min(quant.qty, qty_to_assign)
1204 qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
1205 qty_to_assign -= qty_on_link
1206 if qty_to_assign > 0:
1207 #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
1208 #all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
1209 still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
1210 need_rereserve = True
1212 #2) then, process the remaining part
1213 all_op_processed = True
1214 for ops, product_id, remaining_qty in still_to_do:
1215 all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty)
1216 return (need_rereserve, all_op_processed)
1218 def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
1219 need_rereserve = False
1220 all_op_processed = True
1221 if picking.pack_operation_ids:
1222 need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
1223 return need_rereserve, all_op_processed
1225 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
1226 for picking in self.browse(cr, uid, picking_ids, context=context):
1227 if picking.pack_operation_ids:
1228 self.recompute_remaining_qty(cr, uid, picking, context=context)
1230 def _create_extra_moves(self, cr, uid, picking, context=None):
1231 '''This function creates move lines on a picking, at the time of do_transfer, based on
1232 unexpected product transfers (or exceeding quantities) found in the pack operations.
1234 move_obj = self.pool.get('stock.move')
1235 operation_obj = self.pool.get('stock.pack.operation')
1236 for op in picking.pack_operation_ids:
1237 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1238 if remaining_qty > 0:
1239 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1241 'picking_id': picking.id,
1242 'location_id': picking.location_id.id,
1243 'location_dest_id': picking.location_dest_id.id,
1244 'product_id': product_id,
1245 'product_uom': product.uom_id.id,
1246 'product_uom_qty': remaining_qty,
1247 'name': _('Extra Move: ') + product.name,
1248 'state': 'confirmed',
1250 move_obj.create(cr, uid, vals, context=context)
1252 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1253 """ Unreserve quants then try to reassign quants."""
1254 stock_move_obj = self.pool.get('stock.move')
1256 self.do_unreserve(cr, uid, [picking.id], context=context)
1257 self.action_assign(cr, uid, [picking.id], context=context)
1259 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1260 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1262 def do_transfer(self, cr, uid, picking_ids, context=None):
1264 If no pack operation, we do simple action_done of the picking
1265 Otherwise, do the pack operations
1269 stock_move_obj = self.pool.get('stock.move')
1270 for picking in self.browse(cr, uid, picking_ids, context=context):
1271 if not picking.pack_operation_ids:
1272 self.action_done(cr, uid, [picking.id], context=context)
1275 need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
1276 #create extra moves in the picking (unexpected product moves coming from pack operations)
1277 if not all_op_processed:
1278 self._create_extra_moves(cr, uid, picking, context=context)
1280 #split move lines eventually
1282 toassign_move_ids = []
1283 for move in picking.move_lines:
1284 remaining_qty = move.remaining_qty
1285 if move.state in ('done', 'cancel'):
1286 #ignore stock moves cancelled or already done
1288 elif move.state == 'draft':
1289 toassign_move_ids.append(move.id)
1290 if remaining_qty == 0:
1291 if move.state in ('draft', 'assigned', 'confirmed'):
1292 todo_move_ids.append(move.id)
1293 elif remaining_qty > 0 and remaining_qty < move.product_qty:
1294 new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
1295 todo_move_ids.append(move.id)
1296 #Assign move as it was assigned before
1297 toassign_move_ids.append(new_move)
1298 if (need_rereserve or not all_op_processed) and not picking.location_id.usage in ("supplier", "production", "inventory"):
1299 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1300 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1301 if todo_move_ids and not context.get('do_only_split'):
1302 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1303 elif context.get('do_only_split'):
1304 context.update({'split': todo_move_ids})
1306 self._create_backorder(cr, uid, picking, context=context)
1307 if toassign_move_ids:
1308 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1311 def do_split(self, cr, uid, picking_ids, context=None):
1312 """ just split the picking (create a backorder) without making it 'done' """
1315 ctx = context.copy()
1316 ctx['do_only_split'] = True
1317 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1319 def get_next_picking_for_ui(self, cr, uid, context=None):
1320 """ returns the next pickings to process. Used in the barcode scanner UI"""
1323 domain = [('state', 'in', ('assigned', 'partially_available'))]
1324 if context.get('default_picking_type_id'):
1325 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1326 return self.search(cr, uid, domain, context=context)
1328 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1329 """ called when button 'done' is pushed in the barcode scanner UI """
1330 #write qty_done into field product_qty for every package_operation before doing the transfer
1331 pack_op_obj = self.pool.get('stock.pack.operation')
1332 for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
1333 pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
1334 self.do_transfer(cr, uid, [picking_id], context=context)
1335 #return id of next picking to work on
1336 return self.get_next_picking_for_ui(cr, uid, context=context)
1338 def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
1339 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1340 Used in the barcode scanner UI and the normal interface as well.
1341 operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
1342 if operation_filter_ids == None:
1343 operation_filter_ids = []
1344 stock_operation_obj = self.pool.get('stock.pack.operation')
1345 package_obj = self.pool.get('stock.quant.package')
1346 stock_move_obj = self.pool.get('stock.move')
1347 for picking_id in picking_ids:
1348 operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
1349 if operation_filter_ids != []:
1350 operation_search_domain.append(('id', 'in', operation_filter_ids))
1351 operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
1352 pack_operation_ids = []
1354 for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
1355 #If we haven't done all qty in operation, we have to split into 2 operation
1357 if (operation.qty_done < operation.product_qty):
1358 new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
1359 stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0}, context=context)
1360 op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
1361 pack_operation_ids.append(op.id)
1362 for record in op.linked_move_operation_ids:
1363 stock_move_obj.check_tracking(cr, uid, record.move_id, op.package_id.id or op.lot_id.id, context=context)
1364 package_id = package_obj.create(cr, uid, {}, context=context)
1365 stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
1368 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
1369 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)
1371 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
1372 '''This function is called each time there barcode scanner reads an input'''
1373 lot_obj = self.pool.get('stock.production.lot')
1374 package_obj = self.pool.get('stock.quant.package')
1375 product_obj = self.pool.get('product.product')
1376 stock_operation_obj = self.pool.get('stock.pack.operation')
1377 stock_location_obj = self.pool.get('stock.location')
1378 answer = {'filter_loc': False, 'operation_id': False}
1379 #check if the barcode correspond to a location
1380 matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context)
1381 if matching_location_ids:
1382 #if we have a location, return immediatly with the location name
1383 location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
1384 answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
1385 answer['filter_loc_id'] = matching_location_ids[0]
1387 #check if the barcode correspond to a product
1388 matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context)
1389 if matching_product_ids:
1390 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)
1391 answer['operation_id'] = op_id
1393 #check if the barcode correspond to a lot
1394 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1395 if matching_lot_ids:
1396 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1397 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)
1398 answer['operation_id'] = op_id
1400 #check if the barcode correspond to a package
1401 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1402 if matching_package_ids:
1403 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)
1404 answer['operation_id'] = op_id
1409 class stock_production_lot(osv.osv):
1410 _name = 'stock.production.lot'
1411 _inherit = ['mail.thread']
1412 _description = 'Lot/Serial'
1414 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1415 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1416 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1417 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants'),
1418 'create_date': fields.datetime('Creation Date'),
1421 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1422 'product_id': lambda x, y, z, c: c.get('product_id', False),
1424 _sql_constraints = [
1425 ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1428 def action_traceability(self, cr, uid, ids, context=None):
1429 """ It traces the information of lots
1430 @param self: The object pointer.
1431 @param cr: A database cursor
1432 @param uid: ID of the user currently logged in
1433 @param ids: List of IDs selected
1434 @param context: A standard dictionary
1435 @return: A dictionary of values
1437 quant_obj = self.pool.get("stock.quant")
1438 quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1440 for quant in quant_obj.browse(cr, uid, quants, context=context):
1441 moves |= {move.id for move in quant.history_ids}
1444 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
1445 'name': _('Traceability'),
1446 'view_mode': 'tree,form',
1447 'view_type': 'form',
1448 'context': {'tree_view_ref': 'stock.view_move_tree'},
1449 'res_model': 'stock.move',
1450 'type': 'ir.actions.act_window',
1455 # ----------------------------------------------------
1457 # ----------------------------------------------------
1459 class stock_move(osv.osv):
1460 _name = "stock.move"
1461 _description = "Stock Move"
1462 _order = 'date_expected desc, id'
1465 def get_price_unit(self, cr, uid, move, context=None):
1466 """ Returns the unit price to store on the quant """
1467 return move.price_unit or move.product_id.standard_price
1469 def name_get(self, cr, uid, ids, context=None):
1471 for line in self.browse(cr, uid, ids, context=context):
1472 name = line.location_id.name + ' > ' + line.location_dest_id.name
1473 if line.product_id.code:
1474 name = line.product_id.code + ': ' + name
1475 if line.picking_id.origin:
1476 name = line.picking_id.origin + '/ ' + name
1477 res.append((line.id, name))
1480 def create(self, cr, uid, vals, context=None):
1481 if vals.get('product_id') and not vals.get('price_unit'):
1482 prod_obj = self.pool.get('product.product')
1483 vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price
1484 return super(stock_move, self).create(cr, uid, vals, context=context)
1486 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1487 uom_obj = self.pool.get('product.uom')
1489 for m in self.browse(cr, uid, ids, context=context):
1490 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)
1493 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1494 uom_obj = self.pool.get('product.uom')
1496 for move in self.browse(cr, uid, ids, context=context):
1497 qty = move.product_qty
1498 for record in move.linked_move_operation_ids:
1500 #converting the remaining quantity in the move UoM
1501 res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context)
1504 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1505 res = dict.fromkeys(ids, False)
1506 for move in self.browse(cr, uid, ids, context=context):
1507 if move.state == 'done':
1508 res[move.id] = [q.id for q in move.quant_ids]
1510 res[move.id] = [q.id for q in move.reserved_quant_ids]
1513 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1514 quant_obj = self.pool.get('stock.quant')
1515 res = dict.fromkeys(ids, False)
1516 for move in self.browse(cr, uid, ids, context=context):
1517 if move.state == 'done':
1518 res[move.id] = move.product_qty
1520 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1521 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1523 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1524 availability += quant.qty
1525 res[move.id] = min(move.product_qty, availability)
1528 def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
1529 settings_obj = self.pool.get('stock.config.settings')
1530 uom_obj = self.pool.get('product.uom')
1531 res = dict.fromkeys(ids, '')
1532 for move in self.browse(cr, uid, ids, context=context):
1533 if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
1534 res[move.id] = '' # 'not applicable' or 'n/a' could work too
1536 total_available = min(move.product_qty, move.reserved_availability + move.availability)
1537 total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
1538 info = str(total_available)
1539 #look in the settings if we need to display the UoM name or not
1540 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1542 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1543 if stock_settings.group_uom:
1544 info += ' ' + move.product_uom.name
1545 if move.reserved_availability:
1546 if move.reserved_availability != total_available:
1547 #some of the available quantity is assigned and some are available but not reserved
1548 reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
1549 info += _(' (%s reserved)') % str(reserved_available)
1551 #all available quantity is assigned
1552 info += _(' (reserved)')
1556 def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
1557 res = dict.fromkeys(ids, 0)
1558 for move in self.browse(cr, uid, ids, context=context):
1559 res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
1562 def _get_move(self, cr, uid, ids, context=None):
1564 for quant in self.browse(cr, uid, ids, context=context):
1565 if quant.reservation_id:
1566 res.add(quant.reservation_id.id)
1569 def _get_move_ids(self, cr, uid, ids, context=None):
1571 for picking in self.browse(cr, uid, ids, context=context):
1572 res += [x.id for x in picking.move_lines]
1576 'name': fields.char('Description', required=True, select=True),
1577 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1578 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1579 '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)]}),
1580 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1581 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1582 # TODO: improve store to add dependency on product UoM
1583 'product_qty': fields.function(_quantity_normalize, type='float', store={'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_uom_qty', 'product_uom'], 20)}, string='Quantity',
1584 digits_compute=dp.get_precision('Product Unit of Measure'),
1585 help='Quantity in the default UoM of the product'),
1586 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1587 required=True, states={'done': [('readonly', True)]},
1588 help="This is the quantity of products from an inventory "
1589 "point of view. For moves in the state 'done', this is the "
1590 "quantity of products that were actually moved. For other "
1591 "moves, this is the quantity of product that is planned to "
1592 "be moved. Lowering this quantity does not generate a "
1593 "backorder. Changing this quantity on assigned moves affects "
1594 "the product reservation, and should be done with care."
1596 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1597 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1598 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1600 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1602 '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."),
1603 '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."),
1605 # FP Note: should we remove this?
1606 '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"),
1609 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1610 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1612 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1613 'picking_priority': fields.related('picking_id', 'priority', type='selection', selection=[('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Picking Priority', store={'stock.picking': (_get_move_ids, ['priority'], 10)}),
1614 'note': fields.text('Notes'),
1615 'state': fields.selection([('draft', 'New'),
1616 ('cancel', 'Cancelled'),
1617 ('waiting', 'Waiting Another Move'),
1618 ('confirmed', 'Waiting Availability'),
1619 ('assigned', 'Available'),
1621 ], 'Status', readonly=True, select=True,
1622 help= "* New: When the stock move is created and not yet confirmed.\n"\
1623 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1624 "* 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"\
1625 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1626 "* Done: When the shipment is processed, the state is \'Done\'."),
1627 'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved"),
1628 '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
1630 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1631 '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"),
1632 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1633 'origin': fields.char("Source"),
1634 'procure_method': fields.selection([('make_to_stock', 'Make to Stock'), ('make_to_order', 'Make to Order')], 'Procurement Method', required=True, help="Make to Stock: When needed, the product is taken from the stock or we wait for replenishment. \nMake to Order: When needed, the product is purchased or produced."),
1636 # used for colors in tree views:
1637 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1639 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1640 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1641 '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'),
1642 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1643 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1644 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1645 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1646 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1647 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1648 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1649 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1650 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1651 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'),
1652 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1653 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1654 'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
1655 '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'),
1656 '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'),
1657 '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'"),
1658 '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'"),
1659 '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"),
1660 '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)."),
1663 def _default_location_destination(self, cr, uid, context=None):
1664 context = context or {}
1665 if context.get('default_picking_type_id', False):
1666 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1667 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1670 def _default_location_source(self, cr, uid, context=None):
1671 context = context or {}
1672 if context.get('default_picking_type_id', False):
1673 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1674 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1677 def _default_destination_address(self, cr, uid, context=None):
1678 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1679 return user.company_id.partner_id.id
1682 'location_id': _default_location_source,
1683 'location_dest_id': _default_location_destination,
1684 'partner_id': _default_destination_address,
1688 'product_uom_qty': 1.0,
1690 'date': fields.datetime.now,
1691 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1692 'date_expected': fields.datetime.now,
1693 'procure_method': 'make_to_stock',
1697 def _check_uom(self, cr, uid, ids, context=None):
1698 for move in self.browse(cr, uid, ids, context=context):
1699 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1705 '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.',
1709 def copy_data(self, cr, uid, id, default=None, context=None):
1712 default = default.copy()
1713 default['move_orig_ids'] = []
1714 default['quant_ids'] = []
1715 default['move_dest_id'] = False
1716 default['reserved_quant_ids'] = []
1717 default['returned_move_ids'] = []
1718 default['linked_move_operation_ids'] = []
1719 if not default.get('origin_returned_move_id'):
1720 default['origin_returned_move_id'] = False
1721 default['state'] = 'draft'
1722 return super(stock_move, self).copy_data(cr, uid, id, default, context)
1724 def do_unreserve(self, cr, uid, move_ids, context=None):
1725 quant_obj = self.pool.get("stock.quant")
1726 for move in self.browse(cr, uid, move_ids, context=context):
1727 if move.state in ('done', 'cancel'):
1728 raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
1729 quant_obj.quants_unreserve(cr, uid, move, context=context)
1730 self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
1732 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1733 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1734 group_id = move.group_id and move.group_id.id or False
1736 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1737 group_id = move.rule_id.group_id.id
1738 elif move.rule_id.group_propagation_option == 'none':
1741 'name': move.rule_id and move.rule_id.name or "/",
1743 'company_id': move.company_id and move.company_id.id or False,
1744 'date_planned': move.date,
1745 'product_id': move.product_id.id,
1746 'product_qty': move.product_qty,
1747 'product_uom': move.product_uom.id,
1748 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1749 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1750 'location_id': move.location_id.id,
1751 'move_dest_id': move.id,
1752 'group_id': group_id,
1753 'route_ids': [(4, x.id) for x in move.route_ids],
1754 'warehouse_id': move.warehouse_id and move.warehouse_id.id or False,
1757 def _push_apply(self, cr, uid, moves, context=None):
1758 push_obj = self.pool.get("stock.location.path")
1760 #1) if the move is already chained, there is no need to check push rules
1761 #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
1762 # to receive goods without triggering the push rules again (which would duplicate chained operations)
1763 if not move.move_dest_id and not move.origin_returned_move_id:
1764 domain = [('location_from_id', '=', move.location_dest_id.id)]
1765 if move.warehouse_id:
1766 domain += ['|', ('warehouse_id', '=', move.warehouse_id.id), ('warehouse_id', '=', False)]
1767 #priority goes to the route defined on the product and product category
1768 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1769 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1771 #but if there's no rule matching, we try without filtering on routes
1772 rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context)
1774 rule = push_obj.browse(cr, uid, rules[0], context=context)
1775 push_obj._apply(cr, uid, rule, move, context=context)
1778 def _create_procurement(self, cr, uid, move, context=None):
1779 """ This will create a procurement order """
1780 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1782 def write(self, cr, uid, ids, vals, context=None):
1785 if isinstance(ids, (int, long)):
1787 # Check that we do not modify a stock.move which is done
1788 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1789 for move in self.browse(cr, uid, ids, context=context):
1790 if move.state == 'done':
1791 if frozen_fields.intersection(vals):
1792 raise osv.except_osv(_('Operation Forbidden!'),
1793 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1794 propagated_changes_dict = {}
1795 #propagation of quantity change
1796 if vals.get('product_uom_qty'):
1797 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1798 if vals.get('product_uom_id'):
1799 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1800 #propagation of expected date:
1801 propagated_date_field = False
1802 if vals.get('date_expected'):
1803 #propagate any manual change of the expected date
1804 propagated_date_field = 'date_expected'
1805 elif (vals.get('state', '') == 'done' and vals.get('date')):
1806 #propagate also any delta observed when setting the move as done
1807 propagated_date_field = 'date'
1809 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1810 #any propagation is (maybe) needed
1811 for move in self.browse(cr, uid, ids, context=context):
1812 if move.move_dest_id and move.propagate:
1813 if 'date_expected' in propagated_changes_dict:
1814 propagated_changes_dict.pop('date_expected')
1815 if propagated_date_field:
1816 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1817 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1818 delta = new_date - current_date
1819 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1820 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1821 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1822 propagated_changes_dict['date_expected'] = new_move_date
1823 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1824 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1825 if propagated_changes_dict:
1826 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1827 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1829 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1830 """ On change of product quantity finds UoM and UoS quantities
1831 @param product_id: Product id
1832 @param product_qty: Changed Quantity of product
1833 @param product_uom: Unit of measure of product
1834 @param product_uos: Unit of sale of product
1835 @return: Dictionary of values
1838 'product_uos_qty': 0.00
1842 if (not product_id) or (product_qty <= 0.0):
1843 result['product_qty'] = 0.0
1844 return {'value': result}
1846 product_obj = self.pool.get('product.product')
1847 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1849 # Warn if the quantity was decreased
1851 for move in self.read(cr, uid, ids, ['product_qty']):
1852 if product_qty < move['product_qty']:
1854 'title': _('Information'),
1855 'message': _("By changing this quantity here, you accept the "
1856 "new quantity as complete: OpenERP will not "
1857 "automatically generate a back order.")})
1860 if product_uos and product_uom and (product_uom != product_uos):
1861 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1863 result['product_uos_qty'] = product_qty
1865 return {'value': result, 'warning': warning}
1867 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1868 product_uos, product_uom):
1869 """ On change of product quantity finds UoM and UoS quantities
1870 @param product_id: Product id
1871 @param product_uos_qty: Changed UoS Quantity of product
1872 @param product_uom: Unit of measure of product
1873 @param product_uos: Unit of sale of product
1874 @return: Dictionary of values
1877 'product_uom_qty': 0.00
1881 if (not product_id) or (product_uos_qty <= 0.0):
1882 result['product_uos_qty'] = 0.0
1883 return {'value': result}
1885 product_obj = self.pool.get('product.product')
1886 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1888 # Warn if the quantity was decreased
1889 for move in self.read(cr, uid, ids, ['product_uos_qty']):
1890 if product_uos_qty < move['product_uos_qty']:
1892 'title': _('Warning: No Back Order'),
1893 'message': _("By changing the quantity here, you accept the "
1894 "new quantity as complete: OpenERP will not "
1895 "automatically generate a Back Order.")})
1898 if product_uos and product_uom and (product_uom != product_uos):
1899 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1901 result['product_uom_qty'] = product_uos_qty
1902 return {'value': result, 'warning': warning}
1904 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1905 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1906 @param prod_id: Changed Product id
1907 @param loc_id: Source location id
1908 @param loc_dest_id: Destination location id
1909 @param partner_id: Address id of partner
1910 @return: Dictionary of values
1914 user = self.pool.get('res.users').browse(cr, uid, uid)
1915 lang = user and user.lang or False
1917 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1919 lang = addr_rec and addr_rec.lang or False
1920 ctx = {'lang': lang}
1922 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1923 uos_id = product.uos_id and product.uos_id.id or False
1925 'product_uom': product.uom_id.id,
1926 'product_uos': uos_id,
1927 'product_uom_qty': 1.00,
1928 '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'],
1931 result['name'] = product.partner_ref
1933 result['location_id'] = loc_id
1935 result['location_dest_id'] = loc_dest_id
1936 return {'value': result}
1938 def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
1939 """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
1940 (and company). Those attributes are also given as parameters.
1942 pick_obj = self.pool.get("stock.picking")
1943 picks = pick_obj.search(cr, uid, [
1944 ('group_id', '=', procurement_group),
1945 ('location_id', '=', location_from),
1946 ('location_dest_id', '=', location_to),
1947 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1951 move = self.browse(cr, uid, move_ids, context=context)[0]
1953 'origin': move.origin,
1954 'company_id': move.company_id and move.company_id.id or False,
1955 'move_type': move.group_id and move.group_id.move_type or 'one',
1956 'partner_id': move.group_id and move.group_id.partner_id and move.group_id.partner_id.id or False,
1957 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1959 pick = pick_obj.create(cr, uid, values, context=context)
1960 return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
1962 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1963 """ On change of Scheduled Date gives a Move date.
1964 @param date_expected: Scheduled Date
1965 @param date: Move Date
1968 if not date_expected:
1969 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1970 return {'value': {'date': date_expected}}
1972 def action_confirm(self, cr, uid, ids, context=None):
1973 """ Confirms stock move or put it in waiting if it's linked to another move.
1974 @return: List of ids.
1976 if isinstance(ids, (int, long)):
1983 for move in self.browse(cr, uid, ids, context=context):
1985 #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)
1986 if move.move_orig_ids:
1988 #if the move is split and some of the ancestor was preceeded, then it's waiting as well
1989 elif move.split_from:
1990 move2 = move.split_from
1991 while move2 and state != 'waiting':
1992 if move2.move_orig_ids:
1994 move2 = move2.split_from
1995 states[state].append(move.id)
1997 if not move.picking_id and move.picking_type_id:
1998 key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
1999 if key not in to_assign:
2001 to_assign[key].append(move.id)
2003 for move in self.browse(cr, uid, states['confirmed'], context=context):
2004 if move.procure_method == 'make_to_order':
2005 self._create_procurement(cr, uid, move, context=context)
2006 states['waiting'].append(move.id)
2007 states['confirmed'].remove(move.id)
2009 for state, write_ids in states.items():
2011 self.write(cr, uid, write_ids, {'state': state})
2012 #assign picking in batch for all confirmed move that share the same details
2013 for key, move_ids in to_assign.items():
2014 procurement_group, location_from, location_to = key
2015 self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
2016 moves = self.browse(cr, uid, ids, context=context)
2017 self._push_apply(cr, uid, moves, context=context)
2020 def force_assign(self, cr, uid, ids, context=None):
2021 """ Changes the state to assigned.
2024 #check putaway method
2025 return self.write(cr, uid, ids, {'state': 'assigned'})
2027 def check_tracking(self, cr, uid, move, lot_id, context=None):
2028 """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
2031 if move.product_id.track_all and not move.location_dest_id.usage == 'inventory':
2033 elif move.product_id.track_incoming and move.location_id.usage in ('supplier', 'transit', 'inventory') and move.location_dest_id.usage == 'internal':
2035 elif move.product_id.track_outgoing and move.location_dest_id.usage in ('customer', 'transit') and move.location_id.usage == 'internal':
2037 if check and not lot_id:
2038 raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name))
2040 def action_assign(self, cr, uid, ids, context=None):
2041 """ Checks the product type and accordingly writes the state.
2043 context = context or {}
2044 quant_obj = self.pool.get("stock.quant")
2045 to_assign_moves = []
2049 for move in self.browse(cr, uid, ids, context=context):
2050 if move.state not in ('confirmed', 'waiting', 'assigned'):
2052 if move.picking_type_id and move.picking_type_id.auto_force_assign:
2053 to_assign_moves.append(move.id)
2054 #in case the move is returned, we want to try to find quants before forcing the assignment
2055 if not move.origin_returned_move_id:
2057 if move.product_id.type == 'consu':
2058 to_assign_moves.append(move.id)
2061 todo_moves.append(move)
2063 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
2064 main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
2066 #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
2070 move_orig_ids += [x.id for x in move2.move_orig_ids]
2071 #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
2072 move2 = not move2.move_orig_ids and move2.split_from or False
2074 main_domain[move.id] += [('history_ids', 'in', move_orig_ids)]
2076 #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
2077 if move.origin_returned_move_id:
2078 main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
2079 for link in move.linked_move_operation_ids:
2080 operations.add(link.operation_id)
2081 # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
2082 operations = list(operations)
2083 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))
2084 for ops in operations:
2085 #first try to find quants based on specific domains given by linked operations
2086 for record in ops.linked_move_operation_ids:
2087 move = record.move_id
2088 if move.id in main_domain:
2089 domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2092 quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, qty, domain=domain, prefered_domain=[], fallback_domain=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2093 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
2094 for move in todo_moves:
2095 #then if the move isn't totally assigned, try to find quants without any specific domain
2096 if move.state != 'assigned':
2097 qty_already_assigned = move.reserved_availability
2098 qty = move.product_qty - qty_already_assigned
2099 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain[move.id], prefered_domain=[], fallback_domain=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2100 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
2102 #force assignation of consumable products and picking type auto_force_assign
2104 self.force_assign(cr, uid, to_assign_moves, context=context)
2106 def action_cancel(self, cr, uid, ids, context=None):
2107 """ Cancels the moves and if all moves are cancelled it cancels the picking.
2110 procurement_obj = self.pool.get('procurement.order')
2111 context = context or {}
2112 for move in self.browse(cr, uid, ids, context=context):
2113 if move.state == 'done':
2114 raise osv.except_osv(_('Operation Forbidden!'),
2115 _('You cannot cancel a stock move that has been set to \'Done\'.'))
2116 if move.reserved_quant_ids:
2117 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
2118 if context.get('cancel_procurement'):
2120 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
2121 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
2122 elif move.move_dest_id:
2123 #cancel chained moves
2125 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
2126 elif move.move_dest_id.state == 'waiting':
2127 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2128 return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2130 def _check_package_from_moves(self, cr, uid, ids, context=None):
2131 pack_obj = self.pool.get("stock.quant.package")
2133 for move in self.browse(cr, uid, ids, context=context):
2134 packs |= set([q.package_id.id for q in move.quant_ids if q.package_id and q.qty > 0])
2135 return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
2137 def action_done(self, cr, uid, ids, context=None):
2138 """ Process completly the moves given as ids and if all moves are done, it will finish the picking.
2140 context = context or {}
2141 picking_obj = self.pool.get("stock.picking")
2142 quant_obj = self.pool.get("stock.quant")
2143 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
2145 ids = self.action_confirm(cr, uid, todo, context=context)
2147 procurement_ids = []
2148 #Search operations that are linked to the moves
2151 for move in self.browse(cr, uid, ids, context=context):
2152 move_qty[move.id] = move.product_qty
2153 for link in move.linked_move_operation_ids:
2154 operations.add(link.operation_id)
2156 #Sort operations according to entire packages first, then package + lot, package only, lot only
2157 operations = list(operations)
2158 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))
2160 for ops in operations:
2162 pickings.add(ops.picking_id.id)
2163 main_domain = [('qty', '>', 0)]
2164 for record in ops.linked_move_operation_ids:
2165 move = record.move_id
2166 self.check_tracking(cr, uid, move, ops.package_id.id or ops.lot_id.id, context=context)
2167 if record.reserved_quant_id:
2168 quants = [(record.reserved_quant_id, record.qty)]
2170 prefered_domain = [('reservation_id', '=', move.id)]
2171 fallback_domain = [('reservation_id', '=', False)]
2172 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2173 quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, record.qty, domain=dom, prefered_domain=prefered_domain,
2174 fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2176 if ops.result_package_id.id:
2177 #if a result package is given, all quants go there
2178 quant_dest_package_id = ops.result_package_id.id
2179 elif ops.product_id and ops.package_id:
2180 #if a package and a product is given, we will remove quants from the pack.
2181 quant_dest_package_id = False
2183 #otherwise we keep the current pack of the quant, which may mean None
2184 quant_dest_package_id = ops.package_id.id
2185 quant_obj.quants_move(cr, uid, quants, move, ops.location_dest_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)
2186 # Handle pack in pack
2187 if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
2188 self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
2189 move_qty[move.id] -= record.qty
2190 #Check for remaining qtys and unreserve/check move_dest_id in
2191 for move in self.browse(cr, uid, ids, context=context):
2192 if move_qty[move.id] > 0: #(=In case no pack operations in picking)
2193 main_domain = [('qty', '>', 0)]
2194 prefered_domain = [('reservation_id', '=', move.id)]
2195 fallback_domain = [('reservation_id', '=', False)]
2196 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
2197 qty = move_qty[move.id]
2198 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2199 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)
2200 #unreserve the quants and make them available for other operations/moves
2201 quant_obj.quants_unreserve(cr, uid, move, context=context)
2203 #Check moves that were pushed
2204 if move.move_dest_id.state in ('waiting', 'confirmed'):
2205 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
2206 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
2207 #If no other moves for the move that got pushed:
2208 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
2209 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
2210 if move.procurement_id:
2211 procurement_ids.append(move.procurement_id.id)
2213 # Check the packages have been placed in the correct locations
2214 self._check_package_from_moves(cr, uid, ids, context=context)
2216 done_date = context.get('force_date', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
2217 self.write(cr, uid, ids, {'state': 'done', 'date': done_date}, context=context)
2218 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
2219 #check picking state to set the date_done is needed
2221 for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
2222 if picking.state == 'done' and not picking.date_done:
2223 done_picking.append(picking.id)
2225 picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2228 def unlink(self, cr, uid, ids, context=None):
2229 context = context or {}
2230 for move in self.browse(cr, uid, ids, context=context):
2231 if move.state not in ('draft', 'cancel'):
2232 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2233 return super(stock_move, self).unlink(cr, uid, ids, context=context)
2235 def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
2236 """ Move the scrap/damaged product into scrap location
2237 @param cr: the database cursor
2238 @param uid: the user id
2239 @param ids: ids of stock move object to be scrapped
2240 @param quantity : specify scrap qty
2241 @param location_id : specify scrap location
2242 @param context: context arguments
2243 @return: Scraped lines
2245 #quantity should be given in MOVE UOM
2247 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2249 for move in self.browse(cr, uid, ids, context=context):
2250 source_location = move.location_id
2251 if move.state == 'done':
2252 source_location = move.location_dest_id
2253 #Previously used to prevent scraping from virtual location but not necessary anymore
2254 #if source_location.usage != 'internal':
2255 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2256 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2257 move_qty = move.product_qty
2258 uos_qty = quantity / move_qty * move.product_uos_qty
2260 'location_id': source_location.id,
2261 'product_uom_qty': quantity,
2262 'product_uos_qty': uos_qty,
2263 'state': move.state,
2265 'location_dest_id': location_id,
2266 'restrict_lot_id': restrict_lot_id,
2267 'restrict_partner_id': restrict_partner_id,
2269 new_move = self.copy(cr, uid, move.id, default_val)
2272 product_obj = self.pool.get('product.product')
2273 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2275 uom = product.uom_id.name if product.uom_id else ''
2276 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2277 move.picking_id.message_post(body=message)
2279 self.action_done(cr, uid, res, context=context)
2282 def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
2283 """ Splits qty from move move into a new move
2284 :param move: browse record
2285 :param qty: float. quantity to split (given in product UoM)
2286 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
2288 returns the ID of the backorder move created
2290 if move.state in ('done', 'cancel'):
2291 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
2292 if move.state == 'draft':
2293 #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
2294 #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
2295 raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
2297 if move.product_qty <= qty or qty == 0:
2300 uom_obj = self.pool.get('product.uom')
2301 context = context or {}
2303 uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom)
2304 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
2307 'product_uom_qty': uom_qty,
2308 'product_uos_qty': uos_qty,
2309 'state': move.state,
2310 'procure_method': 'make_to_stock',
2311 'restrict_lot_id': restrict_lot_id,
2312 'restrict_partner_id': restrict_partner_id,
2313 'split_from': move.id,
2315 if context.get('source_location_id'):
2316 defaults['location_id'] = context['source_location_id']
2317 new_move = self.copy(cr, uid, move.id, defaults)
2319 ctx = context.copy()
2320 ctx['do_not_propagate'] = True
2321 self.write(cr, uid, [move.id], {
2322 'product_uom_qty': move.product_uom_qty - uom_qty,
2323 'product_uos_qty': move.product_uos_qty - uos_qty,
2326 if move.move_dest_id and move.propagate:
2327 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2328 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2329 #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
2330 #thus the result of action_confirm should always be a list of 1 element length)
2331 return self.action_confirm(cr, uid, [new_move], context=context)[0]
2334 class stock_inventory(osv.osv):
2335 _name = "stock.inventory"
2336 _description = "Inventory"
2338 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2340 for inv in self.browse(cr, uid, ids, context=context):
2346 def _get_available_filters(self, cr, uid, context=None):
2348 This function will return the list of filter allowed according to the options checked
2349 in 'Settings\Warehouse'.
2351 :rtype: list of tuple
2353 #default available choices
2354 res_filter = [('none', _('All products of a whole location')), ('product', _('One product only'))]
2355 settings_obj = self.pool.get('stock.config.settings')
2356 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2357 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2361 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2362 if stock_settings.group_stock_tracking_owner:
2363 res_filter.append(('owner', _('One owner only')))
2364 res_filter.append(('product_owner', _('One product for a specific owner')))
2365 if stock_settings.group_stock_tracking_lot:
2366 res_filter.append(('lot', _('One Lot/Serial Number')))
2367 if stock_settings.group_stock_packaging:
2368 res_filter.append(('pack', _('A Pack')))
2371 def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
2373 for inv in self.browse(cr, uid, ids, context=context):
2374 res[inv.id] = sum([x.product_qty for x in inv.line_ids])
2378 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2379 'date': fields.datetime('Inventory Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Create Date."),
2380 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
2381 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
2382 'state': fields.selection([('draft', 'Draft'), ('cancel', 'Cancelled'), ('confirm', 'In Progress'), ('done', 'Validated')], 'Status', readonly=True, select=True),
2383 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2384 'location_id': fields.many2one('stock.location', 'Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2385 'product_id': fields.many2one('product.product', 'Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2386 'package_id': fields.many2one('stock.quant.package', 'Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."),
2387 'partner_id': fields.many2one('res.partner', 'Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2388 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number."),
2389 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2390 'filter': fields.selection(_get_available_filters, 'Selection Filter'),
2391 'total_qty': fields.function(_get_total_qty, type="float"),
2394 def _default_stock_location(self, cr, uid, context=None):
2396 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2397 return warehouse.lot_stock_id.id
2402 'date': fields.datetime.now,
2404 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2405 'location_id': _default_stock_location,
2408 def set_checked_qty(self, cr, uid, ids, context=None):
2409 inventory = self.browse(cr, uid, ids[0], context=context)
2410 line_ids = [line.id for line in inventory.line_ids]
2411 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2414 def copy(self, cr, uid, id, default=None, context=None):
2417 default = default.copy()
2418 default.update({'move_ids': []})
2419 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2421 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2422 """ Creates a stock move from an inventory line
2423 @param inventory_line:
2427 return self.pool.get('stock.move').create(cr, uid, move_vals)
2429 def action_done(self, cr, uid, ids, context=None):
2430 """ Finish the inventory
2435 move_obj = self.pool.get('stock.move')
2436 for inv in self.browse(cr, uid, ids, context=context):
2437 for inventory_line in inv.line_ids:
2438 if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.th_qty:
2439 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)))
2440 if not inv.move_ids:
2441 self.action_check(cr, uid, [inv.id], context=context)
2443 self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
2444 #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
2445 #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
2446 #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
2447 ctx = context.copy()
2448 ctx['force_date'] = inv.date
2449 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=ctx)
2452 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2453 stock_move_obj = self.pool.get('stock.move')
2454 product_obj = self.pool.get('product.product')
2455 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2457 'name': _('INV:') + (inventory.name or ''),
2458 'product_id': todo_line['product_id'],
2459 'product_uom': todo_line['product_uom_id'],
2460 'date': inventory.date,
2461 'company_id': inventory.company_id.id,
2462 'inventory_id': inventory.id,
2463 'state': 'assigned',
2464 'restrict_lot_id': todo_line.get('prod_lot_id'),
2465 'restrict_partner_id': todo_line.get('partner_id'),
2468 if todo_line['product_qty'] < 0:
2469 #found more than expected
2470 vals['location_id'] = inventory_location_id
2471 vals['location_dest_id'] = todo_line['location_id']
2472 vals['product_uom_qty'] = -todo_line['product_qty']
2474 #found less than expected
2475 vals['location_id'] = todo_line['location_id']
2476 vals['location_dest_id'] = inventory_location_id
2477 vals['product_uom_qty'] = todo_line['product_qty']
2478 return stock_move_obj.create(cr, uid, vals, context=context)
2480 def action_check(self, cr, uid, ids, context=None):
2481 """ Checks the inventory and computes the stock move to do
2484 inventory_line_obj = self.pool.get('stock.inventory.line')
2485 stock_move_obj = self.pool.get('stock.move')
2486 for inventory in self.browse(cr, uid, ids, context=context):
2487 #first remove the existing stock moves linked to this inventory
2488 move_ids = [move.id for move in inventory.move_ids]
2489 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2490 #compute what should be in the inventory lines
2491 theorical_lines = self._get_inventory_lines(cr, uid, inventory, context=context)
2492 for line in inventory.line_ids:
2493 #compare the inventory lines to the theorical ones and store the diff in theorical_lines
2494 inventory_line_obj._resolve_inventory_line(cr, uid, line, theorical_lines, context=context)
2495 #each theorical_lines where product_qty is not 0 is a difference for which we need to create a stock move
2496 for todo_line in theorical_lines:
2497 if todo_line['product_qty'] != 0:
2498 self._create_stock_move(cr, uid, inventory, todo_line, context=context)
2500 def action_cancel_draft(self, cr, uid, ids, context=None):
2501 """ Cancels the stock move and change inventory state to draft.
2504 for inv in self.browse(cr, uid, ids, context=context):
2505 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2506 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2509 def action_cancel_inventory(self, cr, uid, ids, context=None):
2510 self.action_cancel_draft(cr, uid, ids, context=context)
2512 def check_inventory_date(self, cr, uid, inventory, context=None):
2513 domain = ['|', ('location_id', 'child_of', [inventory.location_id.id]), ('location_dest_id', 'child_of', [inventory.location_id.id]), ('date', '>', inventory.date), '|', ('state', 'in', ['assigned', 'done']), '&', ('state', 'in', ['confirmed', 'waiting']), ('partially_available', '=', True)]
2514 if inventory.product_id:
2515 domain += [('product_id', '=', inventory.product_id.id)]
2516 return self.pool.get('stock.move').search(cr, uid, domain, context=context)
2518 def prepare_inventory(self, cr, uid, ids, context=None):
2519 inventory_line_obj = self.pool.get('stock.inventory.line')
2520 for inventory in self.browse(cr, uid, ids, context=context):
2521 #check inventory start date is allowed
2522 if inventory.date > time.strftime(DEFAULT_SERVER_DATETIME_FORMAT):
2523 raise osv.except_osv(_('Error!'), _('It\'s impossible to confirm an inventory in the future. Please change the inventory date to proceed further.'))
2524 conflicting_move_ids = self.check_inventory_date(cr, uid, inventory, context=context)
2526 for move in self.pool.get('stock.move').browse(cr, uid, conflicting_move_ids, context=context):
2527 error_message += _("\n * Date: %s - %s %s - From: %s To: %s State: %s") % (move.date, move.product_uom_qty, move.product_uom.name, move.location_id.name, move.location_dest_id.name, move.state)
2528 if conflicting_move_ids:
2529 raise osv.except_osv(_('Error!'), _('Stock moves exist made/scheduled after the inventory date which are conflicting with its settings. Please unreserve them or change the inventory date to proceed further.\n\n%s') % (error_message))
2530 #clean the existing inventory lines before redoing an inventory proposal
2531 line_ids = [line.id for line in inventory.line_ids]
2532 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2533 #compute the inventory lines and create them
2534 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2535 for product_line in vals:
2536 inventory_line_obj.create(cr, uid, product_line, context=context)
2537 return self.write(cr, uid, ids, {'state': 'confirm'})
2539 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2540 location_obj = self.pool.get('stock.location')
2541 product_obj = self.pool.get('product.product')
2542 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2543 domain = ' location_id in %s'
2544 args = (tuple(location_ids),)
2545 if inventory.partner_id:
2546 domain += ' and owner_id = %s'
2547 args += (inventory.partner_id.id,)
2548 if inventory.lot_id:
2549 domain += ' and lot_id = %s'
2550 args += (inventory.lot_id.id,)
2551 if inventory.product_id:
2552 domain += 'and product_id = %s'
2553 args += (inventory.product_id.id,)
2554 if inventory.package_id:
2555 domain += ' and package_id = %s'
2556 args += (inventory.package_id.id,)
2558 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2559 FROM stock_quant WHERE''' + domain + '''
2560 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2563 for product_line in cr.dictfetchall():
2564 #replace the None the dictionary by False, because falsy values are tested later on
2565 for key, value in product_line.items():
2567 product_line[key] = False
2568 product_line['inventory_id'] = inventory.id
2569 product_line['th_qty'] = product_line['product_qty']
2570 if product_line['product_id']:
2571 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2572 product_line['product_uom_id'] = product.uom_id.id
2573 vals.append(product_line)
2576 class stock_inventory_line(osv.osv):
2577 _name = "stock.inventory.line"
2578 _description = "Inventory Line"
2579 _rec_name = "inventory_id"
2580 _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2582 def _get_product_name_change(self, cr, uid, ids, context=None):
2583 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2585 def _get_location_change(self, cr, uid, ids, context=None):
2586 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2588 def _get_prodlot_change(self, cr, uid, ids, context=None):
2589 return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2592 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2593 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2594 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2595 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2596 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2597 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2598 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2599 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2600 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2601 'th_qty': fields.float('Theoretical Quantity', readonly=True),
2602 'partner_id': fields.many2one('res.partner', 'Owner'),
2603 'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
2604 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2605 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2606 'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
2607 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2608 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2609 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
2610 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2611 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2612 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
2613 'stock.production.lot': (_get_prodlot_change, ['name'], 20),
2614 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
2621 def _resolve_inventory_line(self, cr, uid, inventory_line, theorical_lines, context=None):
2622 #TODO : package_id management !
2624 uom_obj = self.pool.get('product.uom')
2625 for th_line in theorical_lines:
2626 #We try to match the inventory line with a theorical line with same product, lot, location and owner
2627 if th_line['location_id'] == inventory_line.location_id.id and th_line['product_id'] == inventory_line.product_id.id and th_line['prod_lot_id'] == inventory_line.prod_lot_id.id and th_line['partner_id'] == inventory_line.partner_id.id:
2628 uom_reference = inventory_line.product_id.uom_id
2629 real_qty = uom_obj._compute_qty_obj(cr, uid, inventory_line.product_uom_id, inventory_line.product_qty, uom_reference)
2630 th_line['product_qty'] -= real_qty
2633 #if it was still not found, we add it to the theorical lines so that it will create a stock move for it
2636 'inventory_id': inventory_line.inventory_id.id,
2637 'location_id': inventory_line.location_id.id,
2638 'product_id': inventory_line.product_id.id,
2639 'product_uom_id': inventory_line.product_id.uom_id.id,
2640 'product_qty': -inventory_line.product_qty,
2641 'prod_lot_id': inventory_line.prod_lot_id.id,
2642 'partner_id': inventory_line.partner_id.id,
2644 theorical_lines.append(vals)
2646 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, owner_id=False, lot_id=False, package_id=False, context=None):
2647 """ Changes UoM and name if product_id changes.
2648 @param location_id: Location id
2649 @param product: Changed product_id
2650 @param uom: UoM product
2651 @return: Dictionary of changed values
2653 context = context or {}
2655 return {'value': {'product_qty': 0.0, 'product_uom_id': False}}
2656 uom_obj = self.pool.get('product.uom')
2657 ctx = context.copy()
2658 ctx['location'] = location_id
2659 ctx['lot_id'] = lot_id
2660 ctx['owner_id'] = owner_id
2661 ctx['package_id'] = package_id
2662 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
2663 th_qty = obj_product.qty_available
2664 if uom and uom != obj_product.uom_id.id:
2665 uom_record = uom_obj.browse(cr, uid, uom, context=context)
2666 th_qty = uom_obj._compute_qty_obj(cr, uid, obj_product.uom_id, th_qty, uom_record)
2667 return {'value': {'th_qty': th_qty, 'product_uom_id': uom or obj_product.uom_id.id}}
2670 #----------------------------------------------------------
2672 #----------------------------------------------------------
2673 class stock_warehouse(osv.osv):
2674 _name = "stock.warehouse"
2675 _description = "Warehouse"
2678 'name': fields.char('Warehouse Name', size=128, required=True, select=True),
2679 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2680 'partner_id': fields.many2one('res.partner', 'Address'),
2681 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2682 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2683 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2684 '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'),
2685 'reception_steps': fields.selection([
2686 ('one_step', 'Receive goods directly in stock (1 step)'),
2687 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2688 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', required=True),
2689 'delivery_steps': fields.selection([
2690 ('ship_only', 'Ship directly from stock (Ship only)'),
2691 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2692 ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings', required=True),
2693 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2694 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2695 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2696 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2697 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2698 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2699 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2700 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2701 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2702 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2703 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2704 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2705 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2706 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2707 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2708 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes'),
2709 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse'),
2712 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2713 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2714 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2715 resupply_wh_ids.add(default_resupply_wh_id)
2716 resupply_wh_ids = list(resupply_wh_ids)
2717 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2719 def _get_inter_wh_location(self, cr, uid, warehouse, context=None):
2720 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2721 data_obj = self.pool.get('ir.model.data')
2723 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2725 inter_wh_loc = False
2728 def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None):
2729 return self.pool.get('product.product').search(cr, uid, [], context=context)
2731 def _assign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2732 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2733 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2735 def _unassign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2736 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2737 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(3, inter_wh_route_id)]}, context=context)
2739 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2741 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2742 'warehouse_selectable': False,
2743 'product_selectable': True,
2744 'product_categ_selectable': True,
2745 'supplied_wh_id': warehouse.id,
2746 'supplier_wh_id': wh.id,
2749 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2750 location_obj = self.pool.get('stock.location')
2751 route_obj = self.pool.get('stock.location.route')
2752 pull_obj = self.pool.get('procurement.rule')
2753 #create route selectable on the product to resupply the warehouse from another one
2754 inter_wh_location_id = self._get_inter_wh_location(cr, uid, warehouse, context=context)
2755 if inter_wh_location_id:
2756 input_loc = warehouse.wh_input_stock_loc_id
2757 if warehouse.reception_steps == 'one_step':
2758 input_loc = warehouse.lot_stock_id
2759 inter_wh_location = location_obj.browse(cr, uid, inter_wh_location_id, context=context)
2760 for wh in supplier_warehouses:
2761 output_loc = wh.wh_output_stock_loc_id
2762 if wh.delivery_steps == 'ship_only':
2763 output_loc = wh.lot_stock_id
2764 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2765 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2766 values = [(output_loc, inter_wh_location, wh.out_type_id.id, wh), (inter_wh_location, input_loc, warehouse.in_type_id.id, warehouse)]
2767 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2768 for pull_rule in pull_rules_list:
2769 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2770 #if the warehouse is also set as default resupply method, assign this route automatically to all product
2771 if default_resupply_wh and default_resupply_wh.id == wh.id:
2772 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2773 #finally, save the route on the warehouse
2774 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2776 def _default_stock_id(self, cr, uid, context=None):
2777 #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2779 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2780 return warehouse.lot_stock_id.id
2785 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2786 'lot_stock_id': _default_stock_id,
2787 'reception_steps': 'one_step',
2788 'delivery_steps': 'ship_only',
2790 _sql_constraints = [
2791 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2792 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2795 def _get_partner_locations(self, cr, uid, ids, context=None):
2796 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2797 data_obj = self.pool.get('ir.model.data')
2798 location_obj = self.pool.get('stock.location')
2800 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2801 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2803 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2804 customer_loc = customer_loc and customer_loc[0] or False
2805 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2806 supplier_loc = supplier_loc and supplier_loc[0] or False
2807 if not (customer_loc and supplier_loc):
2808 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2809 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2811 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2812 location_obj = self.pool.get('stock.location')
2814 new_reception_step = new_reception_step or warehouse.reception_steps
2815 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2816 if warehouse.reception_steps != new_reception_step:
2817 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2818 if new_reception_step != 'one_step':
2819 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2820 if new_reception_step == 'three_steps':
2821 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2823 if warehouse.delivery_steps != new_delivery_step:
2824 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2825 if new_delivery_step != 'ship_only':
2826 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2827 if new_delivery_step == 'pick_pack_ship':
2828 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2831 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2833 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2834 'product_categ_selectable': True,
2835 'product_selectable': False,
2839 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2840 pull_rules_list = []
2841 for from_loc, dest_loc, pick_type_id, warehouse in values:
2842 pull_rules_list.append({
2843 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2844 'location_src_id': from_loc.id,
2845 'location_id': dest_loc.id,
2846 'route_id': new_route_id,
2848 'picking_type_id': pick_type_id,
2849 'procure_method': 'make_to_order',
2850 'warehouse_id': supplied_warehouse.id,
2851 'propagate_warehouse_id': warehouse.id,
2853 return pull_rules_list
2855 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2857 push_rules_list = []
2858 pull_rules_list = []
2859 for from_loc, dest_loc, pick_type_id in values:
2860 push_rules_list.append({
2861 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2862 'location_from_id': from_loc.id,
2863 'location_dest_id': dest_loc.id,
2864 'route_id': new_route_id,
2866 'picking_type_id': pick_type_id,
2868 'warehouse_id': warehouse.id,
2870 pull_rules_list.append({
2871 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2872 'location_src_id': from_loc.id,
2873 'location_id': dest_loc.id,
2874 'route_id': new_route_id,
2876 'picking_type_id': pick_type_id,
2877 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2879 'warehouse_id': warehouse.id,
2882 return push_rules_list, pull_rules_list
2884 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2885 route_obj = self.pool.get('stock.location.route')
2886 data_obj = self.pool.get('ir.model.data')
2888 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2890 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2891 mto_route_id = mto_route_id and mto_route_id[0] or False
2892 if not mto_route_id:
2893 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
2895 from_loc, dest_loc, pick_type_id = values[0]
2897 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2898 'location_src_id': from_loc.id,
2899 'location_id': dest_loc.id,
2900 'route_id': mto_route_id,
2902 'picking_type_id': pick_type_id,
2903 'procure_method': 'make_to_order',
2905 'warehouse_id': warehouse.id,
2908 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2910 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2911 'warehouse_selectable': False,
2912 'product_selectable': True,
2913 'product_categ_selectable': True,
2914 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
2918 def create_routes(self, cr, uid, ids, warehouse, context=None):
2920 route_obj = self.pool.get('stock.location.route')
2921 pull_obj = self.pool.get('procurement.rule')
2922 push_obj = self.pool.get('stock.location.path')
2923 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2924 #create reception route and rules
2925 route_name, values = routes_dict[warehouse.reception_steps]
2926 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2927 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
2928 wh_route_ids.append((4, reception_route_id))
2929 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
2930 #create the push/pull rules
2931 for push_rule in push_rules_list:
2932 push_obj.create(cr, uid, vals=push_rule, context=context)
2933 for pull_rule in pull_rules_list:
2934 #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
2935 pull_rule['procure_method'] = 'make_to_order'
2936 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2938 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
2939 route_name, values = routes_dict[warehouse.delivery_steps]
2940 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2941 #create the route and its pull rules
2942 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
2943 wh_route_ids.append((4, delivery_route_id))
2944 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
2945 for pull_rule in pull_rules_list:
2946 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2947 #create MTO pull rule and link it to the generic MTO route
2948 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2949 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
2951 #create a route for cross dock operations, that can be set on products and product categories
2952 route_name, values = routes_dict['crossdock']
2953 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
2954 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
2955 wh_route_ids.append((4, crossdock_route_id))
2956 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)
2957 for pull_rule in pull_rules_list:
2958 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2960 #create route selectable on the product to resupply the warehouse from another one
2961 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
2963 #return routes and mto pull rule to store on the warehouse
2965 'route_ids': wh_route_ids,
2966 'mto_pull_id': mto_pull_id,
2967 'reception_route_id': reception_route_id,
2968 'delivery_route_id': delivery_route_id,
2969 'crossdock_route_id': crossdock_route_id,
2972 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2973 picking_type_obj = self.pool.get('stock.picking.type')
2974 pull_obj = self.pool.get('procurement.rule')
2975 push_obj = self.pool.get('stock.location.path')
2976 route_obj = self.pool.get('stock.location.route')
2977 new_reception_step = new_reception_step or warehouse.reception_steps
2978 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2980 #change the default source and destination location and (de)activate picking types
2981 input_loc = warehouse.wh_input_stock_loc_id
2982 if new_reception_step == 'one_step':
2983 input_loc = warehouse.lot_stock_id
2984 output_loc = warehouse.wh_output_stock_loc_id
2985 if new_delivery_step == 'ship_only':
2986 output_loc = warehouse.lot_stock_id
2987 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
2988 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
2989 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
2990 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
2992 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2993 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
2994 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
2995 route_name, values = routes_dict[new_delivery_step]
2996 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2997 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
2998 #create the pull rules
2999 for pull_rule in pull_rules_list:
3000 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3002 #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
3003 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
3004 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
3005 route_name, values = routes_dict[new_reception_step]
3006 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3007 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
3008 #create the push/pull rules
3009 for push_rule in push_rules_list:
3010 push_obj.create(cr, uid, vals=push_rule, context=context)
3011 for pull_rule in pull_rules_list:
3012 #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
3013 pull_rule['procure_method'] = 'make_to_order'
3014 pull_obj.create(cr, uid, vals=pull_rule, context=context)
3016 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
3019 dummy, values = routes_dict[new_delivery_step]
3020 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
3021 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
3024 def create(self, cr, uid, vals, context=None):
3029 data_obj = self.pool.get('ir.model.data')
3030 seq_obj = self.pool.get('ir.sequence')
3031 picking_type_obj = self.pool.get('stock.picking.type')
3032 location_obj = self.pool.get('stock.location')
3034 #create view location for warehouse
3035 wh_loc_id = location_obj.create(cr, uid, {
3036 'name': _(vals.get('code')),
3038 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
3040 vals['view_location_id'] = wh_loc_id
3041 #create all location
3042 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
3043 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
3044 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
3045 context_with_inactive = context.copy()
3046 context_with_inactive['active_test'] = False
3048 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
3049 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
3050 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
3051 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
3052 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
3054 for values in sub_locations:
3055 location_id = location_obj.create(cr, uid, {
3056 'name': values['name'],
3057 'usage': 'internal',
3058 'location_id': wh_loc_id,
3059 'active': values['active'],
3060 }, context=context_with_inactive)
3061 vals[values['field']] = location_id
3063 #create new sequences
3064 in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence in'), 'prefix': vals.get('code', '') + '/IN/', 'padding': 5}, context=context)
3065 out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence out'), 'prefix': vals.get('code', '') + '/OUT/', 'padding': 5}, context=context)
3066 pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence packing'), 'prefix': vals.get('code', '') + '/PACK/', 'padding': 5}, context=context)
3067 pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence picking'), 'prefix': vals.get('code', '') + '/PICK/', 'padding': 5}, context=context)
3068 int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': vals.get('name', '') + _(' Sequence internal'), 'prefix': vals.get('code', '') + '/INT/', 'padding': 5}, context=context)
3071 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
3073 warehouse = self.browse(cr, uid, new_id, context=context)
3074 wh_stock_loc = warehouse.lot_stock_id
3075 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
3076 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
3077 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
3079 #fetch customer and supplier locations, for references
3080 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context)
3082 #create in, out, internal picking types for warehouse
3083 input_loc = wh_input_stock_loc
3084 if warehouse.reception_steps == 'one_step':
3085 input_loc = wh_stock_loc
3086 output_loc = wh_output_stock_loc
3087 if warehouse.delivery_steps == 'ship_only':
3088 output_loc = wh_stock_loc
3090 #choose the next available color for the picking types of this warehouse
3092 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
3093 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
3094 #don't use sets to preserve the list order
3095 for x in all_used_colors:
3096 if x['color'] in available_colors:
3097 available_colors.remove(x['color'])
3098 if available_colors:
3099 color = available_colors[0]
3101 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
3102 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
3103 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
3105 in_type_id = picking_type_obj.create(cr, uid, vals={
3106 'name': _('Receptions'),
3107 'warehouse_id': new_id,
3109 'auto_force_assign': True,
3110 'sequence_id': in_seq_id,
3111 'default_location_src_id': supplier_loc.id,
3112 'default_location_dest_id': input_loc.id,
3113 'sequence': max_sequence + 1,
3114 'color': color}, context=context)
3115 out_type_id = picking_type_obj.create(cr, uid, vals={
3116 'name': _('Delivery Orders'),
3117 'warehouse_id': new_id,
3119 'sequence_id': out_seq_id,
3120 'return_picking_type_id': in_type_id,
3121 'default_location_src_id': output_loc.id,
3122 'default_location_dest_id': customer_loc.id,
3123 'sequence': max_sequence + 4,
3124 'color': color}, context=context)
3125 picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
3126 int_type_id = picking_type_obj.create(cr, uid, vals={
3127 'name': _('Internal Transfers'),
3128 'warehouse_id': new_id,
3130 'sequence_id': int_seq_id,
3131 'default_location_src_id': wh_stock_loc.id,
3132 'default_location_dest_id': wh_stock_loc.id,
3134 'sequence': max_sequence + 2,
3135 'color': color}, context=context)
3136 pack_type_id = picking_type_obj.create(cr, uid, vals={
3138 'warehouse_id': new_id,
3140 'sequence_id': pack_seq_id,
3141 'default_location_src_id': wh_pack_stock_loc.id,
3142 'default_location_dest_id': output_loc.id,
3143 'active': delivery_steps == 'pick_pack_ship',
3144 'sequence': max_sequence + 3,
3145 'color': color}, context=context)
3146 pick_type_id = picking_type_obj.create(cr, uid, vals={
3148 'warehouse_id': new_id,
3150 'sequence_id': pick_seq_id,
3151 'default_location_src_id': wh_stock_loc.id,
3152 'default_location_dest_id': wh_pack_stock_loc.id,
3153 'active': delivery_steps != 'ship_only',
3154 'sequence': max_sequence + 2,
3155 'color': color}, context=context)
3157 #write picking types on WH
3159 'in_type_id': in_type_id,
3160 'out_type_id': out_type_id,
3161 'pack_type_id': pack_type_id,
3162 'pick_type_id': pick_type_id,
3163 'int_type_id': int_type_id,
3165 super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context)
3168 #create routes and push/pull rules
3169 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
3170 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
3173 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
3174 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
3176 def _format_routename(self, cr, uid, obj, name, context=None):
3177 return obj.name + ': ' + name
3179 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
3180 #fetch customer and supplier locations, for references
3181 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
3184 'one_step': (_('Reception in 1 step'), []),
3185 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3186 '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)]),
3187 '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)]),
3188 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
3189 '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)]),
3190 '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)]),
3193 def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
3194 location_obj = self.pool.get('stock.location')
3195 route_obj = self.pool.get('stock.location.route')
3196 pull_obj = self.pool.get('procurement.rule')
3197 push_obj = self.pool.get('stock.location.path')
3199 location_id = warehouse.lot_stock_id.location_id.id
3200 location_obj.write(cr, uid, location_id, {'name': code}, context=context)
3201 #rename route and push-pull rules
3202 for route in warehouse.route_ids:
3203 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
3204 for pull in route.pull_ids:
3205 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3206 for push in route.push_ids:
3207 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3208 #change the mto pull rule name
3209 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
3211 def write(self, cr, uid, ids, vals, context=None):
3214 if isinstance(ids, (int, long)):
3216 seq_obj = self.pool.get('ir.sequence')
3217 route_obj = self.pool.get('stock.location.route')
3219 context_with_inactive = context.copy()
3220 context_with_inactive['active_test'] = False
3221 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
3222 #first of all, check if we need to delete and recreate route
3223 if vals.get('reception_steps') or vals.get('delivery_steps'):
3224 #activate and deactivate location according to reception and delivery option
3225 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
3226 # switch between route
3227 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
3229 if vals.get('code') or vals.get('name'):
3230 name = warehouse.name
3232 if vals.get('name'):
3233 name = vals.get('name', warehouse.name)
3234 self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
3235 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)
3236 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)
3237 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)
3238 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)
3239 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)
3240 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
3241 for cmd in vals.get('resupply_wh_ids'):
3243 new_ids = set(cmd[2])
3244 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
3245 to_add_wh_ids = new_ids - old_ids
3247 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
3248 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
3249 to_remove_wh_ids = old_ids - new_ids
3250 if to_remove_wh_ids:
3251 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)
3252 if to_remove_route_ids:
3253 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
3257 if 'default_resupply_wh_id' in vals:
3258 if vals.get('default_resupply_wh_id') == warehouse.id:
3259 raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
3260 if warehouse.default_resupply_wh_id:
3261 #remove the existing resupplying route on all products
3262 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)
3263 for inter_wh_route_id in to_remove_route_ids:
3264 self._unassign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
3265 if vals.get('default_resupply_wh_id'):
3266 #assign the new resupplying route on all products
3267 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)
3268 for inter_wh_route_id in to_assign_route_ids:
3269 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
3271 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
3273 def unlink(self, cr, uid, ids, context=None):
3274 #TODO try to delete location and route and if not possible, put them in inactive
3275 return super(stock_warehouse, self).unlink(cr, uid, ids, context=context)
3277 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
3278 all_routes = [route.id for route in warehouse.route_ids]
3279 all_routes += [warehouse.mto_pull_id.route_id.id]
3282 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
3284 for wh in self.browse(cr, uid, ids, context=context):
3285 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
3287 domain = [('id', 'in', all_routes)]
3289 'name': _('Warehouse\'s Routes'),
3291 'res_model': 'stock.location.route',
3292 'type': 'ir.actions.act_window',
3294 'view_mode': 'tree,form',
3295 'view_type': 'form',
3299 class stock_location_path(osv.osv):
3300 _name = "stock.location.path"
3301 _description = "Pushed Flows"
3304 def _get_route(self, cr, uid, ids, context=None):
3305 #WARNING TODO route_id is not required, so a field related seems a bad idea >-<
3311 context_with_inactive = context.copy()
3312 context_with_inactive['active_test'] = False
3313 for route in self.pool.get('stock.location.route').browse(cr, uid, ids, context=context_with_inactive):
3314 for push_rule in route.push_ids:
3315 result[push_rule.id] = True
3316 return result.keys()
3318 def _get_rules(self, cr, uid, ids, context=None):
3320 for route in self.browse(cr, uid, ids, context=context):
3321 res += [x.id for x in route.push_ids]
3325 'name': fields.char('Operation Name', size=64, required=True),
3326 'company_id': fields.many2one('res.company', 'Company'),
3327 'route_id': fields.many2one('stock.location.route', 'Route'),
3328 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
3329 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
3330 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
3331 'invoice_state': fields.selection([
3332 ("invoiced", "Invoiced"),
3333 ("2binvoiced", "To Be Invoiced"),
3334 ("none", "Not Applicable")], "Invoice Status",
3336 '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"),
3337 'auto': fields.selection(
3338 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
3340 required=True, select=1,
3341 help="This is used to define paths the product has to follow within the location tree.\n" \
3342 "The 'Automatic Move' value will create a stock move after the current one that will be "\
3343 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
3344 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
3346 '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'),
3347 'active': fields.related('route_id', 'active', type='boolean', string='Active', store={
3348 'stock.location.route': (_get_route, ['active'], 20),
3349 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 20),},
3350 help="If the active field is set to False, it will allow you to hide the rule without removing it." ),
3351 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3352 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3354 'stock.location.route': (_get_rules, ['sequence'], 10),
3355 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3357 'sequence': fields.integer('Sequence'),
3362 'invoice_state': 'none',
3363 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3368 def _apply(self, cr, uid, rule, move, context=None):
3369 move_obj = self.pool.get('stock.move')
3370 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3371 if rule.auto == 'transparent':
3372 old_dest_location = move.location_dest_id.id
3373 move_obj.write(cr, uid, [move.id], {
3375 'date_expected': newdate,
3376 'location_dest_id': rule.location_dest_id.id
3379 #avoid looping if a push rule is not well configured
3380 if rule.location_dest_id.id != old_dest_location:
3381 #call again push_apply to see if a next step is defined
3382 move_obj._push_apply(cr, uid, [move], context=context)
3384 move_id = move_obj.copy(cr, uid, move.id, {
3385 'location_id': move.location_dest_id.id,
3386 'location_dest_id': rule.location_dest_id.id,
3388 'company_id': rule.company_id and rule.company_id.id or False,
3389 'date_expected': newdate,
3390 'picking_id': False,
3391 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3392 'propagate': rule.propagate,
3393 'push_rule_id': rule.id,
3394 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3396 move_obj.write(cr, uid, [move.id], {
3397 'move_dest_id': move_id,
3399 move_obj.action_confirm(cr, uid, [move_id], context=None)
3402 # -------------------------
3403 # Packaging related stuff
3404 # -------------------------
3406 from openerp.report import report_sxw
3407 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
3409 class stock_package(osv.osv):
3411 These are the packages, containing quants and/or other packages
3413 _name = "stock.quant.package"
3414 _description = "Physical Packages"
3415 _parent_name = "parent_id"
3416 _parent_store = True
3417 _parent_order = 'name'
3418 _order = 'parent_left'
3420 def name_get(self, cr, uid, ids, context=None):
3421 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3424 def _complete_name(self, cr, uid, ids, name, args, context=None):
3425 """ Forms complete name of location from parent location to child location.
3426 @return: Dictionary of values
3429 for m in self.browse(cr, uid, ids, context=context):
3431 parent = m.parent_id
3433 res[m.id] = parent.name + ' / ' + res[m.id]
3434 parent = parent.parent_id
3437 def _get_packages(self, cr, uid, ids, context=None):
3438 """Returns packages from quants for store"""
3440 for quant in self.browse(cr, uid, ids, context=context):
3441 if quant.package_id:
3442 res.add(quant.package_id.id)
3445 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3447 for pack in self.browse(cr, uid, ids, context=context):
3450 res.add(pack.parent_id.id)
3453 # TODO: Problem when package is empty!
3455 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3456 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3457 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id})
3458 for pack in self.browse(cr, uid, ids, context=context):
3460 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3461 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3462 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3463 elif pack.children_ids:
3464 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3465 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3466 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3470 'name': fields.char('Package Reference', size=64, select=True),
3471 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3472 'parent_left': fields.integer('Left Parent', select=1),
3473 'parent_right': fields.integer('Right Parent', select=1),
3474 'packaging_id': fields.many2one('product.packaging', 'Type of Packaging'),
3475 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3477 'stock.quant': (_get_packages, ['location_id'], 10),
3478 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3480 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
3481 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
3482 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
3483 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3485 'stock.quant': (_get_packages, ['company_id'], 10),
3486 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3488 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3490 'stock.quant': (_get_packages, ['owner_id'], 10),
3491 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3495 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3498 def _check_location_constraint(self, cr, uid, ids, context=None):
3499 '''checks that all quants in a package are stored in the same location. This function cannot be used
3500 as a constraint because it needs to be checked on pack operations (they may not call write on the
3503 quant_obj = self.pool.get('stock.quant')
3504 for pack in self.browse(cr, uid, ids, context=context):
3506 while parent.parent_id:
3507 parent = parent.parent_id
3508 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3509 quants = quant_obj.browse(cr, uid, quant_ids, context=context)
3510 location_id = quants and quants[0].location_id.id or False
3511 if not all([quant.location_id.id == location_id for quant in quants if quant.qty > 0]):
3512 raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
3515 def action_print(self, cr, uid, ids, context=None):
3519 'ids': context.get('active_id') and [context.get('active_id')] or ids,
3520 'model': 'stock.quant.package',
3521 'form': self.read(cr, uid, ids)[0]
3524 'type': 'ir.actions.report.xml',
3525 'report_name': 'stock.quant.package.barcode',
3529 def unpack(self, cr, uid, ids, context=None):
3530 quant_obj = self.pool.get('stock.quant')
3531 for package in self.browse(cr, uid, ids, context=context):
3532 quant_ids = [quant.id for quant in package.quant_ids]
3533 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3534 children_package_ids = [child_package.id for child_package in package.children_ids]
3535 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3536 #delete current package since it contains nothing anymore
3537 self.unlink(cr, uid, ids, context=context)
3538 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3540 def get_content(self, cr, uid, ids, context=None):
3541 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3542 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3544 def get_content_package(self, cr, uid, ids, context=None):
3545 quants_ids = self.get_content(cr, uid, ids, context=context)
3546 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3547 res['domain'] = [('id', 'in', quants_ids)]
3550 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3551 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3552 quant_obj = self.pool.get('stock.quant')
3553 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3555 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3556 if quant.product_id.id == product_id:
3560 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3561 '''This function computes the different product quantities for the given package
3563 quant_obj = self.pool.get('stock.quant')
3565 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3566 if quant.product_id.id not in res:
3567 res[quant.product_id.id] = 0
3568 res[quant.product_id.id] += quant.qty
3571 def copy(self, cr, uid, id, default=None, context=None):
3574 if not default.get('name'):
3575 default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3576 return super(stock_package, self).copy(cr, uid, id, default, context=context)
3578 def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
3579 stock_pack_operation_obj = self.pool.get('stock.pack.operation')
3582 new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
3583 default['result_package_id'] = new_package_id
3584 op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
3585 for op_id in op_ids:
3586 stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
3589 class stock_pack_operation(osv.osv):
3590 _name = "stock.pack.operation"
3591 _description = "Packing Operation"
3593 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3594 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3595 #if the operation doesn't concern a package, it's not relevant to call this function
3596 if not operation.package_id or operation.product_id:
3597 return {operation.product_id.id: operation.remaining_qty}
3598 #get the total of products the package contains
3599 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3600 #reduce by the quantities linked to a move
3601 for record in operation.linked_move_operation_ids:
3602 if record.move_id.product_id.id not in res:
3603 res[record.move_id.product_id.id] = 0
3604 res[record.move_id.product_id.id] -= record.qty
3607 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3608 uom_obj = self.pool.get('product.uom')
3610 for ops in self.browse(cr, uid, ids, context=context):
3612 if ops.package_id and not ops.product_id:
3613 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3614 #should use _get_remaining_prod_quantities instead
3617 qty = ops.product_qty
3618 if ops.product_uom_id:
3619 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
3620 for record in ops.linked_move_operation_ids:
3622 #converting the remaining quantity in the pack operation UoM
3623 if ops.product_uom_id:
3624 qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context)
3628 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3629 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3630 if product_id and not product_uom_id:
3631 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3632 res['value']['product_uom_id'] = product.uom_id.id
3635 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3637 uom_obj = self.pool.get('product.uom')
3639 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3640 product_uom_id = product_uom_id or product.uom_id.id
3641 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3642 if selected_uom.category_id.id != product.uom_id.category_id.id:
3644 'title': _('Warning: wrong UoM!'),
3645 '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)
3647 if product_qty and 'warning' not in res:
3648 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3649 if rounded_qty != product_qty:
3651 'title': _('Warning: wrong quantity!'),
3652 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3657 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3658 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3659 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3660 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3661 'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
3662 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2
3663 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3664 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3665 'date': fields.datetime('Date', required=True),
3666 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3667 #'update_cost': fields.boolean('Need cost update'),
3668 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3669 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3670 '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'),
3671 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3672 'location_id': fields.many2one('stock.location', 'Location From', required=True),
3673 'location_dest_id': fields.many2one('stock.location', 'Location To', required=True),
3674 'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
3678 'date': fields.date.context_today,
3680 'processed': lambda *a: 'false',
3683 def write(self, cr, uid, ids, vals, context=None):
3684 context = context or {}
3685 res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
3686 if isinstance(ids, (int, long)):
3688 if not context.get("no_recompute"):
3689 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)]))
3690 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
3693 def create(self, cr, uid, vals, context=None):
3694 context = context or {}
3695 res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
3696 if vals.get("picking_id") and not context.get("no_recompute"):
3697 self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
3700 def action_drop_down(self, cr, uid, ids, context=None):
3701 ''' Used by barcode interface to say that pack_operation has been moved from src location
3702 to destination location, if qty_done is less than product_qty than we have to split the
3703 operation in two to process the one with the qty moved
3706 for pack_op in self.browse(cr, uid, ids, context=None):
3708 if pack_op.qty_done < pack_op.product_qty:
3709 # we split the operation in two
3710 op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
3711 self.write(cr, uid, ids, {'product_qty': pack_op.product_qty - pack_op.qty_done, 'qty_done': 0}, context=context)
3712 processed_ids.append(op)
3713 self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
3715 def create_and_assign_lot(self, cr, uid, id, context=None):
3716 ''' Used by barcode interface to create a new lot and assign it to the operation
3718 obj = self.browse(cr,uid,id,context)
3719 product_id = obj.product_id.id
3721 new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, {'product_id': product_id}, context=context)
3722 self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
3724 #TODO: this function can be refactored
3725 def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False ,visible_op_ids=False, increment=True, context=None):
3726 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3728 :param domain: list of tuple directly reusable as a domain
3729 context can receive a key 'current_package_id' with the package to consider for this operation
3732 previously: returns the update to do in stock.move one2many field of picking (adapt remaining quantities) and to the list of package in the classic one2many syntax
3733 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3734 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3735 (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
3740 #if current_package_id is given in the context, we increase the number of items in this package
3741 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3742 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3743 todo_operation_ids = []
3744 if existing_operation_ids:
3746 todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
3748 todo_operation_ids = existing_operation_ids
3749 if todo_operation_ids:
3750 #existing operation found for the given domain and picking => increment its quantity
3751 operation_id = todo_operation_ids[0]
3752 op_obj = self.browse(cr, uid, operation_id, context=context)
3753 qty = op_obj.qty_done
3757 qty -= 1 if qty >= 1 else 0
3758 if qty == 0 and op_obj.product_qty == 0:
3759 #we have a line with 0 qty set, so delete it
3760 self.unlink(cr, uid, [operation_id], context=context)
3762 self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
3764 #no existing operation found for the given domain and picking => create a new one
3766 'picking_id': picking_id,
3771 var_name, dummy, value = key
3773 if var_name == 'product_id':
3774 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3775 update_dict = {var_name: value}
3777 update_dict['product_uom_id'] = uom_id
3778 values.update(update_dict)
3779 operation_id = self.create(cr, uid, values, context=context)
3783 class stock_move_operation_link(osv.osv):
3785 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3787 _name = "stock.move.operation.link"
3788 _description = "Link between stock moves and pack operations"
3791 '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."),
3792 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3793 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3794 '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"),
3797 def get_specific_domain(self, cr, uid, record, context=None):
3798 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3799 having the record given as parameter making the link between the stock move and a pack operation'''
3801 op = record.operation_id
3803 if op.package_id and op.product_id:
3804 #if removing a product from a box, we restrict the choice of quants to this box
3805 domain.append(('package_id', '=', op.package_id.id))
3807 #if moving a box, we allow to take everything from inside boxes as well
3808 domain.append(('package_id', 'child_of', [op.package_id.id]))
3810 #if not given any information about package, we don't open boxes
3811 domain.append(('package_id', '=', False))
3812 #if lot info is given, we restrict choice to this lot otherwise we can take any
3814 domain.append(('lot_id', '=', op.lot_id.id))
3815 #if owner info is given, we restrict to this owner otherwise we restrict to no owner
3817 domain.append(('owner_id', '=', op.owner_id.id))
3819 domain.append(('owner_id', '=', False))
3822 class stock_warehouse_orderpoint(osv.osv):
3824 Defines Minimum stock rules.
3826 _name = "stock.warehouse.orderpoint"
3827 _description = "Minimum Inventory Rule"
3829 def get_draft_procurements(self, cr, uid, ids, context=None):
3832 if not isinstance(ids, list):
3834 procurement_obj = self.pool.get('procurement.order')
3835 for orderpoint in self.browse(cr, uid, ids, context=context):
3836 procurement_ids = procurement_obj.search(cr, uid, [('state', 'not in', ('cancel', 'done')), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)], context=context)
3837 return list(set(procurement_ids))
3839 def _check_product_uom(self, cr, uid, ids, context=None):
3841 Check if the UoM has the same category as the product standard UoM
3846 for rule in self.browse(cr, uid, ids, context=context):
3847 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3852 def action_view_proc_to_process(self, cr, uid, ids, context=None):
3853 act_obj = self.pool.get('ir.actions.act_window')
3854 mod_obj = self.pool.get('ir.model.data')
3855 draft_ids = self.get_draft_procurements(cr, uid, ids, context=context)
3856 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3860 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3861 result['domain'] = "[('id', 'in', [" + ','.join(map(str, draft_ids)) + "])]"
3865 'name': fields.char('Name', size=32, required=True),
3866 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3867 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3868 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3869 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3870 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '!=', 'service')]),
3871 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
3872 'product_min_qty': fields.float('Minimum Quantity', required=True,
3873 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
3874 "a procurement to bring the forecasted quantity to the Max Quantity."),
3875 'product_max_qty': fields.float('Maximum Quantity', required=True,
3876 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
3877 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
3878 'qty_multiple': fields.integer('Qty Multiple', required=True,
3879 help="The procurement quantity will be rounded up to this multiple."),
3880 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
3881 'company_id': fields.many2one('res.company', 'Company', required=True)
3884 'active': lambda *a: 1,
3885 'logic': lambda *a: 'max',
3886 'qty_multiple': lambda *a: 1,
3887 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3888 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
3889 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
3891 _sql_constraints = [
3892 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
3895 (_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']),
3898 def default_get(self, cr, uid, fields, context=None):
3899 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
3900 # default 'warehouse_id' and 'location_id'
3901 if 'warehouse_id' not in res:
3902 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
3903 res['warehouse_id'] = warehouse.id
3904 if 'location_id' not in res:
3905 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
3906 res['location_id'] = warehouse.lot_stock_id.id
3909 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
3910 """ Finds location id for changed warehouse.
3911 @param warehouse_id: Changed id of warehouse.
3912 @return: Dictionary of values.
3915 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
3916 v = {'location_id': w.lot_stock_id.id}
3920 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
3921 """ Finds UoM for changed product.
3922 @param product_id: Changed id of product.
3923 @return: Dictionary of values.
3926 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3927 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
3928 v = {'product_uom': prod.uom_id.id}
3929 return {'value': v, 'domain': d}
3930 return {'domain': {'product_uom': []}}
3932 def copy(self, cr, uid, id, default=None, context=None):
3936 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3938 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
3941 class stock_picking_type(osv.osv):
3942 _name = "stock.picking.type"
3943 _description = "The picking type determines the picking view"
3946 def open_barcode_interface(self, cr, uid, ids, context=None):
3947 final_url="/barcode/web/#action=stock.ui&picking_type_id="+str(ids[0]) if len(ids) else '0'
3948 return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
3951 def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
3952 picking_obj = self.pool.get('stock.picking')
3953 res = dict.fromkeys(ids, [])
3954 for picking_type_id in ids:
3955 #get last 10 pickings of this type
3956 picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
3958 for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
3959 if picking.date_done > picking.date:
3960 tristates.insert(0, {'tooltip': picking.name + _(': Late'), 'value': -1})
3961 elif picking.backorder_id:
3962 tristates.insert(0, {'tooltip': picking.name + _(': Backorder exists'), 'value': 0})
3964 tristates.insert(0, {'tooltip': picking.name + _(': OK'), 'value': 1})
3965 res[picking_type_id] = tristates
3968 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
3969 obj = self.pool.get('stock.picking')
3971 'count_picking_draft': [('state', '=', 'draft')],
3972 'count_picking_waiting': [('state', '=', 'confirmed')],
3973 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
3974 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
3975 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
3976 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
3979 for field in domains:
3980 data = obj.read_group(cr, uid, domains[field] +
3981 [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
3982 ['picking_type_id'], ['picking_type_id'], context=context)
3983 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
3985 result.setdefault(tid, {})[field] = count.get(tid, 0)
3987 if result[tid]['count_picking']:
3988 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
3989 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
3991 result[tid]['rate_picking_late'] = 0
3992 result[tid]['rate_picking_backorders'] = 0
3995 #TODO: not returning valus in required format to show in sparkline library,just added latest_picking_waiting need to add proper logic.
3996 def _get_picking_history(self, cr, uid, ids, field_names, arg, context=None):
3997 obj = self.pool.get('stock.picking')
4001 'latest_picking_late': [],
4002 'latest_picking_backorders': [],
4003 'latest_picking_waiting': []
4006 pick_ids = obj.search(cr, uid, [('state', '=','done'), ('picking_type_id','=',type_id)], limit=12, order="date desc", context=context)
4007 for pick in obj.browse(cr, uid, pick_ids, context=context):
4008 result[type_id]['latest_picking_late'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
4009 result[type_id]['latest_picking_backorders'] = bool(pick.backorder_id)
4010 result[type_id]['latest_picking_waiting'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
4013 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
4014 if not picking_code:
4017 obj_data = self.pool.get('ir.model.data')
4018 stock_loc = obj_data.get_object_reference(cr, uid, 'stock','stock_location_stock')[1]
4021 'default_location_src_id': stock_loc,
4022 'default_location_dest_id': stock_loc,
4024 if picking_code == 'incoming':
4025 result['default_location_src_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_suppliers')[1]
4026 return {'value': result}
4027 if picking_code == 'outgoing':
4028 result['default_location_dest_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_customers')[1]
4029 return {'value': result}
4031 return {'value': result}
4033 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
4034 return dict(self.name_get(cr, uid, ids, context=context))
4036 def name_get(self, cr, uid, ids, context=None):
4037 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
4040 if not isinstance(ids, list):
4045 for record in self.browse(cr, uid, ids, context=context):
4047 if record.warehouse_id:
4048 name = record.warehouse_id.name + ': ' +name
4049 if context.get('special_shortened_wh_name'):
4050 if record.warehouse_id:
4051 name = record.warehouse_id.name
4053 name = _('Customer') + ' (' + record.name + ')'
4054 res.append((record.id, name))
4057 def _default_warehouse(self, cr, uid, context=None):
4058 user = self.pool.get('res.users').browse(cr, uid, uid, context)
4059 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
4060 return res and res[0] or False
4063 'name': fields.char('Picking Type Name', translate=True, required=True),
4064 'complete_name': fields.function(_get_name, type='char', string='Name'),
4065 'auto_force_assign': fields.boolean('Automatic Availability', help='This picking type does\'t need to check for the availability in source location.'),
4066 'color': fields.integer('Color'),
4067 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
4068 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
4069 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
4070 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
4071 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
4072 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
4073 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
4074 'active': fields.boolean('Active'),
4076 # Statistics for the kanban view
4077 'last_done_picking': fields.function(_get_tristate_values,
4079 string='Last 10 Done Pickings'),
4081 'count_picking_draft': fields.function(_get_picking_count,
4082 type='integer', multi='_get_picking_count'),
4083 'count_picking_ready': fields.function(_get_picking_count,
4084 type='integer', multi='_get_picking_count'),
4085 'count_picking': fields.function(_get_picking_count,
4086 type='integer', multi='_get_picking_count'),
4087 'count_picking_waiting': fields.function(_get_picking_count,
4088 type='integer', multi='_get_picking_count'),
4089 'count_picking_late': fields.function(_get_picking_count,
4090 type='integer', multi='_get_picking_count'),
4091 'count_picking_backorders': fields.function(_get_picking_count,
4092 type='integer', multi='_get_picking_count'),
4094 'rate_picking_late': fields.function(_get_picking_count,
4095 type='integer', multi='_get_picking_count'),
4096 'rate_picking_backorders': fields.function(_get_picking_count,
4097 type='integer', multi='_get_picking_count'),
4099 'latest_picking_late': fields.function(_get_picking_history,
4100 type='string', multi='_get_picking_history'),
4101 'latest_picking_backorders': fields.function(_get_picking_history,
4102 type='string', multi='_get_picking_history'),
4103 'latest_picking_waiting': fields.function(_get_picking_history,
4104 type='string', multi='_get_picking_history'),
4108 'warehouse_id': _default_warehouse,
4113 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: