1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import date, datetime
23 from dateutil import relativedelta
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29 from openerp import tools
30 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
31 from openerp import SUPERUSER_ID
32 import openerp.addons.decimal_precision as dp
34 _logger = logging.getLogger(__name__)
37 #----------------------------------------------------------
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41 _name = "stock.incoterms"
42 _description = "Incoterms"
44 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
45 'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
46 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
52 #----------------------------------------------------------
54 #----------------------------------------------------------
56 class stock_location(osv.osv):
57 _name = "stock.location"
58 _description = "Inventory Locations"
59 _parent_name = "location_id"
61 _parent_order = 'name'
62 _order = 'parent_left'
63 _rec_name = 'complete_name'
65 def _complete_name(self, cr, uid, ids, name, args, context=None):
66 """ Forms complete name of location from parent location to child location.
67 @return: Dictionary of values
70 for m in self.browse(cr, uid, ids, context=context):
72 parent = m.location_id
74 res[m.id] = parent.name + ' / ' + res[m.id]
75 parent = parent.location_id
78 def _get_sublocations(self, cr, uid, ids, context=None):
79 """ return all sublocations of the given stock locations (included) """
82 context_with_inactive = context.copy()
83 context_with_inactive['active_test'] = False
84 return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
87 'name': fields.char('Location Name', size=64, required=True, translate=True),
88 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
89 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
90 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
91 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
92 \n* Internal Location: Physical locations inside your own warehouses,
93 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
94 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
95 \n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running.
96 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
99 'complete_name': fields.function(_complete_name, type='char', string="Location Name",
100 store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
101 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
102 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
104 'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
106 'comment': fields.text('Additional Information'),
107 'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
108 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
109 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
111 'parent_left': fields.integer('Left Parent', select=1),
112 'parent_right': fields.integer('Right Parent', select=1),
114 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
115 'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'),
116 'removal_strategy_ids': fields.one2many('product.removal', 'location_id', 'Removal Strategies'),
117 'putaway_strategy_ids': fields.one2many('product.putaway', 'location_id', 'Put Away Strategies'),
122 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
126 'scrap_location': False,
129 def get_putaway_strategy(self, cr, uid, location, product, context=None):
130 pa = self.pool.get('product.putaway')
131 categ = product.categ_id
132 categs = [categ.id, False]
133 while categ.parent_id:
134 categ = categ.parent_id
135 categs.append(categ.id)
137 result = pa.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
139 return pa.browse(cr, uid, result[0], context=context)
141 def get_removal_strategy(self, cr, uid, location, product, context=None):
142 pr = self.pool.get('product.removal')
143 categ = product.categ_id
144 categs = [categ.id, False]
145 while categ.parent_id:
146 categ = categ.parent_id
147 categs.append(categ.id)
149 result = pr.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
151 return pr.browse(cr, uid, result[0], context=context).method
154 #----------------------------------------------------------
156 #----------------------------------------------------------
158 class stock_location_route(osv.osv):
159 _name = 'stock.location.route'
160 _description = "Inventory Routes"
164 'name': fields.char('Route Name', required=True),
165 'sequence': fields.integer('Sequence'),
166 'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'),
167 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
168 'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'),
169 'product_selectable': fields.boolean('Applicable on Product'),
170 'product_categ_selectable': fields.boolean('Applicable on Product Category'),
171 'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
172 'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
173 'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
174 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
178 'sequence': lambda self, cr, uid, ctx: 0,
180 'product_selectable': True,
181 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
185 #----------------------------------------------------------
187 #----------------------------------------------------------
189 class stock_quant(osv.osv):
191 Quants are the smallest unit of stock physical instances
193 _name = "stock.quant"
194 _description = "Quants"
196 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
197 """ Forms complete name of location from parent location to child location.
198 @return: Dictionary of values
201 for q in self.browse(cr, uid, ids, context=context):
203 res[q.id] = q.product_id.code or ''
205 res[q.id] = q.lot_id.name
206 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
209 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
211 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
212 for quant in self.browse(cr, uid, ids, context=context):
213 context.pop('force_company', None)
214 if quant.company_id.id != uid_company_id:
215 #if the company of the quant is different than the current user company, force the company in the context
216 #then re-do a browse to read the property fields for the good company.
217 context['force_company'] = quant.company_id.id
218 quant = self.browse(cr, uid, quant.id, context=context)
219 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
222 def _get_inventory_value(self, cr, uid, quant, context=None):
223 return quant.product_id.standard_price * quant.qty
226 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
227 'product_id': fields.many2one('product.product', 'Product', required=True),
228 'location_id': fields.many2one('stock.location', 'Location', required=True),
229 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"),
230 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"),
231 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True),
232 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"),
233 'link_move_operation_id': fields.many2one('stock.move.operation.link', 'Reserved for Link between Move and Pack Operation', help="Technical field decpicting for with tuple (move, operation) this quant is reserved for"),
234 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
235 'cost': fields.float('Unit Cost'),
236 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"),
238 'create_date': fields.datetime('Creation Date'),
239 'in_date': fields.datetime('Incoming Date'),
241 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
242 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True),
244 # Used for negative quants to reconcile after compensated by a new positive one
245 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'),
246 'negative_dest_location_id': fields.many2one('stock.location', 'Destination Location', help='Technical field used to record the destination location of a move that created a negative quant'),
247 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
251 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
254 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
255 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
256 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
257 if 'inventory_value' in fields:
259 if '__domain' in line:
260 lines = self.search(cr, uid, line['__domain'], context=context)
262 for line2 in self.browse(cr, uid, lines, context=context):
263 inv_value += line2.inventory_value
264 line['inventory_value'] = inv_value
267 def action_view_quant_history(self, cr, uid, ids, context=None):
269 This function returns an action that display the history of the quant, which
270 mean all the stock moves that lead to this quant creation with this quant quantity.
272 mod_obj = self.pool.get('ir.model.data')
273 act_obj = self.pool.get('ir.actions.act_window')
275 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
276 id = result and result[1] or False
277 result = act_obj.read(cr, uid, [id], context={})[0]
280 for quant in self.browse(cr, uid, ids, context=context):
281 move_ids += [move.id for move in quant.history_ids]
283 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
286 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
287 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
288 is also set to 'assigned'
290 :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
291 :param move: browse record
292 :param link: browse record (stock.move.operation.link)
295 #split quants if needed
296 for quant, qty in quants:
299 self._quant_split(cr, uid, quant, qty, context=context)
300 toreserve.append(quant.id)
303 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id, 'link_move_operation_id': link and link.id or False}, context=context)
304 #check if move'state needs to be set as 'assigned'
306 if sum([q.qty for q in move.reserved_quant_ids]) == move.product_qty and move.state in ('confirmed', 'waiting'):
307 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
309 def quants_move(self, cr, uid, quants, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
310 """Moves all given stock.quant in the destination location of the given move.
312 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
313 :param move: browse record (stock.move)
314 :param lot_id: ID of the lot that mus be set on the quants to move
315 :param owner_id: ID of the partner that must own the quants to move
316 :param src_package_id: ID of the package that contains the quants to move
317 :param dest_package_id: ID of the package that must be set on the moved quant
319 for quant, qty in quants:
321 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
322 quant = self._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, context=context)
323 self.move_single_quant_tuple(cr, uid, quant, qty, move, context=context)
325 def check_preferred_location(self, cr, uid, move, qty, context=None):
326 '''Checks the preferred location on the move, if any returned by a putaway strategy, and returns a list of
327 tuple(location, qty) where the quant have to be moved
329 :param move: browse record (stock.move)
331 :returns: list of tuple build as [(browe record (stock.move), float)]
335 for record in move.putaway_ids:
336 res.append((record.location_id, record.quantity))
338 return [(move.location_dest_id, qty)]
340 def move_single_quant(self, cr, uid, quant, location_to, qty, move, context=None):
341 '''Moves the given 'quant' in 'location_to' for the given 'qty', and logs the stock.move that triggered this move in the quant history.
342 If needed, the quant may be split if it's not totally moved.
344 :param quant: browse record (stock.quant)
345 :param location_to: browse record (stock.location)
347 :param move: browse record (stock.move)
349 new_quant = self._quant_split(cr, uid, quant, qty, context=context)
351 'location_id': location_to.id,
352 'history_ids': [(4, move.id)],
354 #if the quant we are moving had been split and was inside a package, it means we unpacked it
355 if new_quant and new_quant.package_id:
356 vals['package_id'] = False
357 self.write(cr, SUPERUSER_ID, [quant.id], vals, context=context)
361 def move_single_quant_tuple(self, cr, uid, quant, qty, move, context=None):
362 '''Effectively process the move of a tuple (quant record, qty to move). This may result in several quants moved
363 if the preferred locations on the move say so but by default it will only move the quant record given as argument
364 :param quant: browse record (stock.quant)
366 :param move: browse record (stock.move)
368 for location_to, qty in self.check_preferred_location(cr, uid, move, qty, context=context):
371 new_quant = self.move_single_quant(cr, uid, quant, location_to, qty, move, context=context)
372 self._quant_reconcile_negative(cr, uid, quant, context=context)
375 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):
376 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
377 the choice on the quants that match the prefered_domain as well. But if the qty requested is not reached
378 it tries to find the remaining quantity by using the fallback_domain.
380 if prefered_domain and fallback_domain:
383 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)
388 quant_ids.append(quant[0].id)
391 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
393 #make sure the quants aren't found twice (if the prefered_domain and the fallback_domain aren't orthogonal
394 domain += [('id', 'not in', quant_ids)]
395 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)
396 for quant in unprefered_quants:
399 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)
401 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
403 Use the removal strategies of product to search for the correct quants
404 If you inherit, put the super at the end of your method.
406 :location: browse record of the parent location where the quants have to be found
407 :product: browse record of the product to find
408 :qty in UoM of product
411 domain = domain or [('qty', '>', 0.0)]
412 if restrict_partner_id:
413 domain += [('owner_id', '=', restrict_partner_id)]
415 domain += [('lot_id', '=', restrict_lot_id)]
417 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context) or 'fifo'
418 if removal_strategy == 'fifo':
419 result += self._quants_get_fifo(cr, uid, location, product, qty, domain, context=context)
420 elif removal_strategy == 'lifo':
421 result += self._quants_get_lifo(cr, uid, location, product, qty, domain, context=context)
423 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
426 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):
427 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
431 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
432 location = force_location or move.location_dest_id
434 'product_id': move.product_id.id,
435 'location_id': location.id,
438 'history_ids': [(4, move.id)],
439 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
440 'company_id': move.company_id.id,
442 'owner_id': owner_id,
443 'package_id': dest_package_id,
446 if move.location_id.usage == 'internal':
447 #if we were trying to move something from an internal location and reach here (quant creation),
448 #it means that a negative quant has to be created as well.
449 negative_vals = vals.copy()
450 negative_vals['location_id'] = move.location_id.id
451 negative_vals['qty'] = -qty
452 negative_vals['cost'] = price_unit
453 negative_vals['negative_dest_location_id'] = move.location_dest_id.id
454 negative_vals['package_id'] = src_package_id
455 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
456 vals.update({'propagated_from_id': negative_quant_id})
458 #create the quant as superuser, because we want to restrict the creation of quant manually: they should always use this method to create quants
459 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
460 return self.browse(cr, uid, quant_id, context=context)
462 def _quant_split(self, cr, uid, quant, qty, context=None):
463 context = context or {}
464 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
466 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
467 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
469 return self.browse(cr, uid, new_quant, context=context)
471 def _get_latest_move(self, cr, uid, quant, context=None):
473 for m in quant.history_ids:
474 if not move or m.date > move.date:
478 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
480 for move in solving_quant.history_ids:
481 path.append((4, move.id))
482 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
484 def _quant_reconcile_negative(self, cr, uid, quant, context=None):
486 When new quant arrive in a location, try to reconcile it with
487 negative quants. If it's possible, apply the cost of the new
488 quant to the conter-part of the negative quant.
490 if quant.location_id.usage != 'internal':
492 solving_quant = quant
493 dom = [('qty', '<', 0)]
494 dom += [('lot_id', '=', quant.lot_id and quant.lot_id.id or False)]
495 dom += [('owner_id', '=', quant.owner_id and quant.owner_id.id or False)]
496 dom += [('package_id', '=', quant.package_id and quant.package_id.id or False)]
497 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, [('qty', '<', '0')], context=context)
498 for quant_neg, qty in quants:
501 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
502 if not to_solve_quant_ids:
505 solved_quant_ids = []
506 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
509 solved_quant_ids.append(to_solve_quant.id)
510 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
511 solving_qty -= min(solving_qty, to_solve_quant.qty)
512 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
513 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
514 #if the reconciliation was not complete, we need to link together the remaining parts
515 if remaining_neg_quant:
516 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
517 if remaining_to_solve_quant_ids:
518 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
519 #delete the reconciled quants, as it is replaced by the solved quants
520 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
521 #price update + accounting entries adjustments
522 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
523 #merge history (and cost?)
524 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
525 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
526 solving_quant = remaining_solving_quant
528 def _price_update(self, cr, uid, ids, newprice, context=None):
529 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
531 def quants_unreserve(self, cr, uid, move, context=None):
532 related_quants = [x.id for x in move.reserved_quant_ids]
533 return self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False, 'link_move_operation_id': False}, context=context)
535 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
536 ''' Implementation of removal strategies
537 If it can not reserve, it will return a tuple (None, qty)
539 domain += location and [('location_id', 'child_of', location.id)] or []
540 domain += [('product_id', '=', product.id)] + domain
541 #don't take into account location that are production, supplier or inventory
542 ignore_location_ids = self.pool.get('stock.location').search(cr, uid, [('usage', 'in', ('production', 'supplier', 'inventory'))], context=context)
543 domain.append(('location_id','not in',ignore_location_ids))
547 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
549 res.append((None, quantity))
551 for quant in self.browse(cr, uid, quants, context=context):
552 if quantity >= abs(quant.qty):
553 res += [(quant, abs(quant.qty))]
554 quantity -= abs(quant.qty)
556 res += [(quant, quantity)]
562 def _quants_get_fifo(self, cr, uid, location, product, quantity, domain=[], context=None):
564 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
566 def _quants_get_lifo(self, cr, uid, location, product, quantity, domain=[], context=None):
567 order = 'in_date desc'
568 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
570 def _location_owner(self, cr, uid, quant, location, context=None):
571 ''' Return the company owning the location if any '''
572 return location and (location.usage == 'internal') and location.company_id or False
574 def _check_location(self, cr, uid, ids, context=None):
575 for record in self.browse(cr, uid, ids, context=context):
576 if record.location_id.usage == 'view':
577 raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.') % (record.product_id.name, record.location_id.name))
581 (_check_location, 'You cannot move products to a location of the type view.', ['location_id'])
585 #----------------------------------------------------------
587 #----------------------------------------------------------
589 class stock_picking(osv.osv):
590 _name = "stock.picking"
591 _inherit = ['mail.thread']
592 _description = "Picking List"
593 _order = "priority desc, date desc, id desc"
595 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
596 move_obj = self.pool.get("stock.move")
598 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
599 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
601 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
602 """ Finds minimum and maximum dates for picking.
603 @return: Dictionary of values
607 res[id] = {'min_date': False, 'max_date': False}
619 picking_id""", (tuple(ids),))
620 for pick, dt1, dt2 in cr.fetchall():
621 res[pick]['min_date'] = dt1
622 res[pick]['max_date'] = dt2
625 def create(self, cr, user, vals, context=None):
626 context = context or {}
627 if ('name' not in vals) or (vals.get('name') in ('/', False)):
628 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
629 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
630 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
631 return super(stock_picking, self).create(cr, user, vals, context)
633 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
634 '''The state of a picking depends on the state of its related stock.move
635 draft: the picking has no line or any one of the lines is draft
636 done, draft, cancel: all lines are done / draft / cancel
637 confirmed, auto, assigned depends on move_type (all at once or direct)
640 for pick in self.browse(cr, uid, ids, context=context):
641 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
642 res[pick.id] = 'draft'
644 if all([x.state == 'cancel' for x in pick.move_lines]):
645 res[pick.id] = 'cancel'
647 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
648 res[pick.id] = 'done'
651 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
652 order_inv = dict(zip(order.values(), order.keys()))
653 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
654 if pick.move_lines == 'one':
655 res[pick.id] = order_inv[min(lst)]
657 res[pick.id] = order_inv[max(lst)]
660 def _get_pickings(self, cr, uid, ids, context=None):
662 for move in self.browse(cr, uid, ids, context=context):
664 res.add(move.picking_id.id)
667 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
669 for pick in self.browse(cr, uid, ids, context=context):
671 if pick.pack_operation_ids:
675 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
677 for pick in self.browse(cr, uid, ids, context=context):
679 for move in pick.move_lines:
680 if move.reserved_quant_ids:
685 def action_assign_owner(self, cr, uid, ids, context=None):
686 for picking in self.browse(cr, uid, ids, context=context):
687 packop_ids = [op.id for op in picking.pack_operation_ids]
688 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
691 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
692 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
693 '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),
694 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
695 '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"),
696 'state': fields.function(_state_get, type="selection", store={
697 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type', 'move_lines'], 20),
698 'stock.move': (_get_pickings, ['state', 'picking_id'], 20)}, selection=[
700 ('cancel', 'Cancelled'),
701 ('waiting', 'Waiting Another Operation'),
702 ('confirmed', 'Waiting Availability'),
703 ('assigned', 'Ready to Transfer'),
704 ('done', 'Transferred'),
705 ], string='Status', readonly=True, select=True, track_visibility='onchange', help="""
706 * Draft: not confirmed yet and will not be scheduled until confirmed\n
707 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
708 * Waiting Availability: still waiting for the availability of products\n
709 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
710 * Transferred: has been processed, can't be modified or cancelled anymore\n
711 * Cancelled: has been cancelled, can't be confirmed anymore"""
713 'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Priority', required=True),
714 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
715 store={'stock.move': (_get_pickings, ['state', 'date_expected'], 20)}, type='datetime', string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.", track_visibility='onchange'),
716 'max_date': fields.function(get_min_max_date, multi="min_max_date",
717 store={'stock.move': (_get_pickings, ['state', 'date_expected'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
718 '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'),
719 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
720 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
721 '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'),
722 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
723 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
724 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', string='Related Packing Operations'),
725 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
726 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True),
727 '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"),
729 'owner_id': fields.many2one('res.partner', 'Owner', help="Default Owner"),
730 # Used to search on pickings
731 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
732 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
733 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
734 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
736 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
737 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
742 'name': lambda self, cr, uid, context: '/',
745 'priority': '1', # normal
746 'date': fields.datetime.now,
747 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
750 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
753 def copy(self, cr, uid, id, default=None, context=None):
756 default = default.copy()
757 picking_obj = self.browse(cr, uid, id, context=context)
758 if ('name' not in default) or (picking_obj.name == '/'):
759 default['name'] = '/'
760 if not default.get('backorder_id'):
761 default['backorder_id'] = False
762 default['pack_operation_ids'] = []
763 default['date_done'] = False
764 return super(stock_picking, self).copy(cr, uid, id, default, context)
766 def do_print_delivery(self, cr, uid, ids, context=None):
767 '''This function prints the delivery order'''
768 assert len(ids) == 1, 'This option should only be used for a single id at a time'
770 'model': 'stock.picking',
773 return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list', 'datas': datas, 'nodestroy': True}
775 def do_print_picking(self, cr, uid, ids, context=None):
776 '''This function prints the picking list'''
777 assert len(ids) == 1, 'This option should only be used for a single id at a time'
779 'model': 'stock.picking',
782 return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list.internal', 'datas': datas, 'nodestroy': True}
784 def action_confirm(self, cr, uid, ids, context=None):
786 todo_force_assign = []
787 for picking in self.browse(cr, uid, ids, context=context):
788 if picking.picking_type_id.auto_force_assign:
789 todo_force_assign.append(picking.id)
790 for r in picking.move_lines:
791 if r.state == 'draft':
794 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
796 if todo_force_assign:
797 self.force_assign(cr, uid, todo_force_assign, context=context)
800 def action_assign(self, cr, uid, ids, context=None):
801 """ Check availability of picking moves.
802 This has the effect of changing the state and reserve quants on available moves, and may
803 also impact the state of the picking as it is computed based on move's states.
806 for pick in self.browse(cr, uid, ids, context=context):
807 if pick.state == 'draft':
808 self.action_confirm(cr, uid, [pick.id], context=context)
809 #skip the moves that don't need to be checked
810 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
812 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
813 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
816 def force_assign(self, cr, uid, ids, context=None):
817 """ Changes state of picking to available if moves are confirmed or waiting.
820 for pick in self.browse(cr, uid, ids, context=context):
821 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
822 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
825 def cancel_assign(self, cr, uid, ids, context=None):
826 """ Cancels picking for the moves that are in the assigned state
829 for pick in self.browse(cr, uid, ids, context=context):
830 move_ids = [x.id for x in pick.move_lines if x not in ['done', 'cancel']]
831 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids, context=context)
834 def action_cancel(self, cr, uid, ids, context=None):
835 for pick in self.browse(cr, uid, ids, context=context):
836 ids2 = [move.id for move in pick.move_lines]
837 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
840 def action_done(self, cr, uid, ids, context=None):
841 """Changes picking state to done by processing the Stock Moves of the Picking
843 Normally that happens when the button "Done" is pressed on a Picking view.
846 for pick in self.browse(cr, uid, ids, context=context):
848 for move in pick.move_lines:
849 if move.state == 'draft':
850 self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
853 elif move.state in ('assigned', 'confirmed'):
856 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
859 def unlink(self, cr, uid, ids, context=None):
860 #on picking deletion, cancel its move then unlink them too
861 move_obj = self.pool.get('stock.move')
862 context = context or {}
863 for pick in self.browse(cr, uid, ids, context=context):
864 move_ids = [move.id for move in pick.move_lines]
865 move_obj.action_cancel(cr, uid, move_ids, context=context)
866 move_obj.unlink(cr, uid, move_ids, context=context)
867 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
869 def write(self, cr, uid, ids, vals, context=None):
870 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
871 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
872 if 'move_lines' in vals or 'pack_operation_ids' in vals:
873 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
876 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
877 """ 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.
879 if not backorder_moves:
880 backorder_moves = picking.move_lines
881 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
882 if 'do_only_split' in context and context['do_only_split']:
883 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
885 if backorder_move_ids:
886 backorder_id = self.copy(cr, uid, picking.id, {
889 'pack_operation_ids': [],
890 'backorder_id': picking.id,
892 back_order_name = self.browse(cr, uid, backorder_id, context=context).name
893 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (back_order_name), context=context)
894 move_obj = self.pool.get("stock.move")
895 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
897 self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
898 self.action_confirm(cr, uid, [backorder_id], context=context)
902 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
904 context = context or {}
905 pack_operation_obj = self.pool.get('stock.pack.operation')
906 pack_obj = self.pool.get("stock.quant.package")
907 quant_obj = self.pool.get("stock.quant")
908 for picking in self.browse(cr, uid, picking_ids, context=context):
909 for move in picking.move_lines:
910 if move.state != 'assigned':
912 #Check which of the reserved quants are entirely in packages (can be in separate method)
913 packages = list(set([x.package_id for x in move.reserved_quant_ids if x.package_id]))
915 for pack in packages:
920 quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
921 if all([x.reservation_id.id == move.id for x in quant_obj.browse(cr, uid, quants, context=context) if x.reservation_id]):
922 good_pack = test_pack.id
923 if test_pack.parent_id:
924 test_pack = test_pack.parent_id
930 done_packages.append(good_pack)
931 done_packages = list(set(done_packages))
933 #Create package operations
934 reserved = set([x.id for x in move.reserved_quant_ids])
935 remaining_qty = move.product_qty
936 for pack in pack_obj.browse(cr, uid, done_packages, context=context):
937 quantl = pack_obj.get_content(cr, uid, [pack.id], context=context)
938 for quant in quant_obj.browse(cr, uid, quantl, context=context):
939 remaining_qty -= quant.qty
940 quants = set(pack_obj.get_content(cr, uid, [pack.id], context=context))
942 pack_operation_obj.create(cr, uid, {
943 'picking_id': picking.id,
944 'package_id': pack.id,
948 yet_to_reserve = list(reserved)
949 #Create operations based on quants
950 for quant in quant_obj.browse(cr, uid, yet_to_reserve, context=context):
951 qty = min(quant.qty, move.product_qty)
953 pack_operation_obj.create(cr, uid, {
954 'picking_id': picking.id,
956 'product_id': quant.product_id.id,
957 'lot_id': quant.lot_id and quant.lot_id.id or False,
958 'product_uom_id': quant.product_id.uom_id.id,
959 'owner_id': quant.owner_id and quant.owner_id.id or False,
961 'package_id': quant.package_id and quant.package_id.id or False,
963 if remaining_qty > 0:
964 pack_operation_obj.create(cr, uid, {
965 'picking_id': picking.id,
966 'product_qty': remaining_qty,
967 'product_id': move.product_id.id,
968 'product_uom_id': move.product_id.uom_id.id,
969 'cost': move.product_id.standard_price,
972 def do_unreserve(self, cr, uid, picking_ids, context=None):
974 Will remove all quants for picking in picking_ids
976 moves_to_unreserve = []
977 for picking in self.browse(cr, uid, picking_ids, context=context):
978 moves_to_unreserve += [m.id for m in picking.move_lines]
979 if moves_to_unreserve:
980 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
982 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
983 def _create_link_for_product(product_id, qty):
985 for move in picking.move_lines:
986 if move.product_id.id == product_id and move.state not in ['done', 'cancel']:
987 qty_on_link = min(move.remaining_qty, qty_to_assign)
988 link_obj.create(cr, uid, {'move_id': move.id, 'operation_id': op.id, 'qty': qty_on_link}, context=context)
989 qty_to_assign -= qty_on_link
991 if qty_to_assign <= 0:
994 link_obj = self.pool.get('stock.move.operation.link')
995 uom_obj = self.pool.get('product.uom')
996 package_obj = self.pool.get('stock.quant.package')
997 for picking in self.browse(cr, uid, picking_ids, context=context):
998 for op in picking.pack_operation_ids:
999 to_unlink_ids = [x.id for x in op.linked_move_operation_ids]
1001 link_obj.unlink(cr, uid, to_unlink_ids, context=context)
1003 normalized_qty = uom_obj._compute_qty(cr, uid, op.product_uom_id.id, op.product_qty, op.product_id.uom_id.id)
1004 _create_link_for_product(op.product_id.id, normalized_qty)
1006 for product_id, qty in package_obj._get_all_products_quantities(cr, uid, op.package_id.id, context=context).items():
1007 _create_link_for_product(product_id, qty)
1009 def _create_extra_moves(self, cr, uid, picking, context=None):
1010 '''This function creates move lines on a picking, at the time of do_transfer, based on
1011 unexpected product transfers (or exceeding quantities) found in the pack operations.
1013 move_obj = self.pool.get('stock.move')
1014 operation_obj = self.pool.get('stock.pack.operation')
1015 for op in picking.pack_operation_ids:
1016 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1017 if remaining_qty > 0:
1018 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1020 'picking_id': picking.id,
1021 'location_id': picking.location_id.id,
1022 'location_dest_id': picking.location_dest_id.id,
1023 'product_id': product_id,
1024 'product_uom': product.uom_id.id,
1025 'product_uom_qty': remaining_qty,
1026 'name': _('Extra Move: ') + product.name,
1027 'state': 'confirmed',
1029 move_obj.create(cr, uid, vals, context=context)
1030 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1032 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1033 """ Unreserve quants then try to reassign quants."""
1034 stock_move_obj = self.pool.get('stock.move')
1036 self.do_unreserve(cr, uid, [picking.id], context=context)
1037 self.action_assign(cr, uid, [picking.id], context=context)
1039 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1040 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1042 def do_transfer(self, cr, uid, picking_ids, context=None):
1044 If no pack operation, we do simple action_done of the picking
1045 Otherwise, do the pack operations
1049 stock_move_obj = self.pool.get('stock.move')
1050 for picking in self.browse(cr, uid, picking_ids, context=context):
1051 if not picking.pack_operation_ids:
1052 self.action_done(cr, uid, [picking.id], context=context)
1055 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1056 #create extra moves in the picking (unexpected product moves coming from pack operations)
1057 self._create_extra_moves(cr, uid, picking, context=context)
1059 #split move lines eventually
1061 toassign_move_ids = []
1062 for move in picking.move_lines:
1063 if move.state in ('done', 'cancel'):
1064 #ignore stock moves cancelled or already done
1066 elif move.state == 'draft':
1067 toassign_move_ids.append(move.id)
1068 if move.remaining_qty == 0:
1069 if move.state in ('draft', 'assigned', 'confirmed'):
1070 todo_move_ids.append(move.id)
1071 elif move.remaining_qty > 0:
1072 new_move = stock_move_obj.split(cr, uid, move, move.remaining_qty, context=context)
1073 todo_move_ids.append(move.id)
1074 #Assign move as it was assigned before
1075 toassign_move_ids.append(new_move)
1077 #this should never happens
1079 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1080 if todo_move_ids and not context.get('do_only_split'):
1081 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1082 elif context.get('do_only_split'):
1083 context.update({'split': todo_move_ids})
1085 self._create_backorder(cr, uid, picking, context=context)
1086 if toassign_move_ids:
1087 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1090 def do_split(self, cr, uid, picking_ids, context=None):
1091 """ just split the picking (create a backorder) without making it 'done' """
1094 ctx = context.copy()
1095 ctx['do_only_split'] = True
1096 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1098 def get_next_picking_for_ui(self, cr, uid, context=None):
1099 """ returns the next pickings to process. Used in the barcode scanner UI"""
1102 domain = [('state', 'in', ('confirmed', 'assigned'))]
1103 if context.get('default_picking_type_id'):
1104 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1105 return self.search(cr, uid, domain, context=context)
1107 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1108 """ called when button 'done' in pused in the barcode scanner UI """
1109 self.do_transfer(cr, uid, [picking_id], context=context)
1110 #return id of next picking to work on
1111 return self.get_next_picking_for_ui(cr, uid, context=context)
1113 def action_pack(self, cr, uid, picking_ids, context=None):
1114 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1115 Used in the barcode scanner UI and the normal interface as well. """
1116 stock_operation_obj = self.pool.get('stock.pack.operation')
1117 package_obj = self.pool.get('stock.quant.package')
1118 for picking_id in picking_ids:
1119 operation_ids = stock_operation_obj.search(cr, uid, [('picking_id', '=', picking_id), ('result_package_id', '=', False)], context=context)
1121 package_id = package_obj.create(cr, uid, {}, context=context)
1122 stock_operation_obj.write(cr, uid, operation_ids, {'result_package_id': package_id}, context=context)
1125 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, context=None):
1126 return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id)], context=context)
1128 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, context=None):
1129 '''This function is called each time there barcode scanner reads an input'''
1130 lot_obj = self.pool.get('stock.production.lot')
1131 package_obj = self.pool.get('stock.quant.package')
1132 product_obj = self.pool.get('product.product')
1133 stock_operation_obj = self.pool.get('stock.pack.operation')
1134 #check if the barcode correspond to a product
1135 matching_product_ids = product_obj.search(cr, uid, [('ean13', '=', barcode_str)], context=context)
1136 if matching_product_ids:
1137 self.process_product_id_from_ui(cr, uid, picking_id, matching_product_ids[0], context=context)
1139 #check if the barcode correspond to a lot
1140 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1141 if matching_lot_ids:
1142 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1143 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], context=context)
1145 #check if the barcode correspond to a package
1146 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1147 if matching_package_ids:
1148 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], context=context)
1151 class stock_production_lot(osv.osv):
1152 _name = 'stock.production.lot'
1153 _inherit = ['mail.thread']
1154 _description = 'Lot/Serial'
1156 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1157 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1158 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1159 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants'),
1160 'create_date': fields.datetime('Creation Date'),
1163 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1164 'product_id': lambda x, y, z, c: c.get('product_id', False),
1166 _sql_constraints = [
1167 ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1170 def action_traceability(self, cr, uid, ids, context=None):
1171 """ It traces the information of lots
1172 @param self: The object pointer.
1173 @param cr: A database cursor
1174 @param uid: ID of the user currently logged in
1175 @param ids: List of IDs selected
1176 @param context: A standard dictionary
1177 @return: A dictionary of values
1179 quant_obj = self.pool.get("stock.quant")
1180 move_obj = self.pool.get("stock.move")
1181 quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1183 for quant in quant_obj.browse(cr, uid, quants, context=context):
1184 moves |= {move.id for move in quant.history_ids}
1187 'domain': "[('id','in',["+','.join(map(str, list(moves)))+"])]",
1188 'name': _('Traceability'),
1189 'view_mode': 'tree,form',
1190 'view_type': 'form',
1191 'context': {'tree_view_ref': 'stock.view_move_tree'},
1192 'res_model': 'stock.move',
1193 'type': 'ir.actions.act_window',
1199 # ----------------------------------------------------
1201 # ----------------------------------------------------
1203 class stock_move(osv.osv):
1204 _name = "stock.move"
1205 _description = "Stock Move"
1206 _order = 'date_expected desc, id'
1209 def get_price_unit(self, cr, uid, move, context=None):
1210 """ Returns the unit price to store on the quant """
1211 return move.price_unit or move.product_id.standard_price
1213 def name_get(self, cr, uid, ids, context=None):
1215 for line in self.browse(cr, uid, ids, context=context):
1216 name = line.location_id.name + ' > ' + line.location_dest_id.name
1217 if line.product_id.code:
1218 name = line.product_id.code + ': ' + name
1219 if line.picking_id.origin:
1220 name = line.picking_id.origin + '/ ' + name
1221 res.append((line.id, name))
1224 def create(self, cr, uid, vals, context=None):
1225 if vals.get('product_id') and not vals.get('price_unit'):
1226 prod_obj = self.pool.get('product.product')
1227 vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price
1228 return super(stock_move, self).create(cr, uid, vals, context=context)
1230 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1231 uom_obj = self.pool.get('product.uom')
1233 for m in self.browse(cr, uid, ids, context=context):
1234 res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False)
1237 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1238 uom_obj = self.pool.get('product.uom')
1240 for move in self.browse(cr, uid, ids, context=context):
1241 qty = move.product_qty
1242 for record in move.linked_move_operation_ids:
1244 #converting the remaining quantity in the move UoM
1245 res[move.id] = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1248 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1249 res = dict.fromkeys(ids, False)
1250 for move in self.browse(cr, uid, ids, context=context):
1251 if move.state == 'done':
1252 res[move.id] = [q.id for q in move.quant_ids]
1254 res[move.id] = [q.id for q in move.reserved_quant_ids]
1257 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1258 quant_obj = self.pool.get('stock.quant')
1259 res = dict.fromkeys(ids, False)
1260 for move in self.browse(cr, uid, ids, context=context):
1261 if move.state == 'done':
1262 res[move.id] = move.product_qty
1264 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1265 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1267 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1268 availability += quant.qty
1269 res[move.id] = min(move.product_qty, availability)
1272 def _get_move(self, cr, uid, ids, context=None):
1274 for quant in self.browse(cr, uid, ids, context=context):
1275 if quant.reservation_id:
1276 res.add(quant.reservation_id.id)
1279 def _get_move_ids(self, cr, uid, ids, context=None):
1281 for picking in self.browse(cr, uid, ids, context=context):
1282 res += [x.id for x in picking.move_lines]
1286 'name': fields.char('Description', required=True, select=True),
1287 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1288 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1289 '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)]}),
1290 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1291 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1292 # TODO: improve store to add dependency on product UoM
1293 'product_qty': fields.function(_quantity_normalize, type='float', store=True, string='Quantity',
1294 digits_compute=dp.get_precision('Product Unit of Measure'),
1295 help='Quantity in the default UoM of the product'),
1296 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1297 required=True, states={'done': [('readonly', True)]},
1298 help="This is the quantity of products from an inventory "
1299 "point of view. For moves in the state 'done', this is the "
1300 "quantity of products that were actually moved. For other "
1301 "moves, this is the quantity of product that is planned to "
1302 "be moved. Lowering this quantity does not generate a "
1303 "backorder. Changing this quantity on assigned moves affects "
1304 "the product reservation, and should be done with care."
1306 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1307 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1308 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1310 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1312 '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."),
1313 '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."),
1315 # FP Note: should we remove this?
1316 '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"),
1319 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1320 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1322 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1323 '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)}),
1324 'note': fields.text('Notes'),
1325 'state': fields.selection([('draft', 'New'),
1326 ('cancel', 'Cancelled'),
1327 ('waiting', 'Waiting Another Move'),
1328 ('confirmed', 'Waiting Availability'),
1329 ('assigned', 'Available'),
1331 ], 'Status', readonly=True, select=True,
1332 help= "* New: When the stock move is created and not yet confirmed.\n"\
1333 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1334 "* 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"\
1335 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1336 "* Done: When the shipment is processed, the state is \'Done\'."),
1338 '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
1340 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1341 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1342 'origin': fields.char("Source"),
1343 '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."),
1345 # used for colors in tree views:
1346 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1348 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1349 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1350 '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'),
1351 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1352 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1353 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1354 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1355 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1356 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1357 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1358 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1359 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1360 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'),
1361 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1362 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1363 'availability': fields.function(_get_product_availability, type='float', string='Availability'),
1364 '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'"),
1365 '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'"),
1366 'putaway_ids': fields.one2many('stock.move.putaway', 'move_id', 'Put Away Suggestions'),
1367 '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"),
1368 '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)."),
1371 def _default_location_destination(self, cr, uid, context=None):
1372 context = context or {}
1373 if context.get('default_picking_type_id', False):
1374 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1375 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1378 def _default_location_source(self, cr, uid, context=None):
1379 context = context or {}
1380 if context.get('default_picking_type_id', False):
1381 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1382 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1385 def _default_destination_address(self, cr, uid, context=None):
1386 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1387 return user.company_id.partner_id.id
1390 'location_id': _default_location_source,
1391 'location_dest_id': _default_location_destination,
1392 'partner_id': _default_destination_address,
1396 'product_uom_qty': 1.0,
1398 'date': fields.datetime.now,
1399 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1400 'date_expected': fields.datetime.now,
1401 'procure_method': 'make_to_stock',
1405 def _check_uom(self, cr, uid, ids, context=None):
1406 for move in self.browse(cr, uid, ids, context=context):
1407 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1413 '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.',
1416 def copy_data(self, cr, uid, id, default=None, context=None):
1419 default = default.copy()
1420 default['move_orig_ids'] = []
1421 default['quant_ids'] = []
1422 default['reserved_quant_ids'] = []
1423 default['returned_move_ids'] = []
1424 default['linked_move_operation_ids'] = []
1425 default['origin_returned_move_id'] = False
1426 default['state'] = 'draft'
1427 return super(stock_move, self).copy_data(cr, uid, id, default, context)
1429 def do_unreserve(self, cr, uid, move_ids, context=None):
1430 quant_obj = self.pool.get("stock.quant")
1431 for move in self.browse(cr, uid, move_ids, context=context):
1432 quant_obj.quants_unreserve(cr, uid, move, context=context)
1434 for putaway_rec in move.putaway_ids:
1435 putaway_values.append((2, putaway_rec.id))
1436 self.write(cr, uid, [move.id], {'state': 'confirmed', 'putaway_ids': putaway_values}, context=context)
1438 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1439 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1440 group_id = move.group_id and move.group_id.id or False
1442 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1443 group_id = move.rule_id.group_id.id
1444 elif move.rule_id.group_propagation_option == 'none':
1447 'name': move.rule_id and move.rule_id.name or "/",
1449 'company_id': move.company_id and move.company_id.id or False,
1450 'date_planned': move.date,
1451 'product_id': move.product_id.id,
1452 'product_qty': move.product_qty,
1453 'product_uom': move.product_uom.id,
1454 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1455 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1456 'location_id': move.location_id.id,
1457 'move_dest_id': move.id,
1458 'group_id': group_id,
1459 'route_ids': [(4, x.id) for x in move.route_ids],
1460 'warehouse_id': move.warehouse_id and move.warehouse_id.id or False,
1463 def _push_apply(self, cr, uid, moves, context=None):
1464 push_obj = self.pool.get("stock.location.path")
1466 if not move.move_dest_id:
1467 domain = [('location_from_id', '=', move.location_dest_id.id)]
1468 if move.warehouse_id:
1469 domain += ['|', ('warehouse_id', '=', move.warehouse_id.id), ('warehouse_id', '=', False)]
1470 #priority goes to the route defined on the product and product category
1471 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1472 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1474 #but if there's no rule matching, we try without filtering on routes
1475 rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context)
1477 rule = push_obj.browse(cr, uid, rules[0], context=context)
1478 push_obj._apply(cr, uid, rule, move, context=context)
1481 # Create the stock.move.putaway records
1482 def _putaway_apply(self, cr, uid, move, putaway, context=None):
1483 # Should call different methods here in later versions
1484 moveputaway_obj = self.pool.get('stock.move.putaway')
1485 quant_obj = self.pool.get('stock.quant')
1486 if putaway.method == 'fixed' and putaway.location_spec_id:
1487 for row in quant_obj.read_group(cr, uid, [('reservation_id', '=', move.id)], ['qty', 'lot_id'], ['lot_id'], context=context):
1490 'location_id': putaway.location_spec_id.id,
1491 'quantity': row['qty'],
1492 'lot_id': row.get('lot_id') and row['lot_id'][0] or False,
1494 moveputaway_obj.create(cr, SUPERUSER_ID, vals, context=context)
1496 def _putaway_check(self, cr, uid, ids, context=None):
1497 for move in self.browse(cr, uid, ids, context=context):
1498 putaway = self.pool.get('stock.location').get_putaway_strategy(cr, uid, move.location_dest_id, move.product_id, context=context)
1500 self._putaway_apply(cr, uid, move, putaway, context=context)
1502 def _create_procurement(self, cr, uid, move, context=None):
1503 """ This will create a procurement order """
1504 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1506 def write(self, cr, uid, ids, vals, context=None):
1509 if isinstance(ids, (int, long)):
1511 # Check that we do not modify a stock.move which is done
1512 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1513 for move in self.browse(cr, uid, ids, context=context):
1514 if move.state == 'done':
1515 if frozen_fields.intersection(vals):
1516 raise osv.except_osv(_('Operation Forbidden!'),
1517 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1518 propagated_changes_dict = {}
1519 #propagation of quantity change
1520 if vals.get('product_uom_qty'):
1521 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1522 if vals.get('product_uom_id'):
1523 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1524 #propagation of expected date:
1525 propagated_date_field = False
1526 if vals.get('date_expected'):
1527 #propagate any manual change of the expected date
1528 propagated_date_field = 'date_expected'
1529 elif (vals.get('state', '') == 'done' and vals.get('date')):
1530 #propagate also any delta observed when setting the move as done
1531 propagated_date_field = 'date'
1533 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1534 #any propagation is (maybe) needed
1535 for move in self.browse(cr, uid, ids, context=context):
1536 if move.move_dest_id and move.propagate:
1537 if 'date_expected' in propagated_changes_dict:
1538 propagated_changes_dict.pop('date_expected')
1539 if propagated_date_field:
1540 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1541 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1542 delta = new_date - current_date
1543 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1544 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1545 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1546 propagated_changes_dict['date_expected'] = new_move_date
1547 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1548 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1549 if propagated_changes_dict:
1550 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1551 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1553 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1554 """ On change of product quantity finds UoM and UoS quantities
1555 @param product_id: Product id
1556 @param product_qty: Changed Quantity of product
1557 @param product_uom: Unit of measure of product
1558 @param product_uos: Unit of sale of product
1559 @return: Dictionary of values
1562 'product_uos_qty': 0.00
1566 if (not product_id) or (product_qty <= 0.0):
1567 result['product_qty'] = 0.0
1568 return {'value': result}
1570 product_obj = self.pool.get('product.product')
1571 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1573 # Warn if the quantity was decreased
1575 for move in self.read(cr, uid, ids, ['product_qty']):
1576 if product_qty < move['product_qty']:
1578 'title': _('Information'),
1579 'message': _("By changing this quantity here, you accept the "
1580 "new quantity as complete: OpenERP will not "
1581 "automatically generate a back order.")})
1584 if product_uos and product_uom and (product_uom != product_uos):
1585 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1587 result['product_uos_qty'] = product_qty
1589 return {'value': result, 'warning': warning}
1591 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1592 product_uos, product_uom):
1593 """ On change of product quantity finds UoM and UoS quantities
1594 @param product_id: Product id
1595 @param product_uos_qty: Changed UoS Quantity of product
1596 @param product_uom: Unit of measure of product
1597 @param product_uos: Unit of sale of product
1598 @return: Dictionary of values
1601 'product_uom_qty': 0.00
1605 if (not product_id) or (product_uos_qty <= 0.0):
1606 result['product_uos_qty'] = 0.0
1607 return {'value': result}
1609 product_obj = self.pool.get('product.product')
1610 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1612 # Warn if the quantity was decreased
1613 for move in self.read(cr, uid, ids, ['product_uos_qty']):
1614 if product_uos_qty < move['product_uos_qty']:
1616 'title': _('Warning: No Back Order'),
1617 'message': _("By changing the quantity here, you accept the "
1618 "new quantity as complete: OpenERP will not "
1619 "automatically generate a Back Order.")})
1622 if product_uos and product_uom and (product_uom != product_uos):
1623 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1625 result['product_uom_qty'] = product_uos_qty
1626 return {'value': result, 'warning': warning}
1628 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1629 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1630 @param prod_id: Changed Product id
1631 @param loc_id: Source location id
1632 @param loc_dest_id: Destination location id
1633 @param partner_id: Address id of partner
1634 @return: Dictionary of values
1638 user = self.pool.get('res.users').browse(cr, uid, uid)
1639 lang = user and user.lang or False
1641 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1643 lang = addr_rec and addr_rec.lang or False
1644 ctx = {'lang': lang}
1646 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1647 uos_id = product.uos_id and product.uos_id.id or False
1649 'product_uom': product.uom_id.id,
1650 'product_uos': uos_id,
1651 'product_uom_qty': 1.00,
1652 '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'],
1655 result['name'] = product.partner_ref
1657 result['location_id'] = loc_id
1659 result['location_dest_id'] = loc_dest_id
1660 return {'value': result}
1662 def _picking_assign(self, cr, uid, move, context=None):
1663 if move.picking_id or not move.picking_type_id:
1665 context = context or {}
1666 pick_obj = self.pool.get("stock.picking")
1668 group = move.group_id and move.group_id.id or False
1669 picks = pick_obj.search(cr, uid, [
1670 ('group_id', '=', group),
1671 ('location_id', '=', move.location_id.id),
1672 ('location_dest_id', '=', move.location_dest_id.id),
1673 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1678 'origin': move.origin,
1679 'company_id': move.company_id and move.company_id.id or False,
1680 'move_type': move.group_id and move.group_id.move_type or 'one',
1681 'partner_id': move.group_id and move.group_id.partner_id and move.group_id.partner_id.id or False,
1682 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1684 pick = pick_obj.create(cr, uid, values, context=context)
1685 move.write({'picking_id': pick})
1688 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1689 """ On change of Scheduled Date gives a Move date.
1690 @param date_expected: Scheduled Date
1691 @param date: Move Date
1694 if not date_expected:
1695 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1696 return {'value': {'date': date_expected}}
1698 def action_confirm(self, cr, uid, ids, context=None):
1699 """ Confirms stock move or put it in waiting if it's linked to another move.
1700 @return: List of ids.
1706 for move in self.browse(cr, uid, ids, context=context):
1708 for m in move.move_orig_ids:
1709 if m.state not in ('done', 'cancel'):
1711 states[state].append(move.id)
1712 self._picking_assign(cr, uid, move, context=context)
1714 for state, write_ids in states.items():
1716 self.write(cr, uid, write_ids, {'state': state})
1717 if state == 'confirmed':
1718 for move in self.browse(cr, uid, write_ids, context=context):
1719 if move.procure_method == 'make_to_order':
1720 self._create_procurement(cr, uid, move, context=context)
1721 moves = self.browse(cr, uid, ids, context=context)
1722 self._push_apply(cr, uid, moves, context=context)
1725 def force_assign(self, cr, uid, ids, context=None):
1726 """ Changes the state to assigned.
1729 return self.write(cr, uid, ids, {'state': 'assigned'})
1731 def cancel_assign(self, cr, uid, ids, context=None):
1732 """ Changes the state to confirmed.
1735 return self.write(cr, uid, ids, {'state': 'confirmed'})
1737 def check_tracking(self, cr, uid, move, lot_id, context=None):
1738 """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
1741 if move.product_id.track_all and not move.location_dest_id.usage == 'inventory':
1743 elif move.product_id.track_incoming and move.location_id.usage in ('supplier', 'transit', 'inventory') and move.location_dest_id.usage == 'internal':
1745 elif move.product_id.track_outgoing and move.location_dest_id.usage in ('customer', 'transit') and move.location_id.usage == 'internal':
1747 if check and not lot_id:
1748 raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name))
1750 def action_assign(self, cr, uid, ids, context=None):
1751 """ Checks the product type and accordingly writes the state.
1753 context = context or {}
1754 quant_obj = self.pool.get("stock.quant")
1755 to_assign_moves = []
1756 for move in self.browse(cr, uid, ids, context=context):
1757 if move.state not in ('confirmed', 'waiting', 'assigned'):
1759 if move.product_id.type == 'consu':
1760 to_assign_moves.append(move.id)
1763 #build the prefered domain based on quants that moved in previous linked done move
1765 for m2 in move.move_orig_ids:
1766 for q in m2.quant_ids:
1767 prev_quant_ids.append(q.id)
1768 prefered_domain = prev_quant_ids and [('id', 'in', prev_quant_ids)] or []
1769 fallback_domain = prev_quant_ids and [('id', 'not in', prev_quant_ids)] or []
1770 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
1771 main_domain = [('reservation_id', '=', False), ('qty', '>', 0)]
1772 #first try to find quants based on specific domains given by linked operations
1773 for record in move.linked_move_operation_ids:
1774 domain = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1775 qty_already_assigned = sum([q.qty for q in record.reserved_quant_ids])
1776 qty = record.qty - qty_already_assigned
1777 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=domain, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
1778 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
1779 #then if the move isn't totally assigned, try to find quants without any specific domain
1780 if move.state != 'assigned':
1781 qty_already_assigned = sum([q.qty for q in move.reserved_quant_ids])
1782 qty = move.product_qty - qty_already_assigned
1783 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)
1784 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
1786 #force assignation of consumable products
1788 self.force_assign(cr, uid, to_assign_moves, context=context)
1789 #check if a putaway rule is likely to be processed and store result on the move
1790 self._putaway_check(cr, uid, ids, context=context)
1792 def action_cancel(self, cr, uid, ids, context=None):
1793 """ Cancels the moves and if all moves are cancelled it cancels the picking.
1796 procurement_obj = self.pool.get('procurement.order')
1797 context = context or {}
1798 for move in self.browse(cr, uid, ids, context=context):
1799 if move.state == 'done':
1800 raise osv.except_osv(_('Operation Forbidden!'),
1801 _('You cannot cancel a stock move that has been set to \'Done\'.'))
1802 if move.reserved_quant_ids:
1803 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
1804 if context.get('cancel_procurement'):
1806 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
1807 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
1808 elif move.move_dest_id:
1809 #cancel chained moves
1811 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
1812 elif move.move_dest_id.state == 'waiting':
1813 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'})
1814 return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1816 def action_done(self, cr, uid, ids, context=None):
1817 """ Makes the move done and if all moves are done, it will finish the picking.
1818 It assumes that quants are already assigned to stock moves.
1819 Putaway strategies should be applied
1822 context = context or {}
1823 picking_obj = self.pool.get("stock.picking")
1824 quant_obj = self.pool.get("stock.quant")
1825 pack_op_obj = self.pool.get("stock.pack.operation")
1826 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
1828 self.action_confirm(cr, uid, todo, context=context)
1831 procurement_ids = []
1832 for move in self.browse(cr, uid, ids, context=context):
1834 pickings.add(move.picking_id.id)
1835 qty = move.product_qty
1836 main_domain = [('qty', '>', 0)]
1837 prefered_domain = [('reservation_id', '=', move.id)]
1838 fallback_domain = [('reservation_id', '=', False)]
1839 #first, process the move per linked operation first because it may imply some specific domains to consider
1840 for record in move.linked_move_operation_ids:
1841 self.check_tracking(cr, uid, move, record.operation_id.lot_id.id, context=context)
1842 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1843 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, record.qty, domain=dom, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
1845 if not record.operation_id.package_id:
1846 #if a package and a result_package is given, we don't enter here because it will be processed by process_packaging() later
1847 #but for operations having only result_package_id, we will create new quants in the final package directly
1848 package_id = record.operation_id.result_package_id.id or False
1849 quant_obj.quants_move(cr, uid, quants, move, lot_id=record.operation_id.lot_id.id, owner_id=record.operation_id.owner_id.id, src_package_id=record.operation_id.package_id.id, dest_package_id=package_id, context=context)
1851 pack_op_obj.process_packaging(cr, uid, record.operation_id, quants, context=context)
1853 #then if the total quantity processed this way isn't enough, process the remaining quantity without any specific domain
1855 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
1856 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)
1857 quant_obj.quants_move(cr, uid, quants, move, lot_id=move.restrict_lot_id.id, owner_id=move.restrict_partner_id.id, context=context)
1858 #unreserve the quants and make them available for other operations/moves
1859 quant_obj.quants_unreserve(cr, uid, move, context=context)
1861 #Check moves that were pushed
1862 if move.move_dest_id.state in ('waiting', 'confirmed'):
1863 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
1864 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
1865 #If no other moves for the move that got pushed:
1866 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
1867 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
1868 if move.procurement_id:
1869 procurement_ids.append(move.procurement_id.id)
1870 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1871 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
1872 #check picking state to set the date_done is needed
1874 for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
1875 if picking.state == 'done' and not picking.date_done:
1876 done_picking.append(picking.id)
1878 picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1881 def unlink(self, cr, uid, ids, context=None):
1882 context = context or {}
1883 for move in self.browse(cr, uid, ids, context=context):
1884 if move.state not in ('draft', 'cancel'):
1885 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
1886 return super(stock_move, self).unlink(cr, uid, ids, context=context)
1888 def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
1889 """ Move the scrap/damaged product into scrap location
1890 @param cr: the database cursor
1891 @param uid: the user id
1892 @param ids: ids of stock move object to be scrapped
1893 @param quantity : specify scrap qty
1894 @param location_id : specify scrap location
1895 @param context: context arguments
1896 @return: Scraped lines
1898 #quantity should be given in MOVE UOM
1900 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
1902 for move in self.browse(cr, uid, ids, context=context):
1903 source_location = move.location_id
1904 if move.state == 'done':
1905 source_location = move.location_dest_id
1906 #Previously used to prevent scraping from virtual location but not necessary anymore
1907 #if source_location.usage != 'internal':
1908 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
1909 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
1910 move_qty = move.product_qty
1911 uos_qty = quantity / move_qty * move.product_uos_qty
1913 'location_id': source_location.id,
1914 'product_uom_qty': quantity,
1915 'product_uos_qty': uos_qty,
1916 'state': move.state,
1918 'location_dest_id': location_id,
1919 'restrict_lot_id': restrict_lot_id,
1920 'restrict_partner_id': restrict_partner_id,
1922 new_move = self.copy(cr, uid, move.id, default_val)
1925 product_obj = self.pool.get('product.product')
1926 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
1928 uom = product.uom_id.name if product.uom_id else ''
1929 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
1930 move.picking_id.message_post(body=message)
1932 self.action_done(cr, uid, res, context=context)
1935 def action_consume(self, cr, uid, ids, quantity, location_id=False, restrict_lot_id=False, restrict_partner_id=False, context=None):
1936 """ Consumed product with specific quantity from specific source location. This correspond to a split of the move (or write if the quantity to consume is >= than the quantity of the move) followed by an action_done
1937 @param ids: ids of stock move object to be consumed
1938 @param quantity : specify consume quantity (given in move UoM)
1939 @param location_id : specify source location
1940 @return: Consumed lines
1942 uom_obj = self.pool.get('product.uom')
1946 raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
1948 for move in self.browse(cr, uid, ids, context=context):
1949 move_qty = move.product_qty
1950 uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, quantity, move.product_uom.id)
1952 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
1953 quantity_rest = move.product_qty - uom_qty
1954 if quantity_rest > 0:
1955 ctx = context.copy()
1957 ctx['source_location_id'] = location_id
1958 res.append(self.split(cr, uid, move, move_qty - quantity_rest, restrict_lot_id=restrict_lot_id,
1959 restrict_partner_id=restrict_partner_id, context=ctx))
1963 self.write(cr, uid, [move.id], {'location_id': location_id, 'restrict_lot_id': restrict_lot_id,
1964 'restrict_partner_id': restrict_partner_id}, context=context)
1966 self.action_done(cr, uid, res, context=context)
1969 def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
1970 """ Splits qty from move move into a new move
1971 :param move: browse record
1972 :param qty: float. quantity to split (given in product UoM)
1973 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
1975 if move.product_qty <= qty or qty == 0:
1978 uom_obj = self.pool.get('product.uom')
1979 context = context or {}
1981 uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1982 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
1984 if move.state in ('done', 'cancel'):
1985 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
1988 'product_uom_qty': uom_qty,
1989 'product_uos_qty': uos_qty,
1990 'state': move.state,
1991 'procure_method': 'make_to_stock',
1992 'move_dest_id': False,
1993 'reserved_quant_ids': [],
1994 'restrict_lot_id': restrict_lot_id,
1995 'restrict_partner_id': restrict_partner_id
1997 if context.get('source_location_id'):
1998 defaults['location_id'] = context['source_location_id']
1999 new_move = self.copy(cr, uid, move.id, defaults)
2001 ctx = context.copy()
2002 ctx['do_not_propagate'] = True
2003 self.write(cr, uid, [move.id], {
2004 'product_uom_qty': move.product_uom_qty - uom_qty,
2005 'product_uos_qty': move.product_uos_qty - uos_qty,
2006 #'reserved_quant_ids': [(6,0,[])] SHOULD NOT CHANGE as it has been reserved already
2009 if move.move_dest_id and move.propagate:
2010 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2011 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2013 self.action_confirm(cr, uid, [new_move], context=context)
2016 class stock_inventory(osv.osv):
2017 _name = "stock.inventory"
2018 _description = "Inventory"
2020 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2022 for inv in self.browse(cr, uid, ids, context=context):
2028 def _get_available_filters(self, cr, uid, context=None):
2030 This function will return the list of filter allowed according to the options checked
2031 in 'Settings\Warehouse'.
2033 :rtype: list of tuple
2035 #default available choices
2036 res_filter = [('none', _('All products of a whole location')), ('product', _('One product only'))]
2037 settings_obj = self.pool.get('stock.config.settings')
2038 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2039 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2043 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2044 if stock_settings.group_stock_tracking_owner:
2045 res_filter.append(('owner', _('One owner only')))
2046 res_filter.append(('product_owner', _('One product for a specific owner')))
2047 if stock_settings.group_stock_tracking_lot:
2048 res_filter.append(('lot', _('One Lot/Serial Number')))
2049 if stock_settings.group_stock_packaging:
2050 res_filter.append(('pack', _('A Pack')))
2054 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2055 'date': fields.datetime('Inventory Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Create Date."),
2056 'date_done': fields.datetime('Date done', help="Inventory Validation Date."),
2057 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
2058 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves."),
2059 'state': fields.selection([('draft', 'Draft'), ('cancel', 'Cancelled'), ('confirm', 'In Progress'), ('done', 'Validated')], 'Status', readonly=True, select=True),
2060 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2061 'location_id': fields.many2one('stock.location', 'Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2062 'product_id': fields.many2one('product.product', 'Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2063 '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."),
2064 'partner_id': fields.many2one('res.partner', 'Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2065 '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."),
2066 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2067 'filter': fields.selection(_get_available_filters, 'Selection Filter'),
2070 def _default_stock_location(self, cr, uid, context=None):
2072 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2073 return warehouse.lot_stock_id.id
2078 'date': fields.datetime.now,
2080 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2081 'location_id': _default_stock_location,
2084 def set_checked_qty(self, cr, uid, ids, context=None):
2085 inventory = self.browse(cr, uid, ids[0], context=context)
2086 line_ids = [line.id for line in inventory.line_ids]
2087 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2090 def copy(self, cr, uid, id, default=None, context=None):
2093 default = default.copy()
2094 default.update({'move_ids': [], 'date_done': False})
2095 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2097 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2098 """ Creates a stock move from an inventory line
2099 @param inventory_line:
2103 return self.pool.get('stock.move').create(cr, uid, move_vals)
2105 def action_done(self, cr, uid, ids, context=None):
2106 """ Finish the inventory
2111 move_obj = self.pool.get('stock.move')
2112 for inv in self.browse(cr, uid, ids, context=context):
2113 if not inv.move_ids:
2114 self.action_check(cr, uid, [inv.id], context=context)
2116 #the action_done on stock_move has to be done in 2 steps:
2117 #first, we start moving the products from stock to inventory loss
2118 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage == 'internal'], context=context)
2119 #then, we move from inventory loss. This 2 steps process is needed because some moved quant may need to be put again in stock
2120 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage != 'internal'], context=context)
2121 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2124 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2125 stock_move_obj = self.pool.get('stock.move')
2126 product_obj = self.pool.get('product.product')
2127 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2129 'name': _('INV:') + (inventory.name or ''),
2130 'product_id': todo_line['product_id'],
2131 'product_uom': todo_line['product_uom_id'],
2132 'date': inventory.date,
2133 'company_id': inventory.company_id.id,
2134 'inventory_id': inventory.id,
2135 'state': 'assigned',
2136 'restrict_lot_id': todo_line.get('prod_lot_id'),
2137 'restrict_partner_id': todo_line.get('partner_id'),
2140 if todo_line['product_qty'] < 0:
2141 #found more than expected
2142 vals['location_id'] = inventory_location_id
2143 vals['location_dest_id'] = todo_line['location_id']
2144 vals['product_uom_qty'] = -todo_line['product_qty']
2146 #found less than expected
2147 vals['location_id'] = todo_line['location_id']
2148 vals['location_dest_id'] = inventory_location_id
2149 vals['product_uom_qty'] = todo_line['product_qty']
2150 return stock_move_obj.create(cr, uid, vals, context=context)
2152 def action_check(self, cr, uid, ids, context=None):
2153 """ Checks the inventory and computes the stock move to do
2156 inventory_line_obj = self.pool.get('stock.inventory.line')
2157 stock_move_obj = self.pool.get('stock.move')
2158 for inventory in self.browse(cr, uid, ids, context=context):
2159 #first remove the existing stock moves linked to this inventory
2160 move_ids = [move.id for move in inventory.move_ids]
2161 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2162 #compute what should be in the inventory lines
2163 theorical_lines = self._get_inventory_lines(cr, uid, inventory, context=context)
2164 for line in inventory.line_ids:
2165 #compare the inventory lines to the theorical ones and store the diff in theorical_lines
2166 inventory_line_obj._resolve_inventory_line(cr, uid, line, theorical_lines, context=context)
2167 #each theorical_lines where product_qty is not 0 is a difference for which we need to create a stock move
2168 for todo_line in theorical_lines:
2169 if todo_line['product_qty'] != 0:
2170 self._create_stock_move(cr, uid, inventory, todo_line, context=context)
2172 def action_cancel_draft(self, cr, uid, ids, context=None):
2173 """ Cancels the stock move and change inventory state to draft.
2176 for inv in self.browse(cr, uid, ids, context=context):
2177 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2178 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2181 def action_cancel_inventory(self, cr, uid, ids, context=None):
2182 self.action_cancel_draft(cr, uid, ids, context=context)
2184 def prepare_inventory(self, cr, uid, ids, context=None):
2185 inventory_line_obj = self.pool.get('stock.inventory.line')
2186 for inventory in self.browse(cr, uid, ids, context=context):
2187 #clean the existing inventory lines before redoing an inventory proposal
2188 line_ids = [line.id for line in inventory.line_ids]
2189 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2190 #compute the inventory lines and create them
2191 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2192 for product_line in vals:
2193 inventory_line_obj.create(cr, uid, product_line, context=context)
2194 return self.write(cr, uid, ids, {'state': 'confirm'})
2196 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2197 location_obj = self.pool.get('stock.location')
2198 product_obj = self.pool.get('product.product')
2199 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2200 domain = ' location_id in %s'
2201 args = (tuple(location_ids),)
2202 if inventory.partner_id:
2203 domain += ' and owner_id = %s'
2204 args += (inventory.partner_id.id,)
2205 if inventory.lot_id:
2206 domain += ' and lot_id = %s'
2207 args += (inventory.lot_id.id,)
2208 if inventory.product_id:
2209 domain += 'and product_id = %s'
2210 args += (inventory.product_id.id,)
2211 if inventory.package_id:
2212 domain += ' and package_id = %s'
2213 args += (inventory.package_id.id,)
2215 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2216 FROM stock_quant WHERE''' + domain + '''
2217 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2220 for product_line in cr.dictfetchall():
2221 #replace the None the dictionary by False, because falsy values are tested later on
2222 for key, value in product_line.items():
2224 product_line[key] = False
2225 product_line['inventory_id'] = inventory.id
2226 product_line['th_qty'] = product_line['product_qty']
2227 if product_line['product_id']:
2228 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2229 product_line['product_uom_id'] = product.uom_id.id
2230 vals.append(product_line)
2233 class stock_inventory_line(osv.osv):
2234 _name = "stock.inventory.line"
2235 _description = "Inventory Line"
2236 _rec_name = "inventory_id"
2237 _order = "inventory_id, location_name, product_code, product_name, prod_lot_id"
2239 def _get_product_name_change(self, cr, uid, ids, context=None):
2240 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2242 def _get_location_change(self, cr, uid, ids, context=None):
2243 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2246 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2247 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2248 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2249 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2250 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2251 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2252 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2253 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2254 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2255 'th_qty': fields.float('Theoretical Quantity', readonly=True),
2256 'partner_id': fields.many2one('res.partner', 'Owner'),
2257 'product_name': fields.related('product_id', 'name', type='char', string='Product name', store={
2258 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2259 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2260 'product_code': fields.related('product_id', 'default_code', type='char', string='Product code', store={
2261 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2262 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2263 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location name', store={
2264 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2265 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2272 def _resolve_inventory_line(self, cr, uid, inventory_line, theorical_lines, context=None):
2273 #TODO : package_id management !
2275 uom_obj = self.pool.get('product.uom')
2276 for th_line in theorical_lines:
2277 #We try to match the inventory line with a theorical line with same product, lot, location and owner
2278 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:
2279 uom_reference = inventory_line.product_id.uom_id
2280 real_qty = uom_obj._compute_qty_obj(cr, uid, inventory_line.product_uom_id, inventory_line.product_qty, uom_reference)
2281 th_line['product_qty'] -= real_qty
2284 #if it was still not found, we add it to the theorical lines so that it will create a stock move for it
2287 'inventory_id': inventory_line.inventory_id.id,
2288 'location_id': inventory_line.location_id.id,
2289 'product_id': inventory_line.product_id.id,
2290 'product_uom_id': inventory_line.product_id.uom_id.id,
2291 'product_qty': -inventory_line.product_qty,
2292 'prod_lot_id': inventory_line.prod_lot_id.id,
2293 'partner_id': inventory_line.partner_id.id,
2295 theorical_lines.append(vals)
2297 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):
2298 """ Changes UoM and name if product_id changes.
2299 @param location_id: Location id
2300 @param product: Changed product_id
2301 @param uom: UoM product
2302 @return: Dictionary of changed values
2304 context = context or {}
2306 return {'value': {'product_qty': 0.0, 'product_uom_id': False}}
2307 uom_obj = self.pool.get('product.uom')
2308 ctx = context.copy()
2309 ctx['location'] = location_id
2310 ctx['lot_id'] = lot_id
2311 ctx['owner_id'] = owner_id
2312 ctx['package_id'] = package_id
2313 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
2314 th_qty = obj_product.qty_available
2315 if uom and uom != obj_product.uom_id.id:
2316 uom_record = uom_obj.browse(cr, uid, uom, context=context)
2317 th_qty = uom_obj._compute_qty_obj(cr, uid, obj_product.uom_id, th_qty, uom_record)
2318 return {'value': {'th_qty': th_qty, 'product_uom_id': uom or obj_product.uom_id.id}}
2321 #----------------------------------------------------------
2323 #----------------------------------------------------------
2324 class stock_warehouse(osv.osv):
2325 _name = "stock.warehouse"
2326 _description = "Warehouse"
2329 'name': fields.char('Name', size=128, required=True, select=True),
2330 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2331 'partner_id': fields.many2one('res.partner', 'Address'),
2332 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2333 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2334 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2335 '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'),
2336 'reception_steps': fields.selection([
2337 ('one_step', 'Receive goods directly in stock (1 step)'),
2338 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2339 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', required=True),
2340 'delivery_steps': fields.selection([
2341 ('ship_only', 'Ship directly from stock (Ship only)'),
2342 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2343 ('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),
2344 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2345 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2346 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2347 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2348 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2349 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2350 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2351 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2352 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2353 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2354 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2355 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2356 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2357 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2358 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2359 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes'),
2360 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse'),
2363 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2364 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2365 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2366 resupply_wh_ids.add(default_resupply_wh_id)
2367 resupply_wh_ids = list(resupply_wh_ids)
2368 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2370 def _get_inter_wh_location(self, cr, uid, warehouse, context=None):
2371 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2372 data_obj = self.pool.get('ir.model.data')
2374 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2376 inter_wh_loc = False
2379 def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None):
2380 return self.pool.get('product.product').search(cr, uid, [], context=context)
2382 def _assign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2383 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2384 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2386 def _unassign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2387 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2388 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(3, inter_wh_route_id)]}, context=context)
2390 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2392 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2393 'warehouse_selectable': False,
2394 'product_selectable': True,
2395 'product_categ_selectable': True,
2396 'supplied_wh_id': warehouse.id,
2397 'supplier_wh_id': wh.id,
2400 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2401 location_obj = self.pool.get('stock.location')
2402 route_obj = self.pool.get('stock.location.route')
2403 pull_obj = self.pool.get('procurement.rule')
2404 #create route selectable on the product to resupply the warehouse from another one
2405 inter_wh_location_id = self._get_inter_wh_location(cr, uid, warehouse, context=context)
2406 if inter_wh_location_id:
2407 input_loc = warehouse.wh_input_stock_loc_id
2408 if warehouse.reception_steps == 'one_step':
2409 input_loc = warehouse.lot_stock_id
2410 inter_wh_location = location_obj.browse(cr, uid, inter_wh_location_id, context=context)
2411 for wh in supplier_warehouses:
2412 output_loc = wh.wh_output_stock_loc_id
2413 if wh.delivery_steps == 'ship_only':
2414 output_loc = wh.lot_stock_id
2415 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2416 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2417 values = [(output_loc, inter_wh_location, wh.out_type_id.id, wh), (inter_wh_location, input_loc, warehouse.in_type_id.id, warehouse)]
2418 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2419 for pull_rule in pull_rules_list:
2420 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2421 #if the warehouse is also set as default resupply method, assign this route automatically to all product
2422 if default_resupply_wh and default_resupply_wh.id == wh.id:
2423 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2424 #finally, save the route on the warehouse
2425 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2427 def _default_stock_id(self, cr, uid, context=None):
2428 #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2430 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2431 return warehouse.lot_stock_id.id
2436 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2437 'lot_stock_id': _default_stock_id,
2438 'reception_steps': 'one_step',
2439 'delivery_steps': 'ship_only',
2441 _sql_constraints = [
2442 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2443 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2444 ('default_resupply_wh_diff', 'check (id != default_resupply_wh_id)', 'The default resupply warehouse should be different that the warehouse itself!'),
2447 def _get_partner_locations(self, cr, uid, ids, context=None):
2448 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2449 data_obj = self.pool.get('ir.model.data')
2450 location_obj = self.pool.get('stock.location')
2452 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2453 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2455 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2456 customer_loc = customer_loc and customer_loc[0] or False
2457 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2458 supplier_loc = supplier_loc and supplier_loc[0] or False
2459 if not (customer_loc and supplier_loc):
2460 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2461 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2463 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2464 location_obj = self.pool.get('stock.location')
2466 new_reception_step = new_reception_step or warehouse.reception_steps
2467 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2468 if warehouse.reception_steps != new_reception_step:
2469 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2470 if new_reception_step != 'one_step':
2471 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2472 if new_reception_step == 'three_steps':
2473 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2475 if warehouse.delivery_steps != new_delivery_step:
2476 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2477 if new_delivery_step != 'ship_only':
2478 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2479 if new_delivery_step == 'pick_pack_ship':
2480 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2483 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2485 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2486 'product_categ_selectable': True,
2487 'product_selectable': False,
2491 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2492 pull_rules_list = []
2493 for from_loc, dest_loc, pick_type_id, warehouse in values:
2494 pull_rules_list.append({
2495 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2496 'location_src_id': from_loc.id,
2497 'location_id': dest_loc.id,
2498 'route_id': new_route_id,
2500 'picking_type_id': pick_type_id,
2501 'procure_method': 'make_to_order',
2502 'warehouse_id': supplied_warehouse.id,
2503 'propagate_warehouse_id': warehouse.id,
2505 return pull_rules_list
2507 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2509 push_rules_list = []
2510 pull_rules_list = []
2511 for from_loc, dest_loc, pick_type_id in values:
2512 push_rules_list.append({
2513 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2514 'location_from_id': from_loc.id,
2515 'location_dest_id': dest_loc.id,
2516 'route_id': new_route_id,
2518 'picking_type_id': pick_type_id,
2520 'warehouse_id': warehouse.id,
2522 pull_rules_list.append({
2523 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2524 'location_src_id': from_loc.id,
2525 'location_id': dest_loc.id,
2526 'route_id': new_route_id,
2528 'picking_type_id': pick_type_id,
2529 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2531 'warehouse_id': warehouse.id,
2534 return push_rules_list, pull_rules_list
2536 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2537 route_obj = self.pool.get('stock.location.route')
2538 data_obj = self.pool.get('ir.model.data')
2540 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2542 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2543 mto_route_id = mto_route_id and mto_route_id[0] or False
2544 if not mto_route_id:
2545 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
2547 from_loc, dest_loc, pick_type_id = values[0]
2549 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2550 'location_src_id': from_loc.id,
2551 'location_id': dest_loc.id,
2552 'route_id': mto_route_id,
2554 'picking_type_id': pick_type_id,
2555 'procure_method': 'make_to_order',
2557 'warehouse_id': warehouse.id,
2560 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2562 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2563 'warehouse_selectable': False,
2564 'product_selectable': True,
2565 'product_categ_selectable': True,
2566 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
2570 def create_routes(self, cr, uid, ids, warehouse, context=None):
2572 route_obj = self.pool.get('stock.location.route')
2573 pull_obj = self.pool.get('procurement.rule')
2574 push_obj = self.pool.get('stock.location.path')
2575 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2576 #create reception route and rules
2577 route_name, values = routes_dict[warehouse.reception_steps]
2578 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2579 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
2580 wh_route_ids.append((4, reception_route_id))
2581 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
2582 #create the push/pull rules
2583 for push_rule in push_rules_list:
2584 push_obj.create(cr, uid, vals=push_rule, context=context)
2585 for pull_rule in pull_rules_list:
2586 #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
2587 pull_rule['procure_method'] = 'make_to_order'
2588 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2590 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
2591 route_name, values = routes_dict[warehouse.delivery_steps]
2592 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2593 #create the route and its pull rules
2594 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
2595 wh_route_ids.append((4, delivery_route_id))
2596 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
2597 for pull_rule in pull_rules_list:
2598 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2599 #create MTO pull rule and link it to the generic MTO route
2600 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2601 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
2603 #create a route for cross dock operations, that can be set on products and product categories
2604 route_name, values = routes_dict['crossdock']
2605 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
2606 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
2607 wh_route_ids.append((4, crossdock_route_id))
2608 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)
2609 for pull_rule in pull_rules_list:
2610 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2612 #create route selectable on the product to resupply the warehouse from another one
2613 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
2615 #return routes and mto pull rule to store on the warehouse
2617 'route_ids': wh_route_ids,
2618 'mto_pull_id': mto_pull_id,
2619 'reception_route_id': reception_route_id,
2620 'delivery_route_id': delivery_route_id,
2621 'crossdock_route_id': crossdock_route_id,
2624 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2625 picking_type_obj = self.pool.get('stock.picking.type')
2626 pull_obj = self.pool.get('procurement.rule')
2627 push_obj = self.pool.get('stock.location.path')
2628 route_obj = self.pool.get('stock.location.route')
2629 new_reception_step = new_reception_step or warehouse.reception_steps
2630 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2632 #change the default source and destination location and (de)activate picking types
2633 input_loc = warehouse.wh_input_stock_loc_id
2634 if new_reception_step == 'one_step':
2635 input_loc = warehouse.lot_stock_id
2636 output_loc = warehouse.wh_output_stock_loc_id
2637 if new_delivery_step == 'ship_only':
2638 output_loc = warehouse.lot_stock_id
2639 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
2640 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
2641 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
2642 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
2644 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2645 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
2646 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
2647 route_name, values = routes_dict[new_delivery_step]
2648 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2649 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
2650 #create the pull rules
2651 for pull_rule in pull_rules_list:
2652 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2654 #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
2655 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
2656 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
2657 route_name, values = routes_dict[new_reception_step]
2658 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2659 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
2660 #create the push/pull rules
2661 for push_rule in push_rules_list:
2662 push_obj.create(cr, uid, vals=push_rule, context=context)
2663 for pull_rule in pull_rules_list:
2664 #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
2665 pull_rule['procure_method'] = 'make_to_order'
2666 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2668 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
2671 dummy, values = routes_dict[new_delivery_step]
2672 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2673 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
2676 def create(self, cr, uid, vals, context=None):
2681 data_obj = self.pool.get('ir.model.data')
2682 seq_obj = self.pool.get('ir.sequence')
2683 picking_type_obj = self.pool.get('stock.picking.type')
2684 location_obj = self.pool.get('stock.location')
2686 #create view location for warehouse
2687 wh_loc_id = location_obj.create(cr, uid, {
2688 'name': _(vals.get('name')),
2690 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
2692 vals['view_location_id'] = wh_loc_id
2693 #create all location
2694 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
2695 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
2696 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
2697 context_with_inactive = context.copy()
2698 context_with_inactive['active_test'] = False
2700 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
2701 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
2702 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
2703 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
2704 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
2706 for values in sub_locations:
2707 location_id = location_obj.create(cr, uid, {
2708 'name': values['name'],
2709 'usage': 'internal',
2710 'location_id': wh_loc_id,
2711 'active': values['active'],
2712 }, context=context_with_inactive)
2713 vals[values['field']] = location_id
2715 #create new sequences
2716 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)
2717 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)
2718 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)
2719 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)
2720 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)
2723 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
2725 warehouse = self.browse(cr, uid, new_id, context=context)
2726 wh_stock_loc = warehouse.lot_stock_id
2727 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
2728 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
2729 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
2731 #fetch customer and supplier locations, for references
2732 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context)
2734 #create in, out, internal picking types for warehouse
2735 input_loc = wh_input_stock_loc
2736 if warehouse.reception_steps == 'one_step':
2737 input_loc = wh_stock_loc
2738 output_loc = wh_output_stock_loc
2739 if warehouse.delivery_steps == 'ship_only':
2740 output_loc = wh_stock_loc
2742 #choose the next available color for the picking types of this warehouse
2744 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
2745 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
2746 #don't use sets to preserve the list order
2747 for x in all_used_colors:
2748 if x['color'] in available_colors:
2749 available_colors.remove(x['color'])
2750 if available_colors:
2751 color = available_colors[0]
2753 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
2754 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
2755 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
2757 in_type_id = picking_type_obj.create(cr, uid, vals={
2758 'name': _('Receptions'),
2759 'warehouse_id': new_id,
2761 'auto_force_assign': True,
2762 'sequence_id': in_seq_id,
2763 'default_location_src_id': supplier_loc.id,
2764 'default_location_dest_id': input_loc.id,
2765 'sequence': max_sequence + 1,
2766 'color': color}, context=context)
2767 out_type_id = picking_type_obj.create(cr, uid, vals={
2768 'name': _('Delivery Orders'),
2769 'warehouse_id': new_id,
2771 'sequence_id': out_seq_id,
2772 'return_picking_type_id': in_type_id,
2773 'default_location_src_id': output_loc.id,
2774 'default_location_dest_id': customer_loc.id,
2775 'sequence': max_sequence + 4,
2776 'color': color}, context=context)
2777 picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
2778 int_type_id = picking_type_obj.create(cr, uid, vals={
2779 'name': _('Internal Transfers'),
2780 'warehouse_id': new_id,
2782 'sequence_id': int_seq_id,
2783 'default_location_src_id': wh_stock_loc.id,
2784 'default_location_dest_id': wh_stock_loc.id,
2786 'sequence': max_sequence + 2,
2787 'color': color}, context=context)
2788 pack_type_id = picking_type_obj.create(cr, uid, vals={
2790 'warehouse_id': new_id,
2792 'sequence_id': pack_seq_id,
2793 'default_location_src_id': wh_pack_stock_loc.id,
2794 'default_location_dest_id': output_loc.id,
2795 'active': delivery_steps == 'pick_pack_ship',
2796 'sequence': max_sequence + 3,
2797 'color': color}, context=context)
2798 pick_type_id = picking_type_obj.create(cr, uid, vals={
2800 'warehouse_id': new_id,
2802 'sequence_id': pick_seq_id,
2803 'default_location_src_id': wh_stock_loc.id,
2804 'default_location_dest_id': wh_pack_stock_loc.id,
2805 'active': delivery_steps != 'ship_only',
2806 'sequence': max_sequence + 2,
2807 'color': color}, context=context)
2809 #write picking types on WH
2811 'in_type_id': in_type_id,
2812 'out_type_id': out_type_id,
2813 'pack_type_id': pack_type_id,
2814 'pick_type_id': pick_type_id,
2815 'int_type_id': int_type_id,
2817 super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context)
2820 #create routes and push/pull rules
2821 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
2822 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
2825 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
2826 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
2828 def _format_routename(self, cr, uid, obj, name, context=None):
2829 return obj.name + ': ' + name
2831 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
2832 #fetch customer and supplier locations, for references
2833 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
2836 'one_step': (_('Reception in 1 step'), []),
2837 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
2838 '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)]),
2839 '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)]),
2840 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
2841 '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)]),
2842 '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)]),
2845 def _handle_renaming(self, cr, uid, warehouse, name, context=None):
2846 location_obj = self.pool.get('stock.location')
2847 route_obj = self.pool.get('stock.location.route')
2848 pull_obj = self.pool.get('procurement.rule')
2849 push_obj = self.pool.get('stock.location.path')
2851 location_id = warehouse.lot_stock_id.location_id.id
2852 location_obj.write(cr, uid, location_id, {'name': name}, context=context)
2853 #rename route and push-pull rules
2854 for route in warehouse.route_ids:
2855 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
2856 for pull in route.pull_ids:
2857 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2858 for push in route.push_ids:
2859 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2860 #change the mto pull rule name
2861 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
2863 def write(self, cr, uid, ids, vals, context=None):
2866 if isinstance(ids, (int, long)):
2868 seq_obj = self.pool.get('ir.sequence')
2869 route_obj = self.pool.get('stock.location.route')
2871 context_with_inactive = context.copy()
2872 context_with_inactive['active_test'] = False
2873 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
2874 #first of all, check if we need to delete and recreate route
2875 if vals.get('reception_steps') or vals.get('delivery_steps'):
2876 #activate and deactivate location according to reception and delivery option
2877 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
2878 # switch between route
2879 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
2880 if vals.get('code') or vals.get('name'):
2881 name = warehouse.name
2883 if vals.get('name'):
2884 name = vals.get('name')
2885 self._handle_renaming(cr, uid, warehouse, name, context=context_with_inactive)
2886 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)
2887 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)
2888 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)
2889 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)
2890 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)
2891 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
2892 for cmd in vals.get('resupply_wh_ids'):
2894 new_ids = set(cmd[2])
2895 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
2896 to_add_wh_ids = new_ids - old_ids
2898 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
2899 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
2900 to_remove_wh_ids = old_ids - new_ids
2901 if to_remove_wh_ids:
2902 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)
2903 if to_remove_route_ids:
2904 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
2908 if 'default_resupply_wh_id' in vals:
2909 if warehouse.default_resupply_wh_id:
2910 #remove the existing resupplying route on all products
2911 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)
2912 for inter_wh_route_id in to_remove_route_ids:
2913 self._unassign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2914 if vals.get('default_resupply_wh_id'):
2915 #assign the new resupplying route on all products
2916 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)
2917 for inter_wh_route_id in to_assign_route_ids:
2918 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2920 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
2922 def unlink(self, cr, uid, ids, context=None):
2923 #TODO try to delete location and route and if not possible, put them in inactive
2924 return super(stock_warehouse, self).unlink(cr, uid, ids, context=context)
2926 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
2927 all_routes = [route.id for route in warehouse.route_ids]
2928 all_routes += [warehouse.mto_pull_id.route_id.id]
2931 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
2933 for wh in self.browse(cr, uid, ids, context=context):
2934 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
2936 domain = [('id', 'in', all_routes)]
2938 'name': _('Warehouse\'s Routes'),
2940 'res_model': 'stock.location.route',
2941 'type': 'ir.actions.act_window',
2943 'view_mode': 'tree,form',
2944 'view_type': 'form',
2948 class stock_location_path(osv.osv):
2949 _name = "stock.location.path"
2950 _description = "Pushed Flows"
2953 def _get_route(self, cr, uid, ids, context=None):
2954 #WARNING TODO route_id is not required, so a field related seems a bad idea >-<
2960 context_with_inactive = context.copy()
2961 context_with_inactive['active_test'] = False
2962 for route in self.pool.get('stock.location.route').browse(cr, uid, ids, context=context_with_inactive):
2963 for push_rule in route.push_ids:
2964 result[push_rule.id] = True
2965 return result.keys()
2967 def _get_rules(self, cr, uid, ids, context=None):
2969 for route in self.browse(cr, uid, ids, context=context):
2970 res += [x.id for x in route.push_ids]
2974 'name': fields.char('Operation Name', size=64, required=True),
2975 'company_id': fields.many2one('res.company', 'Company'),
2976 'route_id': fields.many2one('stock.location.route', 'Route'),
2977 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
2978 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
2979 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
2980 'invoice_state': fields.selection([
2981 ("invoiced", "Invoiced"),
2982 ("2binvoiced", "To Be Invoiced"),
2983 ("none", "Not Applicable")], "Invoice Status",
2985 '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"),
2986 'auto': fields.selection(
2987 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
2989 required=True, select=1,
2990 help="This is used to define paths the product has to follow within the location tree.\n" \
2991 "The 'Automatic Move' value will create a stock move after the current one that will be "\
2992 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
2993 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
2995 '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'),
2996 'active': fields.related('route_id', 'active', type='boolean', string='Active', store={
2997 'stock.location.route': (_get_route, ['active'], 20),
2998 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 20),},
2999 help="If the active field is set to False, it will allow you to hide the rule without removing it." ),
3000 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3001 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3003 'stock.location.route': (_get_rules, ['sequence'], 10),
3004 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3006 'sequence': fields.integer('Sequence'),
3011 'invoice_state': 'none',
3012 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3016 def _apply(self, cr, uid, rule, move, context=None):
3017 move_obj = self.pool.get('stock.move')
3018 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3019 if rule.auto == 'transparent':
3020 old_dest_location = move.location_dest_id.id
3021 move_obj.write(cr, uid, [move.id], {
3023 'date_expected': newdate,
3024 'location_dest_id': rule.location_dest_id.id
3027 #avoid looping if a push rule is not well configured
3028 if rule.location_dest_id.id != old_dest_location:
3029 #call again push_apply to see if a next step is defined
3030 move_obj._push_apply(cr, uid, [move], context=context)
3033 move_id = move_obj.copy(cr, uid, move.id, {
3034 'location_id': move.location_dest_id.id,
3035 'location_dest_id': rule.location_dest_id.id,
3037 'company_id': rule.company_id and rule.company_id.id or False,
3038 'date_expected': newdate,
3039 'picking_id': False,
3040 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3041 'propagate': rule.propagate,
3042 'push_rule_id': rule.id,
3043 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3045 move_obj.write(cr, uid, [move.id], {
3046 'move_dest_id': move_id,
3048 move_obj.action_confirm(cr, uid, [move_id], context=None)
3051 class stock_move_putaway(osv.osv):
3052 _name = 'stock.move.putaway'
3053 _description = 'Proposed Destination'
3055 'move_id': fields.many2one('stock.move', required=True),
3056 'location_id': fields.many2one('stock.location', 'Location', required=True),
3057 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
3058 'quantity': fields.float('Quantity', required=True),
3063 # -------------------------
3064 # Packaging related stuff
3065 # -------------------------
3067 from openerp.report import report_sxw
3068 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
3070 class stock_package(osv.osv):
3072 These are the packages, containing quants and/or other packages
3074 _name = "stock.quant.package"
3075 _description = "Physical Packages"
3076 _parent_name = "parent_id"
3077 _parent_store = True
3078 _parent_order = 'name'
3079 _order = 'parent_left'
3081 def name_get(self, cr, uid, ids, context=None):
3082 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3085 def _complete_name(self, cr, uid, ids, name, args, context=None):
3086 """ Forms complete name of location from parent location to child location.
3087 @return: Dictionary of values
3090 for m in self.browse(cr, uid, ids, context=context):
3092 parent = m.parent_id
3094 res[m.id] = parent.name + ' / ' + res[m.id]
3095 parent = parent.parent_id
3098 def _get_packages(self, cr, uid, ids, context=None):
3099 """Returns packages from quants for store"""
3101 for quant in self.browse(cr, uid, ids, context=context):
3102 if quant.package_id:
3103 res.add(quant.package_id.id)
3106 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3108 for pack in self.browse(cr, uid, ids, context=context):
3111 res.add(pack.parent_id.id)
3114 # TODO: Problem when package is empty!
3116 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3117 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3118 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id})
3119 for pack in self.browse(cr, uid, ids, context=context):
3121 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3122 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3123 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3124 elif pack.children_ids:
3125 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3126 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3127 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3131 'name': fields.char('Package Reference', size=64, select=True),
3132 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3133 'parent_left': fields.integer('Left Parent', select=1),
3134 'parent_right': fields.integer('Right Parent', select=1),
3135 'packaging_id': fields.many2one('product.packaging', 'Type of Packaging'),
3136 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3138 'stock.quant': (_get_packages, ['location_id'], 10),
3139 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3141 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content'),
3142 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict'),
3143 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages'),
3144 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3146 'stock.quant': (_get_packages, ['company_id'], 10),
3147 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3149 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3151 'stock.quant': (_get_packages, ['owner_id'], 10),
3152 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3156 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3158 def _check_location(self, cr, uid, ids, context=None):
3159 '''checks that all quants in a package are stored in the same location'''
3160 quant_obj = self.pool.get('stock.quant')
3161 for pack in self.browse(cr, uid, ids, context=context):
3163 while parent.parent_id:
3164 parent = parent.parent_id
3165 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3166 quants = quant_obj.browse(cr, uid, quant_ids, context=context)
3167 location_id = quants and quants[0].location_id.id or False
3168 if not all([quant.location_id.id == location_id for quant in quants]):
3173 (_check_location, 'Everything inside a package should be in the same location', ['location_id']),
3176 def action_print(self, cr, uid, ids, context=None):
3180 'ids': context.get('active_id') and [context.get('active_id')] or ids,
3181 'model': 'stock.quant.package',
3182 'form': self.read(cr, uid, ids)[0]
3185 'type': 'ir.actions.report.xml',
3186 'report_name': 'stock.quant.package.barcode',
3190 def unpack(self, cr, uid, ids, context=None):
3191 quant_obj = self.pool.get('stock.quant')
3192 for package in self.browse(cr, uid, ids, context=context):
3193 quant_ids = [quant.id for quant in package.quant_ids]
3194 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3195 children_package_ids = [child_package.id for child_package in package.children_ids]
3196 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3197 #delete current package since it contains nothing anymore
3198 self.unlink(cr, uid, ids, context=context)
3199 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3201 def get_content(self, cr, uid, ids, context=None):
3202 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3203 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3205 def get_content_package(self, cr, uid, ids, context=None):
3206 quants_ids = self.get_content(cr, uid, ids, context=context)
3207 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3208 res['domain'] = [('id', 'in', quants_ids)]
3211 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3212 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3213 quant_obj = self.pool.get('stock.quant')
3214 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3216 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3217 if quant.product_id.id == product_id:
3221 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3222 '''This function computes the different product quantities for the given package
3224 quant_obj = self.pool.get('stock.quant')
3226 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3227 if quant.product_id.id not in res:
3228 res[quant.product_id.id] = 0
3229 res[quant.product_id.id] += quant.qty
3232 class stock_pack_operation(osv.osv):
3233 _name = "stock.pack.operation"
3234 _description = "Packing Operation"
3236 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3237 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3238 #if the operation doesn't concern a package, it's not relevant to call this function
3239 if not operation.package_id or operation.product_id:
3240 return {operation.product_id.id: operation.remaining_qty}
3241 #get the total of products the package contains
3242 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3243 #reduce by the quantities linked to a move
3244 for record in operation.linked_move_operation_ids:
3245 if record.move_id.product_id.id not in res:
3246 res[record.move_id.product_id.id] = 0
3247 res[record.move_id.product_id.id] -= record.qty
3250 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3251 uom_obj = self.pool.get('product.uom')
3253 for ops in self.browse(cr, uid, ids, context=context):
3256 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3257 #should use _get_remaining_prod_quantities instead
3259 elif ops.product_id:
3260 qty = ops.product_qty
3261 if ops.product_uom_id:
3262 qty = uom_obj._compute_qty(cr, uid, ops.product_uom_id.id, ops.product_qty, ops.product_id.uom_id.id)
3263 for record in ops.linked_move_operation_ids:
3265 #converting the remaining quantity in the pack operation UoM
3266 if ops.product_uom_id:
3267 qty = uom_obj._compute_qty(cr, uid, ops.product_id.uom_id.id, qty, ops.product_uom_id.id)
3271 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3272 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3273 if product_id and not product_uom_id:
3274 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3275 res['value']['product_uom_id'] = product.uom_id.id
3278 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3280 uom_obj = self.pool.get('product.uom')
3282 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3283 product_uom_id = product_uom_id or product.uom_id.id
3284 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3285 if selected_uom.category_id.id != product.uom_id.category_id.id:
3287 'title': _('Warning: wrong UoM!'),
3288 '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)
3290 if product_qty and 'warning' not in res:
3291 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3292 if rounded_qty != product_qty:
3294 'title': _('Warning: wrong quantity!'),
3295 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3300 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3301 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3302 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3303 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3304 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2
3305 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3306 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3307 'date': fields.datetime('Date', required=True),
3308 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3309 #'update_cost': fields.boolean('Need cost update'),
3310 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3311 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3312 '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'),
3313 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3317 'date': fields.date.context_today,
3320 def process_packaging(self, cr, uid, operation, quants, context=None):
3321 ''' Process the packaging of a given operation, after the quants have been moved. If there was not enough quants found
3322 a quant already has been with the good package information so we don't consider that case in this method'''
3323 quant_obj = self.pool.get("stock.quant")
3324 pack_obj = self.pool.get("stock.quant.package")
3325 for quant, qty in quants:
3327 if operation.product_id:
3328 #if a product + a package information is given, we consider that we took a part of an existing package (unpacking)
3329 quant_obj.write(cr, SUPERUSER_ID, quant.id, {'package_id': operation.result_package_id.id}, context=context)
3330 elif operation.package_id and operation.result_package_id:
3331 #move the whole pack into the final package if any
3332 pack_obj.write(cr, uid, [operation.package_id.id], {'parent_id': operation.result_package_id.id}, context=context)
3337 #TODO: this function can be refactored
3338 def _search_and_increment(self, cr, uid, picking_id, domain, context=None):
3339 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3341 :param domain: list of tuple directly reusable as a domain
3342 context can receive a key 'current_package_id' with the package to consider for this operation
3345 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
3346 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3347 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3348 (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)
3353 #if current_package_id is given in the context, we increase the number of items in this package
3354 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3355 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3356 if existing_operation_ids:
3357 #existing operation found for the given domain and picking => increment its quantity
3358 operation_id = existing_operation_ids[0]
3359 qty = self.browse(cr, uid, operation_id, context=context).product_qty + 1
3360 self.write(cr, uid, operation_id, {'product_qty': qty}, context=context)
3362 #no existing operation found for the given domain and picking => create a new one
3364 'picking_id': picking_id,
3368 var_name, dummy, value = key
3370 if var_name == 'product_id':
3371 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3372 update_dict = {var_name: value}
3374 update_dict['product_uom_id'] = uom_id
3375 values.update(update_dict)
3376 operation_id = self.create(cr, uid, values, context=context)
3380 class stock_move_operation_link(osv.osv):
3382 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3384 _name = "stock.move.operation.link"
3385 _description = "Link between stock moves and pack operations"
3388 '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."),
3389 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3390 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3391 'reserved_quant_ids': fields.one2many('stock.quant', 'link_move_operation_id', 'Reserved quants'),
3394 def get_specific_domain(self, cr, uid, record, context=None):
3395 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3396 having the record given as parameter making the link between the stock move and a pack operation'''
3397 package_obj = self.pool.get('stock.quant.package')
3399 op = record.operation_id
3402 domain.append(('id', 'in', package_obj.get_content(cr, uid, [op.package_id.id], context=context)))
3404 domain.append(('lot_id', '=', op.lot_id.id))
3406 domain.append(('owner_id', '=', op.owner_id.id))
3408 domain.append(('owner_id', '=', False))
3411 class stock_warehouse_orderpoint(osv.osv):
3413 Defines Minimum stock rules.
3415 _name = "stock.warehouse.orderpoint"
3416 _description = "Minimum Inventory Rule"
3418 def get_draft_procurements(self, cr, uid, ids, context=None):
3421 if not isinstance(ids, list):
3423 procurement_obj = self.pool.get('procurement.order')
3424 for orderpoint in self.browse(cr, uid, ids, context=context):
3425 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)
3426 return list(set(procurement_ids))
3428 def _check_product_uom(self, cr, uid, ids, context=None):
3430 Check if the UoM has the same category as the product standard UoM
3435 for rule in self.browse(cr, uid, ids, context=context):
3436 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3441 def action_view_proc_to_process(self, cr, uid, ids, context=None):
3442 act_obj = self.pool.get('ir.actions.act_window')
3443 mod_obj = self.pool.get('ir.model.data')
3444 draft_ids = self.get_draft_procurements(cr, uid, ids, context=context)
3445 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3449 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3450 result['domain'] = "[('id', 'in', [" + ','.join(map(str, draft_ids)) + "])]"
3454 'name': fields.char('Name', size=32, required=True),
3455 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3456 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3457 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3458 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3459 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '!=', 'service')]),
3460 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
3461 'product_min_qty': fields.float('Minimum Quantity', required=True,
3462 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
3463 "a procurement to bring the forecasted quantity to the Max Quantity."),
3464 'product_max_qty': fields.float('Maximum Quantity', required=True,
3465 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
3466 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
3467 'qty_multiple': fields.integer('Qty Multiple', required=True,
3468 help="The procurement quantity will be rounded up to this multiple."),
3469 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
3470 'company_id': fields.many2one('res.company', 'Company', required=True)
3473 'active': lambda *a: 1,
3474 'logic': lambda *a: 'max',
3475 'qty_multiple': lambda *a: 1,
3476 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3477 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
3478 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
3480 _sql_constraints = [
3481 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
3484 (_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']),
3487 def default_get(self, cr, uid, fields, context=None):
3488 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
3489 # default 'warehouse_id' and 'location_id'
3490 if 'warehouse_id' not in res:
3491 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
3492 res['warehouse_id'] = warehouse.id
3493 if 'location_id' not in res:
3494 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
3495 res['location_id'] = warehouse.lot_stock_id.id
3498 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
3499 """ Finds location id for changed warehouse.
3500 @param warehouse_id: Changed id of warehouse.
3501 @return: Dictionary of values.
3504 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
3505 v = {'location_id': w.lot_stock_id.id}
3509 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
3510 """ Finds UoM for changed product.
3511 @param product_id: Changed id of product.
3512 @return: Dictionary of values.
3515 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3516 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
3517 v = {'product_uom': prod.uom_id.id}
3518 return {'value': v, 'domain': d}
3519 return {'domain': {'product_uom': []}}
3521 def copy(self, cr, uid, id, default=None, context=None):
3525 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3527 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
3530 class stock_picking_type(osv.osv):
3531 _name = "stock.picking.type"
3532 _description = "The picking type determines the picking view"
3535 def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
3536 """ Generic method to generate data for bar chart values using SparklineBarWidget.
3537 This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
3539 :param obj: the target model (i.e. crm_lead)
3540 :param domain: the domain applied to the read_group
3541 :param list read_fields: the list of fields to read in the read_group
3542 :param str value_field: the field used to compute the value of the bar slice
3543 :param str groupby_field: the fields used to group
3545 :return list section_result: a list of dicts: [
3546 { 'value': (int) bar_column_value,
3547 'tootip': (str) bar_column_tooltip,
3551 month_begin = date.today().replace(day=1)
3554 'tooltip': (month_begin + relativedelta.relativedelta(months=i)).strftime('%B'),
3555 } for i in range(-2, 2, 1)]
3556 group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
3557 for group in group_obj:
3558 group_begin_date = datetime.strptime(group['__domain'][0][2], DEFAULT_SERVER_DATE_FORMAT)
3559 month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
3560 section_result[-month_delta.months + 2] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
3561 inner_groupby = (group.get('__context', {})).get('group_by',[])
3563 groupby_picking = obj.read_group(cr, uid, group.get('__domain'), read_fields, inner_groupby, context=context)
3564 for groupby in groupby_picking:
3565 section_result[-month_delta.months + 2]['value'] = groupby.get(value_field, 0)
3566 return section_result
3568 def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
3569 picking_obj = self.pool.get('stock.picking')
3570 res = dict.fromkeys(ids, [])
3571 for picking_type_id in ids:
3572 #get last 10 pickings of this type
3573 picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
3575 for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
3576 if picking.date_done > picking.date:
3577 tristates.insert(0, {'tooltip': picking.name + _(': Late'), 'value': -1})
3578 elif picking.backorder_id:
3579 tristates.insert(0, {'tooltip': picking.name + _(': Backorder exists'), 'value': 0})
3581 tristates.insert(0, {'tooltip': picking.name + _(': OK'), 'value': 1})
3582 res[picking_type_id] = tristates
3587 def _get_monthly_pickings(self, cr, uid, ids, field_name, arg, context=None):
3588 obj = self.pool.get('stock.picking')
3589 res = dict.fromkeys(ids, False)
3590 month_begin = date.today().replace(day=1)
3591 groupby_begin = (month_begin + relativedelta.relativedelta(months=-2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3592 groupby_end = (month_begin + relativedelta.relativedelta(months=2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3595 ('picking_type_id', '=', id),
3596 ('state', '=', 'done'),
3597 ('date', '>=', groupby_begin),
3598 ('date', '<', groupby_end),
3600 res[id] = self.__get_bar_values(cr, uid, obj, created_domain, ['date','picking_type_id'], 'picking_type_id_count', ['date','picking_type_id'], context=context)
3603 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
3604 obj = self.pool.get('stock.picking')
3606 'count_picking_draft': [('state', '=', 'draft')],
3607 'count_picking_waiting': [('state','=', 'confirmed')],
3608 'count_picking_ready': [('state','=','assigned')],
3609 'count_picking': [('state','in',('assigned','waiting','confirmed'))],
3610 'count_picking_late': [('min_date','<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state','in',('assigned','waiting','confirmed'))],
3611 'count_picking_backorders': [('backorder_id','!=', False), ('state','in',('confirmed', 'assigned', 'waiting'))],
3614 for field in domains:
3615 data = obj.read_group(cr, uid, domains[field] +
3616 [('state', 'not in',('done','cancel')), ('picking_type_id', 'in', ids)],
3617 ['picking_type_id'], ['picking_type_id'], context=context)
3618 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
3620 result.setdefault(tid, {})[field] = count.get(tid, 0)
3622 if result[tid]['count_picking']:
3623 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] *100 / result[tid]['count_picking']
3624 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] *100 / result[tid]['count_picking']
3626 result[tid]['rate_picking_late'] = 0
3627 result[tid]['rate_picking_backorders'] = 0
3630 #TODO: not returning valus in required format to show in sparkline library,just added latest_picking_waiting need to add proper logic.
3631 def _get_picking_history(self, cr, uid, ids, field_names, arg, context=None):
3632 obj = self.pool.get('stock.picking')
3636 'latest_picking_late': [],
3637 'latest_picking_backorders': [],
3638 'latest_picking_waiting': []
3641 pick_ids = obj.search(cr, uid, [('state', '=','done'), ('picking_type_id','=',type_id)], limit=12, order="date desc", context=context)
3642 for pick in obj.browse(cr, uid, pick_ids, context=context):
3643 result[type_id]['latest_picking_late'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3644 result[type_id]['latest_picking_backorders'] = bool(pick.backorder_id)
3645 result[type_id]['latest_picking_waiting'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3648 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
3649 if not picking_code:
3652 obj_data = self.pool.get('ir.model.data')
3653 stock_loc = obj_data.get_object_reference(cr, uid, 'stock','stock_location_stock')[1]
3656 'default_location_src_id': stock_loc,
3657 'default_location_dest_id': stock_loc,
3659 if picking_code == 'incoming':
3660 result['default_location_src_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_suppliers')[1]
3661 return {'value': result}
3662 if picking_code == 'outgoing':
3663 result['default_location_dest_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_customers')[1]
3664 return {'value': result}
3666 return {'value': result}
3668 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
3669 return dict(self.name_get(cr, uid, ids, context=context))
3671 def name_get(self, cr, uid, ids, context=None):
3672 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
3675 if not isinstance(ids, list):
3680 for record in self.browse(cr, uid, ids, context=context):
3682 if record.warehouse_id:
3683 name = record.warehouse_id.name + ': ' +name
3684 if context.get('special_shortened_wh_name'):
3685 if record.warehouse_id:
3686 name = record.warehouse_id.name
3688 name = _('Customer') + ' (' + record.name + ')'
3689 res.append((record.id, name))
3692 def _default_warehouse(self, cr, uid, context=None):
3693 user = self.pool.get('res.users').browse(cr, uid, uid, context)
3694 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
3695 return res and res[0] or False
3698 'name': fields.char('Name', translate=True, required=True),
3699 'complete_name': fields.function(_get_name, type='char', string='Name'),
3700 'auto_force_assign': fields.boolean('Automatic Availability', help='This picking type does\'t need to check for the availability in source location.'),
3701 'color': fields.integer('Color'),
3702 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
3703 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
3704 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
3705 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
3706 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
3707 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
3708 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
3709 'active': fields.boolean('Active'),
3711 # Statistics for the kanban view
3712 'monthly_picking': fields.function(_get_monthly_pickings,
3714 string='Done Pickings per Month'),
3715 'last_done_picking': fields.function(_get_tristate_values,
3717 string='Last 10 Done Pickings'),
3719 'count_picking_draft': fields.function(_get_picking_count,
3720 type='integer', multi='_get_picking_count'),
3721 'count_picking_ready': fields.function(_get_picking_count,
3722 type='integer', multi='_get_picking_count'),
3723 'count_picking': fields.function(_get_picking_count,
3724 type='integer', multi='_get_picking_count'),
3725 'count_picking_waiting': fields.function(_get_picking_count,
3726 type='integer', multi='_get_picking_count'),
3727 'count_picking_late': fields.function(_get_picking_count,
3728 type='integer', multi='_get_picking_count'),
3729 'count_picking_backorders': fields.function(_get_picking_count,
3730 type='integer', multi='_get_picking_count'),
3732 'rate_picking_late': fields.function(_get_picking_count,
3733 type='integer', multi='_get_picking_count'),
3734 'rate_picking_backorders': fields.function(_get_picking_count,
3735 type='integer', multi='_get_picking_count'),
3737 'latest_picking_late': fields.function(_get_picking_history,
3738 type='string', multi='_get_picking_history'),
3739 'latest_picking_backorders': fields.function(_get_picking_history,
3740 type='string', multi='_get_picking_history'),
3741 'latest_picking_waiting': fields.function(_get_picking_history,
3742 type='string', multi='_get_picking_history'),
3746 'warehouse_id': _default_warehouse,
3751 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: