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'),
177 'sequence': lambda self, cr, uid, ctx: 0,
179 'product_selectable': True,
183 #----------------------------------------------------------
185 #----------------------------------------------------------
187 class stock_quant(osv.osv):
189 Quants are the smallest unit of stock physical instances
191 _name = "stock.quant"
192 _description = "Quants"
194 def _get_quant_name(self, cr, uid, ids, name, args, context=None):
195 """ Forms complete name of location from parent location to child location.
196 @return: Dictionary of values
199 for q in self.browse(cr, uid, ids, context=context):
201 res[q.id] = q.product_id.code or ''
203 res[q.id] = q.lot_id.name
204 res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
207 def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
209 uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
210 for quant in self.browse(cr, uid, ids, context=context):
211 context.pop('force_company', None)
212 if quant.company_id.id != uid_company_id:
213 #if the company of the quant is different than the current user company, force the company in the context
214 #then re-do a browse to read the property fields for the good company.
215 context['force_company'] = quant.company_id.id
216 quant = self.browse(cr, uid, quant.id, context=context)
217 res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
220 def _get_inventory_value(self, cr, uid, quant, context=None):
221 return quant.product_id.standard_price * quant.qty
224 'name': fields.function(_get_quant_name, type='char', string='Identifier'),
225 'product_id': fields.many2one('product.product', 'Product', required=True),
226 'location_id': fields.many2one('stock.location', 'Location', required=True),
227 'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product"),
228 'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant"),
229 'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', store=True),
230 'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for"),
231 '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"),
232 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
233 'cost': fields.float('Unit Cost'),
234 'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant"),
236 'create_date': fields.datetime('Creation Date'),
237 'in_date': fields.datetime('Incoming Date'),
239 'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
240 'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True),
242 # Used for negative quants to reconcile after compensated by a new positive one
243 'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from'),
244 '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'),
245 'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
249 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
252 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
253 ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
254 res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
255 if 'inventory_value' in fields:
257 if '__domain' in line:
258 lines = self.search(cr, uid, line['__domain'], context=context)
260 for line2 in self.browse(cr, uid, lines, context=context):
261 inv_value += line2.inventory_value
262 line['inventory_value'] = inv_value
265 def action_view_quant_history(self, cr, uid, ids, context=None):
267 This function returns an action that display the history of the quant, which
268 mean all the stock moves that lead to this quant creation with this quant quantity.
270 mod_obj = self.pool.get('ir.model.data')
271 act_obj = self.pool.get('ir.actions.act_window')
273 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
274 id = result and result[1] or False
275 result = act_obj.read(cr, uid, [id], context={})[0]
278 for quant in self.browse(cr, uid, ids, context=context):
279 move_ids += [move.id for move in quant.history_ids]
281 result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
284 def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
285 '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
286 is also set to 'assigned'
288 :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
289 :param move: browse record
290 :param link: browse record (stock.move.operation.link)
293 #split quants if needed
294 for quant, qty in quants:
297 self._quant_split(cr, uid, quant, qty, context=context)
298 toreserve.append(quant.id)
301 self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id, 'link_move_operation_id': link and link.id or False}, context=context)
302 #check if move'state needs to be set as 'assigned'
304 if sum([q.qty for q in move.reserved_quant_ids]) == move.product_qty and move.state in ('confirmed', 'waiting'):
305 self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
307 def quants_move(self, cr, uid, quants, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
308 """Moves all given stock.quant in the destination location of the given move.
310 :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
311 :param move: browse record (stock.move)
312 :param lot_id: ID of the lot that mus be set on the quants to move
313 :param owner_id: ID of the partner that must own the quants to move
314 :param src_package_id: ID of the package that contains the quants to move
315 :param dest_package_id: ID of the package that must be set on the moved quant
317 for quant, qty in quants:
319 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
320 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)
321 self.move_single_quant_tuple(cr, uid, quant, qty, move, context=context)
323 def check_preferred_location(self, cr, uid, move, qty, context=None):
324 '''Checks the preferred location on the move, if any returned by a putaway strategy, and returns a list of
325 tuple(location, qty) where the quant have to be moved
327 :param move: browse record (stock.move)
329 :returns: list of tuple build as [(browe record (stock.move), float)]
333 for record in move.putaway_ids:
334 res.append((record.location_id, record.quantity))
336 return [(move.location_dest_id, qty)]
338 def move_single_quant(self, cr, uid, quant, location_to, qty, move, context=None):
339 '''Moves the given 'quant' in 'location_to' for the given 'qty', and logs the stock.move that triggered this move in the quant history.
340 If needed, the quant may be split if it's not totally moved.
342 :param quant: browse record (stock.quant)
343 :param location_to: browse record (stock.location)
345 :param move: browse record (stock.move)
347 new_quant = self._quant_split(cr, uid, quant, qty, context=context)
349 'location_id': location_to.id,
350 'history_ids': [(4, move.id)],
352 #if the quant we are moving had been split and was inside a package, it means we unpacked it
353 if new_quant and new_quant.package_id:
354 vals['package_id'] = False
355 self.write(cr, SUPERUSER_ID, [quant.id], vals, context=context)
359 def move_single_quant_tuple(self, cr, uid, quant, qty, move, context=None):
360 '''Effectively process the move of a tuple (quant record, qty to move). This may result in several quants moved
361 if the preferred locations on the move say so but by default it will only move the quant record given as argument
362 :param quant: browse record (stock.quant)
364 :param move: browse record (stock.move)
366 for location_to, qty in self.check_preferred_location(cr, uid, move, qty, context=context):
369 new_quant = self.move_single_quant(cr, uid, quant, location_to, qty, move, context=context)
370 self._quant_reconcile_negative(cr, uid, quant, context=context)
373 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):
374 ''' This function tries to find quants in the given location for the given domain, by trying to first limit
375 the choice on the quants that match the prefered_domain as well. But if the qty requested is not reached
376 it tries to find the remaining quantity by using the fallback_domain.
378 if prefered_domain and fallback_domain:
381 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)
386 quant_ids.append(quant[0].id)
389 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
391 #make sure the quants aren't found twice (if the prefered_domain and the fallback_domain aren't orthogonal
392 domain += [('id', 'not in', quant_ids)]
393 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)
394 for quant in unprefered_quants:
397 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)
399 def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
401 Use the removal strategies of product to search for the correct quants
402 If you inherit, put the super at the end of your method.
404 :location: browse record of the parent location where the quants have to be found
405 :product: browse record of the product to find
406 :qty in UoM of product
409 domain = domain or [('qty', '>', 0.0)]
410 if restrict_partner_id:
411 domain += [('owner_id', '=', restrict_partner_id)]
413 domain += [('lot_id', '=', restrict_lot_id)]
415 removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context) or 'fifo'
416 if removal_strategy == 'fifo':
417 result += self._quants_get_fifo(cr, uid, location, product, qty, domain, context=context)
418 elif removal_strategy == 'lifo':
419 result += self._quants_get_lifo(cr, uid, location, product, qty, domain, context=context)
421 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
424 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):
425 '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
429 price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
430 location = force_location or move.location_dest_id
432 'product_id': move.product_id.id,
433 'location_id': location.id,
436 'history_ids': [(4, move.id)],
437 'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
438 'company_id': move.company_id.id,
440 'owner_id': owner_id,
441 'package_id': dest_package_id,
444 if move.location_id.usage == 'internal':
445 #if we were trying to move something from an internal location and reach here (quant creation),
446 #it means that a negative quant has to be created as well.
447 negative_vals = vals.copy()
448 negative_vals['location_id'] = move.location_id.id
449 negative_vals['qty'] = -qty
450 negative_vals['cost'] = price_unit
451 negative_vals['negative_dest_location_id'] = move.location_dest_id.id
452 negative_vals['package_id'] = src_package_id
453 negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
454 vals.update({'propagated_from_id': negative_quant_id})
456 #create the quant as superuser, because we want to restrict the creation of quant manually: they should always use this method to create quants
457 quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
458 return self.browse(cr, uid, quant_id, context=context)
460 def _quant_split(self, cr, uid, quant, qty, context=None):
461 context = context or {}
462 if (quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
464 new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty}, context=context)
465 self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
467 return self.browse(cr, uid, new_quant, context=context)
469 def _get_latest_move(self, cr, uid, quant, context=None):
471 for m in quant.history_ids:
472 if not move or m.date > move.date:
476 def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
478 for move in solving_quant.history_ids:
479 path.append((4, move.id))
480 self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
482 def _quant_reconcile_negative(self, cr, uid, quant, context=None):
484 When new quant arrive in a location, try to reconcile it with
485 negative quants. If it's possible, apply the cost of the new
486 quant to the conter-part of the negative quant.
488 if quant.location_id.usage != 'internal':
490 solving_quant = quant
491 dom = [('qty', '<', 0)]
492 dom += [('lot_id', '=', quant.lot_id and quant.lot_id.id or False)]
493 dom += [('owner_id', '=', quant.owner_id and quant.owner_id.id or False)]
494 dom += [('package_id', '=', quant.package_id and quant.package_id.id or False)]
495 quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, [('qty', '<', '0')], context=context)
496 for quant_neg, qty in quants:
499 to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
500 if not to_solve_quant_ids:
503 solved_quant_ids = []
504 for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
507 solved_quant_ids.append(to_solve_quant.id)
508 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
509 solving_qty -= min(solving_qty, to_solve_quant.qty)
510 remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
511 remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
512 #if the reconciliation was not complete, we need to link together the remaining parts
513 if remaining_neg_quant:
514 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
515 if remaining_to_solve_quant_ids:
516 self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
517 #delete the reconciled quants, as it is replaced by the solved quants
518 self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
519 #price update + accounting entries adjustments
520 self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
521 #merge history (and cost?)
522 self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
523 self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
524 solving_quant = remaining_solving_quant
526 def _price_update(self, cr, uid, ids, newprice, context=None):
527 self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
529 def quants_unreserve(self, cr, uid, move, context=None):
530 related_quants = [x.id for x in move.reserved_quant_ids]
531 return self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False, 'link_move_operation_id': False}, context=context)
533 def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
534 ''' Implementation of removal strategies
535 If it can not reserve, it will return a tuple (None, qty)
537 domain += location and [('location_id', 'child_of', location.id)] or []
538 domain += [('product_id', '=', product.id)] + domain
542 quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
544 res.append((None, quantity))
546 for quant in self.browse(cr, uid, quants, context=context):
547 if quantity >= abs(quant.qty):
548 res += [(quant, abs(quant.qty))]
549 quantity -= abs(quant.qty)
551 res += [(quant, quantity)]
557 def _quants_get_fifo(self, cr, uid, location, product, quantity, domain=[], context=None):
559 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
561 def _quants_get_lifo(self, cr, uid, location, product, quantity, domain=[], context=None):
562 order = 'in_date desc'
563 return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
565 def _location_owner(self, cr, uid, quant, location, context=None):
566 ''' Return the company owning the location if any '''
567 return location and (location.usage == 'internal') and location.company_id or False
569 def _check_location(self, cr, uid, ids, context=None):
570 for record in self.browse(cr, uid, ids, context=context):
571 if record.location_id.usage == 'view':
572 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))
575 # FP Note: rehab this, with the auto creation algo
576 # def _check_tracking(self, cr, uid, ids, context=None):
577 # """ Checks if serial number is assigned to stock move or not.
578 # @return: True or False
580 # for move in self.browse(cr, uid, ids, context=context):
581 # if not move.lot_id and \
582 # (move.state == 'done' and \
584 # (move.product_id.track_production and move.location_id.usage == 'production') or \
585 # (move.product_id.track_production and move.location_dest_id.usage == 'production') or \
586 # (move.product_id.track_incoming and move.location_id.usage == 'supplier') or \
587 # (move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \
588 # (move.product_id.track_incoming and move.location_id.usage == 'inventory') \
594 (_check_location, 'You cannot move products to a location of the type view.', ['location_id'])
595 #(_check_tracking, 'You must assign a serial number for this product.', ['prodlot_id']),
599 #----------------------------------------------------------
601 #----------------------------------------------------------
603 class stock_picking(osv.osv):
604 _name = "stock.picking"
605 _inherit = ['mail.thread']
606 _description = "Picking List"
607 _order = "priority desc, date desc, id desc"
609 def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
610 move_obj = self.pool.get("stock.move")
612 move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
613 move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
615 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
616 """ Finds minimum and maximum dates for picking.
617 @return: Dictionary of values
621 res[id] = {'min_date': False, 'max_date': False}
633 picking_id""", (tuple(ids),))
634 for pick, dt1, dt2 in cr.fetchall():
635 res[pick]['min_date'] = dt1
636 res[pick]['max_date'] = dt2
639 def create(self, cr, user, vals, context=None):
640 context = context or {}
641 if ('name' not in vals) or (vals.get('name') in ('/', False)):
642 ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
643 sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
644 vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
645 return super(stock_picking, self).create(cr, user, vals, context)
647 def _state_get(self, cr, uid, ids, field_name, arg, context=None):
648 '''The state of a picking depends on the state of its related stock.move
649 draft: the picking has no line or any one of the lines is draft
650 done, draft, cancel: all lines are done / draft / cancel
651 confirmed, auto, assigned depends on move_type (all at once or direct)
654 for pick in self.browse(cr, uid, ids, context=context):
655 if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
656 res[pick.id] = 'draft'
658 if all([x.state == 'cancel' for x in pick.move_lines]):
659 res[pick.id] = 'cancel'
661 if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
662 res[pick.id] = 'done'
665 order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
666 order_inv = dict(zip(order.values(), order.keys()))
667 lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
668 if pick.move_lines == 'one':
669 res[pick.id] = order_inv[min(lst)]
671 res[pick.id] = order_inv[max(lst)]
674 def _get_pickings(self, cr, uid, ids, context=None):
676 for move in self.browse(cr, uid, ids, context=context):
678 res.add(move.picking_id.id)
681 def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
683 for pick in self.browse(cr, uid, ids, context=context):
685 if pick.pack_operation_ids:
689 def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
691 for pick in self.browse(cr, uid, ids, context=context):
693 for move in pick.move_lines:
694 if move.reserved_quant_ids:
699 def action_assign_owner(self, cr, uid, ids, context=None):
700 for picking in self.browse(cr, uid, ids, context=context):
701 packop_ids = [op.id for op in picking.pack_operation_ids]
702 self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
705 'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
706 'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
707 '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),
708 'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
709 '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"),
710 'state': fields.function(_state_get, type="selection", store={
711 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type', 'move_lines'], 20),
712 'stock.move': (_get_pickings, ['state', 'picking_id'], 20)}, selection=[
714 ('cancel', 'Cancelled'),
715 ('waiting', 'Waiting Another Operation'),
716 ('confirmed', 'Waiting Availability'),
717 ('assigned', 'Ready to Transfer'),
718 ('done', 'Transferred'),
719 ], string='Status', readonly=True, select=True, track_visibility='onchange', help="""
720 * Draft: not confirmed yet and will not be scheduled until confirmed\n
721 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
722 * Waiting Availability: still waiting for the availability of products\n
723 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
724 * Transferred: has been processed, can't be modified or cancelled anymore\n
725 * Cancelled: has been cancelled, can't be confirmed anymore"""
727 'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Priority', required=True),
728 'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
729 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'),
730 'max_date': fields.function(get_min_max_date, multi="min_max_date",
731 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"),
732 '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'),
733 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
734 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
735 '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'),
736 'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
737 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
738 'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', string='Related Packing Operations'),
739 'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
740 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True),
741 '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"),
743 'owner_id': fields.many2one('res.partner', 'Owner', help="Default Owner"),
744 # Used to search on pickings
745 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
746 'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
747 'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
748 'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
750 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
751 'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
756 'name': lambda self, cr, uid, context: '/',
759 'priority': '1', # normal
760 'date': fields.datetime.now,
761 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
764 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
767 def copy(self, cr, uid, id, default=None, context=None):
770 default = default.copy()
771 picking_obj = self.browse(cr, uid, id, context=context)
772 if ('name' not in default) or (picking_obj.name == '/'):
773 default['name'] = '/'
774 if not default.get('backorder_id'):
775 default['backorder_id'] = False
776 default['pack_operation_ids'] = []
777 return super(stock_picking, self).copy(cr, uid, id, default, context)
779 def do_print_delivery(self, cr, uid, ids, context=None):
780 '''This function prints the delivery order'''
781 assert len(ids) == 1, 'This option should only be used for a single id at a time'
783 'model': 'stock.picking',
786 return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list', 'datas': datas, 'nodestroy': True}
788 def do_print_picking(self, cr, uid, ids, context=None):
789 '''This function prints the picking list'''
790 assert len(ids) == 1, 'This option should only be used for a single id at a time'
792 'model': 'stock.picking',
795 return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list.internal', 'datas': datas, 'nodestroy': True}
797 def action_confirm(self, cr, uid, ids, context=None):
799 todo_force_assign = []
800 for picking in self.browse(cr, uid, ids, context=context):
801 if picking.picking_type_id.auto_force_assign:
802 todo_force_assign.append(picking.id)
803 for r in picking.move_lines:
804 if r.state == 'draft':
807 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
809 if todo_force_assign:
810 self.force_assign(cr, uid, todo_force_assign, context=context)
813 def action_assign(self, cr, uid, ids, context=None):
814 """ Check availability of picking moves.
815 This has the effect of changing the state and reserve quants on available moves, and may
816 also impact the state of the picking as it is computed based on move's states.
819 for pick in self.browse(cr, uid, ids, context=context):
820 if pick.state == 'draft':
821 self.action_confirm(cr, uid, [pick.id], context=context)
822 #skip the moves that don't need to be checked
823 move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
825 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
826 self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
829 def force_assign(self, cr, uid, ids, context=None):
830 """ Changes state of picking to available if moves are confirmed or waiting.
833 for pick in self.browse(cr, uid, ids, context=context):
834 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
835 self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
838 def cancel_assign(self, cr, uid, ids, context=None):
839 """ Cancels picking and moves.
842 for pick in self.browse(cr, uid, ids, context=context):
843 move_ids = [x.id for x in pick.move_lines]
844 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids, context=context)
847 def action_cancel(self, cr, uid, ids, context=None):
848 for pick in self.browse(cr, uid, ids, context=context):
849 ids2 = [move.id for move in pick.move_lines]
850 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
853 def action_done(self, cr, uid, ids, context=None):
854 """Changes picking state to done by processing the Stock Moves of the Picking
856 Normally that happens when the button "Done" is pressed on a Picking view.
859 for pick in self.browse(cr, uid, ids, context=context):
861 for move in pick.move_lines:
862 if move.state == 'draft':
863 self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
866 elif move.state in ('assigned', 'confirmed'):
869 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
872 def unlink(self, cr, uid, ids, context=None):
873 #on picking deletion, cancel its move then unlink them too
874 move_obj = self.pool.get('stock.move')
875 context = context or {}
876 for pick in self.browse(cr, uid, ids, context=context):
877 move_ids = [move.id for move in pick.move_lines]
878 move_obj.action_cancel(cr, uid, move_ids, context=context)
879 move_obj.unlink(cr, uid, move_ids, context=context)
880 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
882 def write(self, cr, uid, ids, vals, context=None):
883 res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
884 #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
885 if 'move_lines' in vals or 'pack_operation_ids' in vals:
886 self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
889 def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
890 """ 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.
892 if not backorder_moves:
893 backorder_moves = picking.move_lines
894 backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
895 if 'do_only_split' in context and context['do_only_split']:
896 backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
898 if backorder_move_ids:
899 backorder_id = self.copy(cr, uid, picking.id, {
902 'pack_operation_ids': [],
903 'backorder_id': picking.id,
905 back_order_name = self.browse(cr, uid, backorder_id, context=context).name
906 self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (back_order_name), context=context)
907 move_obj = self.pool.get("stock.move")
908 move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
910 self.pool.get("stock.picking").action_confirm(cr, uid, [picking.id], context=context)
911 self.action_confirm(cr, uid, [backorder_id], context=context)
915 def do_prepare_partial(self, cr, uid, picking_ids, context=None):
917 context = context or {}
918 pack_operation_obj = self.pool.get('stock.pack.operation')
919 pack_obj = self.pool.get("stock.quant.package")
920 quant_obj = self.pool.get("stock.quant")
921 for picking in self.browse(cr, uid, picking_ids, context=context):
922 for move in picking.move_lines:
923 if move.state != 'assigned':
925 #Check which of the reserved quants are entirely in packages (can be in separate method)
926 packages = list(set([x.package_id for x in move.reserved_quant_ids if x.package_id]))
928 for pack in packages:
933 quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
934 if all([x.reservation_id.id == move.id for x in quant_obj.browse(cr, uid, quants, context=context) if x.reservation_id]):
935 good_pack = test_pack.id
936 if test_pack.parent_id:
937 test_pack = test_pack.parent_id
943 done_packages.append(good_pack)
944 done_packages = list(set(done_packages))
946 #Create package operations
947 reserved = set([x.id for x in move.reserved_quant_ids])
948 remaining_qty = move.product_qty
949 for pack in pack_obj.browse(cr, uid, done_packages, context=context):
950 quantl = pack_obj.get_content(cr, uid, [pack.id], context=context)
951 for quant in quant_obj.browse(cr, uid, quantl, context=context):
952 remaining_qty -= quant.qty
953 quants = set(pack_obj.get_content(cr, uid, [pack.id], context=context))
955 pack_operation_obj.create(cr, uid, {
956 'picking_id': picking.id,
957 'package_id': pack.id,
961 yet_to_reserve = list(reserved)
962 #Create operations based on quants
963 for quant in quant_obj.browse(cr, uid, yet_to_reserve, context=context):
964 qty = min(quant.qty, move.product_qty)
966 pack_operation_obj.create(cr, uid, {
967 'picking_id': picking.id,
969 'product_id': quant.product_id.id,
970 'lot_id': quant.lot_id and quant.lot_id.id or False,
971 'product_uom_id': quant.product_id.uom_id.id,
972 'owner_id': quant.owner_id and quant.owner_id.id or False,
974 'package_id': quant.package_id and quant.package_id.id or False,
976 if remaining_qty > 0:
977 pack_operation_obj.create(cr, uid, {
978 'picking_id': picking.id,
979 'product_qty': remaining_qty,
980 'product_id': move.product_id.id,
981 'product_uom_id': move.product_id.uom_id.id,
982 'cost': move.product_id.standard_price,
985 def do_unreserve(self, cr, uid, picking_ids, context=None):
987 Will remove all quants for picking in picking_ids
989 moves_to_unreserve = []
990 for picking in self.browse(cr, uid, picking_ids, context=context):
991 moves_to_unreserve += [m.id for m in picking.move_lines]
992 if moves_to_unreserve:
993 self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
995 def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
996 def _create_link_for_product(product_id, qty):
998 for move in picking.move_lines:
999 if move.product_id.id == product_id:
1000 qty_on_link = min(move.remaining_qty, qty_to_assign)
1001 link_obj.create(cr, uid, {'move_id': move.id, 'operation_id': op.id, 'qty': qty_on_link}, context=context)
1002 qty_to_assign -= qty_on_link
1004 if qty_to_assign <= 0:
1007 link_obj = self.pool.get('stock.move.operation.link')
1008 uom_obj = self.pool.get('product.uom')
1009 package_obj = self.pool.get('stock.quant.package')
1010 for picking in self.browse(cr, uid, picking_ids, context=context):
1011 for op in picking.pack_operation_ids:
1012 to_unlink_ids = [x.id for x in op.linked_move_operation_ids]
1014 link_obj.unlink(cr, uid, to_unlink_ids, context=context)
1016 normalized_qty = uom_obj._compute_qty(cr, uid, op.product_uom_id.id, op.product_qty, op.product_id.uom_id.id)
1017 _create_link_for_product(op.product_id.id, normalized_qty)
1019 for product_id, qty in package_obj._get_all_products_quantities(cr, uid, op.package_id.id, context=context).items():
1020 _create_link_for_product(product_id, qty)
1022 def _create_extra_moves(self, cr, uid, picking, context=None):
1023 '''This function creates move lines on a picking, at the time of do_transfer, based on
1024 unexpected product transfers (or exceeding quantities) found in the pack operations.
1026 move_obj = self.pool.get('stock.move')
1027 operation_obj = self.pool.get('stock.pack.operation')
1028 for op in picking.pack_operation_ids:
1029 for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1030 if remaining_qty > 0:
1031 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1033 'picking_id': picking.id,
1034 'location_id': picking.location_id.id,
1035 'location_dest_id': picking.location_dest_id.id,
1036 'product_id': product_id,
1037 'product_uom': product.uom_id.id,
1038 'product_uom_qty': remaining_qty,
1039 'name': _('Extra Move: ') + product.name,
1040 'state': 'confirmed',
1042 move_obj.create(cr, uid, vals, context=context)
1043 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1045 def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1046 """ Unreserve quants then try to reassign quants."""
1047 stock_move_obj = self.pool.get('stock.move')
1049 self.do_unreserve(cr, uid, [picking.id], context=context)
1050 self.action_assign(cr, uid, [picking.id], context=context)
1052 stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1053 stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1055 def do_transfer(self, cr, uid, picking_ids, context=None):
1057 If no pack operation, we do simple action_done of the picking
1058 Otherwise, do the pack operations
1062 stock_move_obj = self.pool.get('stock.move')
1063 for picking in self.browse(cr, uid, picking_ids, context=context):
1064 if not picking.pack_operation_ids:
1065 self.action_done(cr, uid, [picking.id], context=context)
1068 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1069 #create extra moves in the picking (unexpected product moves coming from pack operations)
1070 self._create_extra_moves(cr, uid, picking, context=context)
1072 #split move lines eventually
1074 toassign_move_ids = []
1075 for move in picking.move_lines:
1076 if move.state == 'draft':
1077 toassign_move_ids.append(move.id)
1078 if move.remaining_qty == 0:
1079 if move.state in ('draft', 'assigned', 'confirmed'):
1080 todo_move_ids.append(move.id)
1081 elif move.remaining_qty > 0:
1082 new_move = stock_move_obj.split(cr, uid, move, move.remaining_qty, context=context)
1083 todo_move_ids.append(move.id)
1084 #Assign move as it was assigned before
1085 toassign_move_ids.append(new_move)
1087 #this should never happens
1089 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1090 if todo_move_ids and not context.get('do_only_split'):
1091 self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1092 elif context.get('do_only_split'):
1093 context.update({'split': todo_move_ids})
1095 self._create_backorder(cr, uid, picking, context=context)
1096 if toassign_move_ids:
1097 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1100 def do_split(self, cr, uid, picking_ids, context=None):
1101 """ just split the picking (create a backorder) without making it 'done' """
1104 ctx = context.copy()
1105 ctx['do_only_split'] = True
1106 return self.do_transfer(cr, uid, picking_ids, context=ctx)
1108 def get_next_picking_for_ui(self, cr, uid, context=None):
1109 """ returns the next pickings to process. Used in the barcode scanner UI"""
1112 domain = [('state', 'in', ('confirmed', 'assigned'))]
1113 if context.get('default_picking_type_id'):
1114 domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1115 return self.search(cr, uid, domain, context=context)
1117 def action_done_from_ui(self, cr, uid, picking_id, context=None):
1118 """ called when button 'done' in pused in the barcode scanner UI """
1119 self.do_transfer(cr, uid, [picking_id], context=context)
1120 #return id of next picking to work on
1121 return self.get_next_picking_for_ui(cr, uid, context=context)
1123 def action_pack(self, cr, uid, picking_ids, context=None):
1124 """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1125 Used in the barcode scanner UI and the normal interface as well. """
1126 stock_operation_obj = self.pool.get('stock.pack.operation')
1127 package_obj = self.pool.get('stock.quant.package')
1128 for picking_id in picking_ids:
1129 operation_ids = stock_operation_obj.search(cr, uid, [('picking_id', '=', picking_id), ('result_package_id', '=', False)], context=context)
1131 package_id = package_obj.create(cr, uid, {}, context=context)
1132 stock_operation_obj.write(cr, uid, operation_ids, {'result_package_id': package_id}, context=context)
1135 def process_product_id_from_ui(self, cr, uid, picking_id, product_id, context=None):
1136 return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id)], context=context)
1138 def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, context=None):
1139 '''This function is called each time there barcode scanner reads an input'''
1140 lot_obj = self.pool.get('stock.production.lot')
1141 package_obj = self.pool.get('stock.quant.package')
1142 product_obj = self.pool.get('product.product')
1143 stock_operation_obj = self.pool.get('stock.pack.operation')
1144 #check if the barcode correspond to a product
1145 matching_product_ids = product_obj.search(cr, uid, [('ean13', '=', barcode_str)], context=context)
1146 if matching_product_ids:
1147 self.process_product_id_from_ui(cr, uid, picking_id, matching_product_ids[0], context=context)
1149 #check if the barcode correspond to a lot
1150 matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1151 if matching_lot_ids:
1152 lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1153 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], context=context)
1155 #check if the barcode correspond to a package
1156 matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1157 if matching_package_ids:
1158 stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], context=context)
1161 class stock_production_lot(osv.osv):
1162 _name = 'stock.production.lot'
1163 _inherit = ['mail.thread']
1164 _description = 'Lot/Serial'
1166 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1167 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1168 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1169 'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants'),
1170 'create_date': fields.datetime('Creation Date'),
1173 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1174 'product_id': lambda x, y, z, c: c.get('product_id', False),
1176 _sql_constraints = [
1177 ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1181 # ----------------------------------------------------
1183 # ----------------------------------------------------
1185 class stock_move(osv.osv):
1186 _name = "stock.move"
1187 _description = "Stock Move"
1188 _order = 'date_expected desc, id'
1191 def get_price_unit(self, cr, uid, move, context=None):
1192 """ Returns the unit price to store on the quant """
1193 return move.price_unit or move.product_id.standard_price
1195 def name_get(self, cr, uid, ids, context=None):
1197 for line in self.browse(cr, uid, ids, context=context):
1198 name = line.location_id.name + ' > ' + line.location_dest_id.name
1199 if line.product_id.code:
1200 name = line.product_id.code + ': ' + name
1201 if line.picking_id.origin:
1202 name = line.picking_id.origin + '/ ' + name
1203 res.append((line.id, name))
1206 def create(self, cr, uid, vals, context=None):
1207 if vals.get('product_id') and not vals.get('price_unit'):
1208 prod_obj = self.pool.get('product.product')
1209 vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price
1210 return super(stock_move, self).create(cr, uid, vals, context=context)
1212 def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1213 uom_obj = self.pool.get('product.uom')
1215 for m in self.browse(cr, uid, ids, context=context):
1216 res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False)
1219 def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1220 uom_obj = self.pool.get('product.uom')
1222 for move in self.browse(cr, uid, ids, context=context):
1223 qty = move.product_qty
1224 for record in move.linked_move_operation_ids:
1226 #converting the remaining quantity in the move UoM
1227 res[move.id] = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1230 def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1231 res = dict.fromkeys(ids, False)
1232 for move in self.browse(cr, uid, ids, context=context):
1233 if move.state == 'done':
1234 res[move.id] = [q.id for q in move.quant_ids]
1236 res[move.id] = [q.id for q in move.reserved_quant_ids]
1239 def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1240 quant_obj = self.pool.get('stock.quant')
1241 res = dict.fromkeys(ids, False)
1242 for move in self.browse(cr, uid, ids, context=context):
1243 if move.state == 'done':
1244 res[move.id] = move.product_qty
1246 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1247 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1249 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1250 availability += quant.qty
1251 res[move.id] = min(move.product_qty, availability)
1254 def _get_move(self, cr, uid, ids, context=None):
1256 for quant in self.browse(cr, uid, ids, context=context):
1257 if quant.reservation_id:
1258 res.add(quant.reservation_id.id)
1262 'name': fields.char('Description', required=True, select=True),
1263 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1264 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1265 '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)]}),
1266 'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1267 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1268 # TODO: improve store to add dependency on product UoM
1269 'product_qty': fields.function(_quantity_normalize, type='float', store=True, string='Quantity',
1270 digits_compute=dp.get_precision('Product Unit of Measure'),
1271 help='Quantity in the default UoM of the product'),
1272 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1273 required=True, states={'done': [('readonly', True)]},
1274 help="This is the quantity of products from an inventory "
1275 "point of view. For moves in the state 'done', this is the "
1276 "quantity of products that were actually moved. For other "
1277 "moves, this is the quantity of product that is planned to "
1278 "be moved. Lowering this quantity does not generate a "
1279 "backorder. Changing this quantity on assigned moves affects "
1280 "the product reservation, and should be done with care."
1282 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1283 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1284 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1286 'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1288 '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."),
1289 '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."),
1291 # FP Note: should we remove this?
1292 '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"),
1295 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1296 'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1298 'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1299 'picking_priority': fields.related('picking_id', 'priority', type='selection', selection=[('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Picking Priority'),
1300 'note': fields.text('Notes'),
1301 'state': fields.selection([('draft', 'New'),
1302 ('cancel', 'Cancelled'),
1303 ('waiting', 'Waiting Another Move'),
1304 ('confirmed', 'Waiting Availability'),
1305 ('assigned', 'Available'),
1307 ], 'Status', readonly=True, select=True,
1308 help= "* New: When the stock move is created and not yet confirmed.\n"\
1309 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1310 "* 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"\
1311 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1312 "* Done: When the shipment is processed, the state is \'Done\'."),
1314 '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
1316 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1317 'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1318 'origin': fields.char("Source"),
1319 '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."),
1321 # used for colors in tree views:
1322 'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1324 'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1325 'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1326 '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'),
1327 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1328 digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1329 'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1330 'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1331 'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1332 'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1333 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1334 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1335 'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1336 'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'),
1337 'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1338 'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1339 'availability': fields.function(_get_product_availability, type='float', string='Availability'),
1340 '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'"),
1341 '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'"),
1342 'putaway_ids': fields.one2many('stock.move.putaway', 'move_id', 'Put Away Suggestions'),
1343 '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"),
1344 '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)."),
1347 def _default_location_destination(self, cr, uid, context=None):
1348 context = context or {}
1349 if context.get('default_picking_type_id', False):
1350 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1351 return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1354 def _default_location_source(self, cr, uid, context=None):
1355 context = context or {}
1356 if context.get('default_picking_type_id', False):
1357 pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1358 return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1361 def _default_destination_address(self, cr, uid, context=None):
1362 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1363 return user.company_id.partner_id.id
1366 'location_id': _default_location_source,
1367 'location_dest_id': _default_location_destination,
1368 'partner_id': _default_destination_address,
1372 'product_uom_qty': 1.0,
1374 'date': fields.datetime.now,
1375 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1376 'date_expected': fields.datetime.now,
1377 'procure_method': 'make_to_stock',
1381 def _check_uom(self, cr, uid, ids, context=None):
1382 for move in self.browse(cr, uid, ids, context=context):
1383 if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1389 '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.',
1392 def copy_data(self, cr, uid, id, default=None, context=None):
1395 default = default.copy()
1396 default['move_orig_ids'] = []
1397 default['quant_ids'] = []
1398 default['reserved_quant_ids'] = []
1399 default['returned_move_ids'] = []
1400 default['linked_move_operation_ids'] = []
1401 default['origin_returned_move_id'] = False
1402 default['state'] = 'draft'
1403 return super(stock_move, self).copy_data(cr, uid, id, default, context)
1405 def do_unreserve(self, cr, uid, move_ids, context=None):
1406 quant_obj = self.pool.get("stock.quant")
1407 for move in self.browse(cr, uid, move_ids, context=context):
1408 quant_obj.quants_unreserve(cr, uid, move, context=context)
1410 for putaway_rec in move.putaway_ids:
1411 putaway_values.append((2, putaway_rec.id))
1412 self.write(cr, uid, [move.id], {'state': 'confirmed', 'putaway_ids': putaway_values}, context=context)
1414 def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1415 origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1416 group_id = move.group_id and move.group_id.id or False
1418 if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1419 group_id = move.rule_id.group_id.id
1420 elif move.rule_id.group_propagation_option == 'none':
1423 'name': move.rule_id and move.rule_id.name or "/",
1425 'company_id': move.company_id and move.company_id.id or False,
1426 'date_planned': move.date,
1427 'product_id': move.product_id.id,
1428 'product_qty': move.product_qty,
1429 'product_uom': move.product_uom.id,
1430 'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1431 'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1432 'location_id': move.location_id.id,
1433 'move_dest_id': move.id,
1434 'group_id': group_id,
1435 'route_ids': [(4, x.id) for x in move.route_ids],
1436 'warehouse_id': move.warehouse_id and move.warehouse_id.id or False,
1439 def _push_apply(self, cr, uid, moves, context=None):
1440 push_obj = self.pool.get("stock.location.path")
1442 if not move.move_dest_id:
1443 domain = [('location_from_id', '=', move.location_dest_id.id)]
1444 if move.warehouse_id:
1445 domain += ['|', ('warehouse_id', '=', move.warehouse_id.id), ('warehouse_id', '=', False)]
1446 #priority goes to the route defined on the product and product category
1447 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1448 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1450 #but if there's no rule matching, we try without filtering on routes
1451 rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context)
1453 rule = push_obj.browse(cr, uid, rules[0], context=context)
1454 push_obj._apply(cr, uid, rule, move, context=context)
1457 # Create the stock.move.putaway records
1458 def _putaway_apply(self, cr, uid, move, putaway, context=None):
1459 # Should call different methods here in later versions
1460 moveputaway_obj = self.pool.get('stock.move.putaway')
1461 quant_obj = self.pool.get('stock.quant')
1462 if putaway.method == 'fixed' and putaway.location_spec_id:
1463 for row in quant_obj.read_group(cr, uid, [('reservation_id', '=', move.id)], ['qty', 'lot_id'], ['lot_id'], context=context):
1466 'location_id': putaway.location_spec_id.id,
1467 'quantity': row['qty'],
1468 'lot_id': row.get('lot_id') and row['lot_id'][0] or False,
1470 moveputaway_obj.create(cr, SUPERUSER_ID, vals, context=context)
1472 def _putaway_check(self, cr, uid, ids, context=None):
1473 for move in self.browse(cr, uid, ids, context=context):
1474 putaway = self.pool.get('stock.location').get_putaway_strategy(cr, uid, move.location_dest_id, move.product_id, context=context)
1476 self._putaway_apply(cr, uid, move, putaway, context=context)
1478 def _create_procurement(self, cr, uid, move, context=None):
1479 """ This will create a procurement order """
1480 return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1482 def write(self, cr, uid, ids, vals, context=None):
1485 if isinstance(ids, (int, long)):
1487 # Check that we do not modify a stock.move which is done
1488 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1489 for move in self.browse(cr, uid, ids, context=context):
1490 if move.state == 'done':
1491 if frozen_fields.intersection(vals):
1492 raise osv.except_osv(_('Operation Forbidden!'),
1493 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1494 propagated_changes_dict = {}
1495 #propagation of quantity change
1496 if vals.get('product_uom_qty'):
1497 propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1498 if vals.get('product_uom_id'):
1499 propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1500 #propagation of expected date:
1501 propagated_date_field = False
1502 if vals.get('date_expected'):
1503 #propagate any manual change of the expected date
1504 propagated_date_field = 'date_expected'
1505 elif (vals.get('state', '') == 'done' and vals.get('date')):
1506 #propagate also any delta observed when setting the move as done
1507 propagated_date_field = 'date'
1509 if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1510 #any propagation is (maybe) needed
1511 for move in self.browse(cr, uid, ids, context=context):
1512 if move.move_dest_id and move.propagate:
1513 if 'date_expected' in propagated_changes_dict:
1514 propagated_changes_dict.pop('date_expected')
1515 if propagated_date_field:
1516 current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1517 new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1518 delta = new_date - current_date
1519 if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1520 old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1521 new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1522 propagated_changes_dict['date_expected'] = new_move_date
1523 #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1524 #Note that, for pulled moves we intentionally don't propagate on the procurement.
1525 if propagated_changes_dict:
1526 self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1527 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1529 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1530 """ On change of product quantity finds UoM and UoS quantities
1531 @param product_id: Product id
1532 @param product_qty: Changed Quantity of product
1533 @param product_uom: Unit of measure of product
1534 @param product_uos: Unit of sale of product
1535 @return: Dictionary of values
1538 'product_uos_qty': 0.00
1542 if (not product_id) or (product_qty <= 0.0):
1543 result['product_qty'] = 0.0
1544 return {'value': result}
1546 product_obj = self.pool.get('product.product')
1547 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1549 # Warn if the quantity was decreased
1551 for move in self.read(cr, uid, ids, ['product_qty']):
1552 if product_qty < move['product_qty']:
1554 'title': _('Information'),
1555 'message': _("By changing this quantity here, you accept the "
1556 "new quantity as complete: OpenERP will not "
1557 "automatically generate a back order.")})
1560 if product_uos and product_uom and (product_uom != product_uos):
1561 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1563 result['product_uos_qty'] = product_qty
1565 return {'value': result, 'warning': warning}
1567 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1568 product_uos, product_uom):
1569 """ On change of product quantity finds UoM and UoS quantities
1570 @param product_id: Product id
1571 @param product_uos_qty: Changed UoS Quantity of product
1572 @param product_uom: Unit of measure of product
1573 @param product_uos: Unit of sale of product
1574 @return: Dictionary of values
1577 'product_uom_qty': 0.00
1581 if (not product_id) or (product_uos_qty <= 0.0):
1582 result['product_uos_qty'] = 0.0
1583 return {'value': result}
1585 product_obj = self.pool.get('product.product')
1586 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1588 # Warn if the quantity was decreased
1589 for move in self.read(cr, uid, ids, ['product_uos_qty']):
1590 if product_uos_qty < move['product_uos_qty']:
1592 'title': _('Warning: No Back Order'),
1593 'message': _("By changing the quantity here, you accept the "
1594 "new quantity as complete: OpenERP will not "
1595 "automatically generate a Back Order.")})
1598 if product_uos and product_uom and (product_uom != product_uos):
1599 result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1601 result['product_uom_qty'] = product_uos_qty
1602 return {'value': result, 'warning': warning}
1604 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1605 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1606 @param prod_id: Changed Product id
1607 @param loc_id: Source location id
1608 @param loc_dest_id: Destination location id
1609 @param partner_id: Address id of partner
1610 @return: Dictionary of values
1614 user = self.pool.get('res.users').browse(cr, uid, uid)
1615 lang = user and user.lang or False
1617 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1619 lang = addr_rec and addr_rec.lang or False
1620 ctx = {'lang': lang}
1622 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1623 uos_id = product.uos_id and product.uos_id.id or False
1625 'product_uom': product.uom_id.id,
1626 'product_uos': uos_id,
1627 'product_uom_qty': 1.00,
1628 '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'],
1631 result['name'] = product.partner_ref
1633 result['location_id'] = loc_id
1635 result['location_dest_id'] = loc_dest_id
1636 return {'value': result}
1638 def _picking_assign(self, cr, uid, move, context=None):
1639 if move.picking_id or not move.picking_type_id:
1641 context = context or {}
1642 pick_obj = self.pool.get("stock.picking")
1644 group = move.group_id and move.group_id.id or False
1645 picks = pick_obj.search(cr, uid, [
1646 ('group_id', '=', group),
1647 ('location_id', '=', move.location_id.id),
1648 ('location_dest_id', '=', move.location_dest_id.id),
1649 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1654 'origin': move.origin,
1655 'company_id': move.company_id and move.company_id.id or False,
1656 'move_type': move.group_id and move.group_id.move_type or 'one',
1657 'partner_id': move.group_id and move.group_id.partner_id and move.group_id.partner_id.id or False,
1658 'date_done': move.date_expected,
1659 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1661 pick = pick_obj.create(cr, uid, values, context=context)
1662 move.write({'picking_id': pick})
1665 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1666 """ On change of Scheduled Date gives a Move date.
1667 @param date_expected: Scheduled Date
1668 @param date: Move Date
1671 if not date_expected:
1672 date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1673 return {'value': {'date': date_expected}}
1675 def action_confirm(self, cr, uid, ids, context=None):
1676 """ Confirms stock move or put it in waiting if it's linked to another move.
1677 @return: List of ids.
1683 for move in self.browse(cr, uid, ids, context=context):
1685 for m in move.move_orig_ids:
1686 if m.state not in ('done', 'cancel'):
1688 states[state].append(move.id)
1689 self._picking_assign(cr, uid, move, context=context)
1691 for state, write_ids in states.items():
1693 self.write(cr, uid, write_ids, {'state': state})
1694 if state == 'confirmed':
1695 for move in self.browse(cr, uid, write_ids, context=context):
1696 if move.procure_method == 'make_to_order':
1697 self._create_procurement(cr, uid, move, context=context)
1698 moves = self.browse(cr, uid, ids, context=context)
1699 self._push_apply(cr, uid, moves, context=context)
1702 def force_assign(self, cr, uid, ids, context=None):
1703 """ Changes the state to assigned.
1706 self.action_assign(cr, uid, ids, context=context)
1707 self.write(cr, uid, ids, {'state': 'assigned'})
1710 def cancel_assign(self, cr, uid, ids, context=None):
1711 """ Changes the state to confirmed.
1714 return self.write(cr, uid, ids, {'state': 'confirmed'})
1716 def action_assign(self, cr, uid, ids, context=None):
1717 """ Checks the product type and accordingly writes the state.
1718 @return: No. of moves done
1720 context = context or {}
1721 quant_obj = self.pool.get("stock.quant")
1723 for move in self.browse(cr, uid, ids, context=context):
1724 if move.state not in ('confirmed', 'waiting', 'assigned'):
1726 if move.product_id.type == 'consu':
1727 done.append(move.id)
1730 #build the prefered domain based on quants that moved in previous linked done move
1732 for m2 in move.move_orig_ids:
1733 for q in m2.quant_ids:
1734 prev_quant_ids.append(q.id)
1735 prefered_domain = prev_quant_ids and [('id', 'in', prev_quant_ids)] or []
1736 fallback_domain = prev_quant_ids and [('id', 'not in', prev_quant_ids)] or []
1737 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
1738 main_domain = [('reservation_id', '=', False), ('qty', '>', 0)]
1739 #first try to find quants based on specific domains given by linked operations
1740 for record in move.linked_move_operation_ids:
1741 domain = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1742 qty_already_assigned = sum([q.qty for q in record.reserved_quant_ids])
1743 qty = record.qty - qty_already_assigned
1744 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)
1745 quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
1746 #then if the move isn't totally assigned, try to find quants without any specific domain
1747 if move.state != 'assigned':
1748 qty_already_assigned = sum([q.qty for q in move.reserved_quant_ids])
1749 qty = move.product_qty - qty_already_assigned
1750 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)
1751 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
1753 self._putaway_check(cr, uid, ids, context=context)
1755 def action_cancel(self, cr, uid, ids, context=None):
1756 """ Cancels the moves and if all moves are cancelled it cancels the picking.
1759 procurement_obj = self.pool.get('procurement.order')
1760 context = context or {}
1761 for move in self.browse(cr, uid, ids, context=context):
1762 if move.state == 'done':
1763 raise osv.except_osv(_('Operation Forbidden!'),
1764 _('You cannot cancel a stock move that has been set to \'Done\'.'))
1765 if move.reserved_quant_ids:
1766 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
1767 if context.get('cancel_procurement'):
1769 procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
1770 procurement_obj.cancel(cr, uid, procurement_ids, context=context)
1771 elif move.move_dest_id:
1772 #cancel chained moves
1774 self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
1775 elif move.move_dest_id.state == 'waiting':
1776 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'})
1777 return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1779 def action_done(self, cr, uid, ids, context=None):
1780 """ Makes the move done and if all moves are done, it will finish the picking.
1781 It assumes that quants are already assigned to stock moves.
1782 Putaway strategies should be applied
1785 context = context or {}
1786 quant_obj = self.pool.get("stock.quant")
1787 pack_op_obj = self.pool.get("stock.pack.operation")
1788 todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
1790 self.action_confirm(cr, uid, todo, context=context)
1793 procurement_ids = []
1794 for move in self.browse(cr, uid, ids, context=context):
1796 pickings.add(move.picking_id.id)
1797 qty = move.product_qty
1798 main_domain = [('qty', '>', 0)]
1799 prefered_domain = [('reservation_id', '=', move.id)]
1800 fallback_domain = [('reservation_id', '=', False)]
1801 #first, process the move per linked operation first because it may imply some specific domains to consider
1802 for record in move.linked_move_operation_ids:
1803 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1804 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, context=context)
1806 if not record.operation_id.package_id:
1807 #if a package and a result_package is given, we don't enter here because it will be processed by process_packaging() later
1808 #but for operations having only result_package_id, we will create new quants in the final package directly
1809 package_id = record.operation_id.result_package_id.id or False
1810 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)
1812 pack_op_obj.process_packaging(cr, uid, record.operation_id, quants, context=context)
1814 #then if the total quantity processed this way isn't enough, process the remaining quantity without any specific domain
1816 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, context=context)
1817 quant_obj.quants_move(cr, uid, quants, move, context=context)
1818 #unreserve the quants and make them available for other operations/moves
1819 quant_obj.quants_unreserve(cr, uid, move, context=context)
1821 #Check moves that were pushed
1822 if move.move_dest_id.state in ('waiting', 'confirmed'):
1823 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
1824 ('move_dest_id', '=', move.move_dest_id.id)], context=context)
1825 #If no other moves for the move that got pushed:
1826 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
1827 self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
1828 if move.procurement_id:
1829 procurement_ids.append(move.procurement_id.id)
1830 self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1831 self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
1834 def unlink(self, cr, uid, ids, context=None):
1835 context = context or {}
1836 for move in self.browse(cr, uid, ids, context=context):
1837 if move.state not in ('draft', 'cancel'):
1838 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
1839 return super(stock_move, self).unlink(cr, uid, ids, context=context)
1841 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1842 """ Move the scrap/damaged product into scrap location
1843 @param cr: the database cursor
1844 @param uid: the user id
1845 @param ids: ids of stock move object to be scrapped
1846 @param quantity : specify scrap qty
1847 @param location_id : specify scrap location
1848 @param context: context arguments
1849 @return: Scraped lines
1851 #quantity should be given in MOVE UOM
1853 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
1855 for move in self.browse(cr, uid, ids, context=context):
1856 source_location = move.location_id
1857 if move.state == 'done':
1858 source_location = move.location_dest_id
1859 #Previously used to prevent scraping from virtual location but not necessary anymore
1860 #if source_location.usage != 'internal':
1861 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
1862 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
1863 move_qty = move.product_qty
1864 uos_qty = quantity / move_qty * move.product_uos_qty
1866 'location_id': source_location.id,
1867 'product_uom_qty': quantity,
1868 'product_uos_qty': uos_qty,
1869 'state': move.state,
1871 'location_dest_id': location_id,
1872 #TODO lot_id is now on quant and not on move, need to do something for this
1873 #'lot_id': move.lot_id.id,
1875 new_move = self.copy(cr, uid, move.id, default_val)
1878 product_obj = self.pool.get('product.product')
1879 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
1881 uom = product.uom_id.name if product.uom_id else ''
1882 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
1883 move.picking_id.message_post(body=message)
1885 self.action_done(cr, uid, res, context=context)
1888 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
1889 """ 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
1890 @param ids: ids of stock move object to be consumed
1891 @param quantity : specify consume quantity (given in move UoM)
1892 @param location_id : specify source location
1893 @return: Consumed lines
1895 uom_obj = self.pool.get('product.uom')
1899 raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
1901 for move in self.browse(cr, uid, ids, context=context):
1902 move_qty = move.product_qty
1903 uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, quantity, move.product_uom.id)
1905 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
1906 quantity_rest = move.product_qty - uom_qty
1907 if quantity_rest > 0:
1908 ctx = context.copy()
1910 ctx['source_location_id'] = location_id
1911 res.append(self.split(cr, uid, move, move_qty - quantity_rest, ctx))
1915 self.write(cr, uid, [move.id], {'location_id': location_id}, context=context)
1917 self.action_done(cr, uid, res, context=context)
1920 def split(self, cr, uid, move, qty, context=None):
1921 """ Splits qty from move move into a new move
1922 :param move: browse record
1923 :param qty: float. quantity to split (given in product UoM)
1924 :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
1926 if move.product_qty <= qty or qty == 0:
1929 uom_obj = self.pool.get('product.uom')
1930 context = context or {}
1932 uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1933 uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
1935 if move.state in ('done', 'cancel'):
1936 raise osv.except_osv(_('Error'), _('You cannot split a move done'))
1939 'product_uom_qty': uom_qty,
1940 'product_uos_qty': uos_qty,
1941 'state': move.state,
1942 'procure_method': 'make_to_stock',
1943 'move_dest_id': False,
1944 'reserved_quant_ids': []
1946 if context.get('source_location_id'):
1947 defaults['location_id'] = context['source_location_id']
1948 new_move = self.copy(cr, uid, move.id, defaults)
1950 ctx = context.copy()
1951 ctx['do_not_propagate'] = True
1952 self.write(cr, uid, [move.id], {
1953 'product_uom_qty': move.product_uom_qty - uom_qty,
1954 'product_uos_qty': move.product_uos_qty - uos_qty,
1955 #'reserved_quant_ids': [(6,0,[])] SHOULD NOT CHANGE as it has been reserved already
1958 if move.move_dest_id and move.propagate:
1959 new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
1960 self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
1962 self.action_confirm(cr, uid, [new_move], context=context)
1965 class stock_inventory(osv.osv):
1966 _name = "stock.inventory"
1967 _description = "Inventory"
1969 def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
1971 for inv in self.browse(cr, uid, ids, context=context):
1977 def _get_available_filters(self, cr, uid, context=None):
1979 This function will return the list of filter allowed according to the options checked
1980 in 'Settings\Warehouse'.
1982 :rtype: list of tuple
1984 #default available choices
1985 res_filter = [('none', ' All products of a whole location'), ('product', 'One product only')]
1986 settings_obj = self.pool.get('stock.config.settings')
1987 config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1988 #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
1992 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1993 if stock_settings.group_stock_tracking_owner:
1994 res_filter.append(('owner', _('One owner only')))
1995 res_filter.append(('product_owner', _('One product for a specific owner')))
1996 if stock_settings.group_stock_production_lot:
1997 res_filter.append(('lot', _('One Lot/Serial Number')))
1998 if stock_settings.group_stock_tracking_lot:
1999 res_filter.append(('pack', _('A Pack')))
2003 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2004 'date': fields.datetime('Inventory Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Create Date."),
2005 'date_done': fields.datetime('Date done', help="Inventory Validation Date."),
2006 'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
2007 'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves."),
2008 'state': fields.selection([('draft', 'Draft'), ('cancel', 'Cancelled'), ('confirm', 'In Progress'), ('done', 'Validated')], 'Status', readonly=True, select=True),
2009 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2010 'location_id': fields.many2one('stock.location', 'Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2011 'product_id': fields.many2one('product.product', 'Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2012 '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."),
2013 'partner_id': fields.many2one('res.partner', 'Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2014 '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."),
2015 'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2016 'filter': fields.selection(_get_available_filters, 'Selection Filter'),
2019 def _default_stock_location(self, cr, uid, context=None):
2021 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2022 return warehouse.lot_stock_id.id
2027 'date': fields.datetime.now,
2029 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2030 'location_id': _default_stock_location,
2033 def set_checked_qty(self, cr, uid, ids, context=None):
2034 inventory = self.browse(cr, uid, ids[0], context=context)
2035 line_ids = [line.id for line in inventory.line_ids]
2036 self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2039 def copy(self, cr, uid, id, default=None, context=None):
2042 default = default.copy()
2043 default.update({'move_ids': [], 'date_done': False})
2044 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2046 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2047 """ Creates a stock move from an inventory line
2048 @param inventory_line:
2052 return self.pool.get('stock.move').create(cr, uid, move_vals)
2054 def action_done(self, cr, uid, ids, context=None):
2055 """ Finish the inventory
2060 move_obj = self.pool.get('stock.move')
2061 for inv in self.browse(cr, uid, ids, context=context):
2062 if not inv.move_ids:
2063 self.action_check(cr, uid, [inv.id], context=context)
2065 #the action_done on stock_move has to be done in 2 steps:
2066 #first, we start moving the products from stock to inventory loss
2067 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage == 'internal'], context=context)
2068 #then, we move from inventory loss. This 2 steps process is needed because some moved quant may need to be put again in stock
2069 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage != 'internal'], context=context)
2070 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2073 def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2074 stock_move_obj = self.pool.get('stock.move')
2075 product_obj = self.pool.get('product.product')
2076 inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2078 'name': _('INV:') + (inventory.name or ''),
2079 'product_id': todo_line['product_id'],
2080 'product_uom': todo_line['product_uom_id'],
2081 'date': inventory.date,
2082 'company_id': inventory.company_id.id,
2083 'inventory_id': inventory.id,
2084 'state': 'assigned',
2085 'restrict_lot_id': todo_line.get('prod_lot_id'),
2086 'restrict_partner_id': todo_line.get('partner_id'),
2089 if todo_line['product_qty'] < 0:
2090 #found more than expected
2091 vals['location_id'] = inventory_location_id
2092 vals['location_dest_id'] = todo_line['location_id']
2093 vals['product_uom_qty'] = -todo_line['product_qty']
2095 #found less than expected
2096 vals['location_id'] = todo_line['location_id']
2097 vals['location_dest_id'] = inventory_location_id
2098 vals['product_uom_qty'] = todo_line['product_qty']
2099 return stock_move_obj.create(cr, uid, vals, context=context)
2101 def action_check(self, cr, uid, ids, context=None):
2102 """ Checks the inventory and computes the stock move to do
2105 inventory_line_obj = self.pool.get('stock.inventory.line')
2106 stock_move_obj = self.pool.get('stock.move')
2107 for inventory in self.browse(cr, uid, ids, context=context):
2108 #first remove the existing stock moves linked to this inventory
2109 move_ids = [move.id for move in inventory.move_ids]
2110 stock_move_obj.unlink(cr, uid, move_ids, context=context)
2111 #compute what should be in the inventory lines
2112 theorical_lines = self._get_inventory_lines(cr, uid, inventory, context=context)
2113 for line in inventory.line_ids:
2114 #compare the inventory lines to the theorical ones and store the diff in theorical_lines
2115 inventory_line_obj._resolve_inventory_line(cr, uid, line, theorical_lines, context=context)
2116 #each theorical_lines where product_qty is not 0 is a difference for which we need to create a stock move
2117 for todo_line in theorical_lines:
2118 if todo_line['product_qty'] != 0:
2119 self._create_stock_move(cr, uid, inventory, todo_line, context=context)
2121 def action_cancel_draft(self, cr, uid, ids, context=None):
2122 """ Cancels the stock move and change inventory state to draft.
2125 for inv in self.browse(cr, uid, ids, context=context):
2126 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2127 self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2130 def action_cancel_inventory(self, cr, uid, ids, context=None):
2132 self.action_cancel_draft(cr, uid, ids, context=context)
2134 def prepare_inventory(self, cr, uid, ids, context=None):
2135 inventory_line_obj = self.pool.get('stock.inventory.line')
2136 for inventory in self.browse(cr, uid, ids, context=context):
2137 #clean the existing inventory lines before redoing an inventory proposal
2138 line_ids = [line.id for line in inventory.line_ids]
2139 inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2140 #compute the inventory lines and create them
2141 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2142 for product_line in vals:
2143 inventory_line_obj.create(cr, uid, product_line, context=context)
2144 return self.write(cr, uid, ids, {'state': 'confirm'})
2146 def _get_inventory_lines(self, cr, uid, inventory, context=None):
2147 location_obj = self.pool.get('stock.location')
2148 product_obj = self.pool.get('product.product')
2149 location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2150 domain = ' location_id in %s'
2151 args = (tuple(location_ids),)
2152 if inventory.partner_id:
2153 domain += ' and owner_id = %s'
2154 args += (inventory.partner_id.id,)
2155 if inventory.lot_id:
2156 domain += ' and lot_id = %s'
2157 args += (inventory.lot_id.id,)
2158 if inventory.product_id:
2159 domain += 'and product_id = %s'
2160 args += (inventory.product_id.id,)
2161 if inventory.package_id:
2162 domain += ' and package_id = %s'
2163 args += (inventory.package_id.id,)
2165 SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2166 FROM stock_quant WHERE''' + domain + '''
2167 GROUP BY product_id, location_id, lot_id, package_id, partner_id
2170 for product_line in cr.dictfetchall():
2171 #replace the None the dictionary by False, because falsy values are tested later on
2172 for key, value in product_line.items():
2174 product_line[key] = False
2175 product_line['inventory_id'] = inventory.id
2176 product_line['th_qty'] = product_line['product_qty']
2177 if product_line['product_id']:
2178 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2179 product_line['product_uom_id'] = product.uom_id.id
2180 vals.append(product_line)
2183 class stock_inventory_line(osv.osv):
2184 _name = "stock.inventory.line"
2185 _description = "Inventory Line"
2186 _rec_name = "inventory_id"
2188 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2189 'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2190 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2191 'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2192 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2193 'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2194 'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2195 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2196 'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2197 'th_qty': fields.float('Theoretical Quantity', readonly=True),
2198 'partner_id': fields.many2one('res.partner', 'Owner'),
2205 def _resolve_inventory_line(self, cr, uid, inventory_line, theorical_lines, context=None):
2206 #TODO : package_id management !
2208 uom_obj = self.pool.get('product.uom')
2209 for th_line in theorical_lines:
2210 #We try to match the inventory line with a theorical line with same product, lot, location and owner
2211 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:
2212 uom_reference = inventory_line.product_id.uom_id
2213 real_qty = uom_obj._compute_qty_obj(cr, uid, inventory_line.product_uom_id, inventory_line.product_qty, uom_reference)
2214 th_line['product_qty'] -= real_qty
2217 #if it was still not found, we add it to the theorical lines so that it will create a stock move for it
2220 'inventory_id': inventory_line.inventory_id.id,
2221 'location_id': inventory_line.location_id.id,
2222 'product_id': inventory_line.product_id.id,
2223 'product_uom_id': inventory_line.product_id.uom_id.id,
2224 'product_qty': -inventory_line.product_qty,
2225 'prod_lot_id': inventory_line.prod_lot_id.id,
2226 'partner_id': inventory_line.partner_id.id,
2228 theorical_lines.append(vals)
2230 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):
2231 """ Changes UoM and name if product_id changes.
2232 @param location_id: Location id
2233 @param product: Changed product_id
2234 @param uom: UoM product
2235 @return: Dictionary of changed values
2237 context = context or {}
2239 return {'value': {'product_qty': 0.0, 'product_uom_id': False}}
2240 uom_obj = self.pool.get('product.uom')
2241 ctx = context.copy()
2242 ctx['location'] = location_id
2243 ctx['lot_id'] = lot_id
2244 ctx['owner_id'] = owner_id
2245 ctx['package_id'] = package_id
2246 obj_product = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
2247 th_qty = obj_product.qty_available
2248 if uom and uom != obj_product.uom_id.id:
2249 uom_record = uom_obj.browse(cr, uid, uom, context=context)
2250 th_qty = uom_obj._compute_qty_obj(cr, uid, obj_product.uom_id, th_qty, uom_record)
2251 return {'value': {'th_qty': th_qty, 'product_uom_id': uom or obj_product.uom_id.id}}
2254 #----------------------------------------------------------
2256 #----------------------------------------------------------
2257 class stock_warehouse(osv.osv):
2258 _name = "stock.warehouse"
2259 _description = "Warehouse"
2262 'name': fields.char('Name', size=128, required=True, select=True),
2263 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2264 'partner_id': fields.many2one('res.partner', 'Address'),
2265 'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2266 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2267 'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2268 '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'),
2269 'reception_steps': fields.selection([
2270 ('one_step', 'Receive goods directly in stock (1 step)'),
2271 ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2272 ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', required=True),
2273 'delivery_steps': fields.selection([
2274 ('ship_only', 'Ship directly from stock (Ship only)'),
2275 ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2276 ('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),
2277 'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2278 'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2279 'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2280 'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2281 'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2282 'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2283 'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2284 'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2285 'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2286 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2287 'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2288 'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2289 'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2290 'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2291 'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2292 'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes'),
2293 'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse'),
2296 def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2297 resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2298 if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id
2299 resupply_wh_ids.add(default_resupply_wh_id)
2300 resupply_wh_ids = list(resupply_wh_ids)
2301 return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2303 def _get_inter_wh_location(self, cr, uid, warehouse, context=None):
2304 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2305 data_obj = self.pool.get('ir.model.data')
2307 inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2309 inter_wh_loc = False
2312 def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None):
2313 return self.pool.get('product.product').search(cr, uid, [], context=context)
2315 def _assign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2316 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2317 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2319 def _unassign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2320 product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2321 self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(3, inter_wh_route_id)]}, context=context)
2323 def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2325 'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2326 'warehouse_selectable': False,
2327 'product_selectable': True,
2328 'product_categ_selectable': True,
2329 'supplied_wh_id': warehouse.id,
2330 'supplier_wh_id': wh.id,
2333 def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2334 location_obj = self.pool.get('stock.location')
2335 route_obj = self.pool.get('stock.location.route')
2336 pull_obj = self.pool.get('procurement.rule')
2337 #create route selectable on the product to resupply the warehouse from another one
2338 inter_wh_location_id = self._get_inter_wh_location(cr, uid, warehouse, context=context)
2339 if inter_wh_location_id:
2340 input_loc = warehouse.wh_input_stock_loc_id
2341 if warehouse.reception_steps == 'one_step':
2342 input_loc = warehouse.lot_stock_id
2343 inter_wh_location = location_obj.browse(cr, uid, inter_wh_location_id, context=context)
2344 for wh in supplier_warehouses:
2345 output_loc = wh.wh_output_stock_loc_id
2346 if wh.delivery_steps == 'ship_only':
2347 output_loc = wh.lot_stock_id
2348 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2349 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2350 values = [(output_loc, inter_wh_location, wh.out_type_id.id, wh), (inter_wh_location, input_loc, warehouse.in_type_id.id, warehouse)]
2351 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2352 for pull_rule in pull_rules_list:
2353 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2354 #if the warehouse is also set as default resupply method, assign this route automatically to all product
2355 if default_resupply_wh and default_resupply_wh.id == wh.id:
2356 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2357 #finally, save the route on the warehouse
2358 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2360 def _default_stock_id(self, cr, uid, context=None):
2361 #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2363 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2364 return warehouse.lot_stock_id.id
2369 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2370 'lot_stock_id': _default_stock_id,
2371 'reception_steps': 'one_step',
2372 'delivery_steps': 'ship_only',
2374 _sql_constraints = [
2375 ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2376 ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2377 ('default_resupply_wh_diff', 'check (id != default_resupply_wh_id)', 'The default resupply warehouse should be different that the warehouse itself!'),
2380 def _get_partner_locations(self, cr, uid, ids, context=None):
2381 ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2382 data_obj = self.pool.get('ir.model.data')
2383 location_obj = self.pool.get('stock.location')
2385 customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2386 supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2388 customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2389 customer_loc = customer_loc and customer_loc[0] or False
2390 supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2391 supplier_loc = supplier_loc and supplier_loc[0] or False
2392 if not (customer_loc and supplier_loc):
2393 raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2394 return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2396 def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2397 location_obj = self.pool.get('stock.location')
2399 new_reception_step = new_reception_step or warehouse.reception_steps
2400 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2401 if warehouse.reception_steps != new_reception_step:
2402 location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2403 if new_reception_step != 'one_step':
2404 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2405 if new_reception_step == 'three_steps':
2406 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2408 if warehouse.delivery_steps != new_delivery_step:
2409 location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2410 if new_delivery_step != 'ship_only':
2411 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2412 if new_delivery_step == 'pick_pack_ship':
2413 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2416 def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2418 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2419 'product_categ_selectable': True,
2420 'product_selectable': False,
2424 def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2425 pull_rules_list = []
2426 for from_loc, dest_loc, pick_type_id, warehouse in values:
2427 pull_rules_list.append({
2428 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2429 'location_src_id': from_loc.id,
2430 'location_id': dest_loc.id,
2431 'route_id': new_route_id,
2433 'picking_type_id': pick_type_id,
2434 'procure_method': 'make_to_order',
2435 'warehouse_id': supplied_warehouse.id,
2436 'propagate_warehouse_id': warehouse.id,
2438 return pull_rules_list
2440 def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2442 push_rules_list = []
2443 pull_rules_list = []
2444 for from_loc, dest_loc, pick_type_id in values:
2445 push_rules_list.append({
2446 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2447 'location_from_id': from_loc.id,
2448 'location_dest_id': dest_loc.id,
2449 'route_id': new_route_id,
2451 'picking_type_id': pick_type_id,
2453 'warehouse_id': warehouse.id,
2455 pull_rules_list.append({
2456 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2457 'location_src_id': from_loc.id,
2458 'location_id': dest_loc.id,
2459 'route_id': new_route_id,
2461 'picking_type_id': pick_type_id,
2462 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2464 'warehouse_id': warehouse.id,
2467 return push_rules_list, pull_rules_list
2469 def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2470 route_obj = self.pool.get('stock.location.route')
2471 data_obj = self.pool.get('ir.model.data')
2473 mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2475 mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2476 mto_route_id = mto_route_id and mto_route_id[0] or False
2477 if not mto_route_id:
2478 raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
2480 from_loc, dest_loc, pick_type_id = values[0]
2482 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2483 'location_src_id': from_loc.id,
2484 'location_id': dest_loc.id,
2485 'route_id': mto_route_id,
2487 'picking_type_id': pick_type_id,
2488 'procure_method': 'make_to_order',
2490 'warehouse_id': warehouse.id,
2493 def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2495 'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2496 'warehouse_selectable': False,
2497 'product_selectable': True,
2498 'product_categ_selectable': True,
2499 'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
2503 def create_routes(self, cr, uid, ids, warehouse, context=None):
2505 route_obj = self.pool.get('stock.location.route')
2506 pull_obj = self.pool.get('procurement.rule')
2507 push_obj = self.pool.get('stock.location.path')
2508 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2509 #create reception route and rules
2510 route_name, values = routes_dict[warehouse.reception_steps]
2511 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2512 reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
2513 wh_route_ids.append((4, reception_route_id))
2514 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
2515 #create the push/pull rules
2516 for push_rule in push_rules_list:
2517 push_obj.create(cr, uid, vals=push_rule, context=context)
2518 for pull_rule in pull_rules_list:
2519 #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
2520 pull_rule['procure_method'] = 'make_to_order'
2521 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2523 #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
2524 route_name, values = routes_dict[warehouse.delivery_steps]
2525 route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2526 #create the route and its pull rules
2527 delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
2528 wh_route_ids.append((4, delivery_route_id))
2529 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
2530 for pull_rule in pull_rules_list:
2531 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2532 #create MTO pull rule and link it to the generic MTO route
2533 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2534 mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
2536 #create a route for cross dock operations, that can be set on products and product categories
2537 route_name, values = routes_dict['crossdock']
2538 crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
2539 crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
2540 wh_route_ids.append((4, crossdock_route_id))
2541 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)
2542 for pull_rule in pull_rules_list:
2543 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2545 #create route selectable on the product to resupply the warehouse from another one
2546 self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
2548 #return routes and mto pull rule to store on the warehouse
2550 'route_ids': wh_route_ids,
2551 'mto_pull_id': mto_pull_id,
2552 'reception_route_id': reception_route_id,
2553 'delivery_route_id': delivery_route_id,
2554 'crossdock_route_id': crossdock_route_id,
2557 def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2558 picking_type_obj = self.pool.get('stock.picking.type')
2559 pull_obj = self.pool.get('procurement.rule')
2560 push_obj = self.pool.get('stock.location.path')
2561 route_obj = self.pool.get('stock.location.route')
2562 new_reception_step = new_reception_step or warehouse.reception_steps
2563 new_delivery_step = new_delivery_step or warehouse.delivery_steps
2565 #change the default source and destination location and (de)activate picking types
2566 input_loc = warehouse.wh_input_stock_loc_id
2567 if new_reception_step == 'one_step':
2568 input_loc = warehouse.lot_stock_id
2569 output_loc = warehouse.wh_output_stock_loc_id
2570 if new_delivery_step == 'ship_only':
2571 output_loc = warehouse.lot_stock_id
2572 picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
2573 picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
2574 picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
2575 picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
2577 routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2578 #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
2579 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
2580 route_name, values = routes_dict[new_delivery_step]
2581 route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2582 dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
2583 #create the pull rules
2584 for pull_rule in pull_rules_list:
2585 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2587 #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
2588 pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
2589 push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
2590 route_name, values = routes_dict[new_reception_step]
2591 route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2592 push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
2593 #create the push/pull rules
2594 for push_rule in push_rules_list:
2595 push_obj.create(cr, uid, vals=push_rule, context=context)
2596 for pull_rule in pull_rules_list:
2597 #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
2598 pull_rule['procure_method'] = 'make_to_order'
2599 pull_obj.create(cr, uid, vals=pull_rule, context=context)
2601 route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
2604 dummy, values = routes_dict[new_delivery_step]
2605 mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2606 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
2609 def create(self, cr, uid, vals, context=None):
2614 data_obj = self.pool.get('ir.model.data')
2615 seq_obj = self.pool.get('ir.sequence')
2616 picking_type_obj = self.pool.get('stock.picking.type')
2617 location_obj = self.pool.get('stock.location')
2619 #create view location for warehouse
2620 wh_loc_id = location_obj.create(cr, uid, {
2621 'name': _(vals.get('name')),
2623 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
2625 vals['view_location_id'] = wh_loc_id
2626 #create all location
2627 def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
2628 reception_steps = vals.get('reception_steps', def_values['reception_steps'])
2629 delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
2630 context_with_inactive = context.copy()
2631 context_with_inactive['active_test'] = False
2633 {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
2634 {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
2635 {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
2636 {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
2637 {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
2639 for values in sub_locations:
2640 location_id = location_obj.create(cr, uid, {
2641 'name': values['name'],
2642 'usage': 'internal',
2643 'location_id': wh_loc_id,
2644 'active': values['active'],
2645 }, context=context_with_inactive)
2646 vals[values['field']] = location_id
2648 #create new sequences
2649 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)
2650 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)
2651 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)
2652 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)
2653 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)
2656 new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
2658 warehouse = self.browse(cr, uid, new_id, context=context)
2659 wh_stock_loc = warehouse.lot_stock_id
2660 wh_input_stock_loc = warehouse.wh_input_stock_loc_id
2661 wh_output_stock_loc = warehouse.wh_output_stock_loc_id
2662 wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
2664 #fetch customer and supplier locations, for references
2665 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context)
2667 #create in, out, internal picking types for warehouse
2668 input_loc = wh_input_stock_loc
2669 if warehouse.reception_steps == 'one_step':
2670 input_loc = wh_stock_loc
2671 output_loc = wh_output_stock_loc
2672 if warehouse.delivery_steps == 'ship_only':
2673 output_loc = wh_stock_loc
2675 #choose the next available color for the picking types of this warehouse
2677 available_colors = [c%9 for c in range(3, 12)] # put flashy colors first
2678 all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
2679 #don't use sets to preserve the list order
2680 for x in all_used_colors:
2681 if x['color'] in available_colors:
2682 available_colors.remove(x['color'])
2683 if available_colors:
2684 color = available_colors[0]
2686 #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship.
2687 max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
2688 max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
2690 in_type_id = picking_type_obj.create(cr, uid, vals={
2691 'name': _('Receptions'),
2692 'warehouse_id': new_id,
2694 'auto_force_assign': True,
2695 'sequence_id': in_seq_id,
2696 'default_location_src_id': supplier_loc.id,
2697 'default_location_dest_id': input_loc.id,
2698 'sequence': max_sequence + 1,
2699 'color': color}, context=context)
2700 out_type_id = picking_type_obj.create(cr, uid, vals={
2701 'name': _('Delivery Orders'),
2702 'warehouse_id': new_id,
2704 'sequence_id': out_seq_id,
2705 'default_location_src_id': output_loc.id,
2706 'default_location_dest_id': customer_loc.id,
2707 'sequence': max_sequence + 4,
2708 'color': color}, context=context)
2709 int_type_id = picking_type_obj.create(cr, uid, vals={
2710 'name': _('Internal Transfers'),
2711 'warehouse_id': new_id,
2713 'sequence_id': int_seq_id,
2714 'default_location_src_id': wh_stock_loc.id,
2715 'default_location_dest_id': wh_stock_loc.id,
2717 'sequence': max_sequence + 2,
2718 'color': color}, context=context)
2719 pack_type_id = picking_type_obj.create(cr, uid, vals={
2721 'warehouse_id': new_id,
2723 'sequence_id': pack_seq_id,
2724 'default_location_src_id': wh_pack_stock_loc.id,
2725 'default_location_dest_id': output_loc.id,
2726 'active': delivery_steps == 'pick_pack_ship',
2727 'sequence': max_sequence + 3,
2728 'color': color}, context=context)
2729 pick_type_id = picking_type_obj.create(cr, uid, vals={
2731 'warehouse_id': new_id,
2733 'sequence_id': pick_seq_id,
2734 'default_location_src_id': wh_stock_loc.id,
2735 'default_location_dest_id': wh_pack_stock_loc.id,
2736 'active': delivery_steps != 'ship_only',
2737 'sequence': max_sequence + 2,
2738 'color': color}, context=context)
2740 #write picking types on WH
2742 'in_type_id': in_type_id,
2743 'out_type_id': out_type_id,
2744 'pack_type_id': pack_type_id,
2745 'pick_type_id': pick_type_id,
2746 'int_type_id': int_type_id,
2748 super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context)
2751 #create routes and push/pull rules
2752 new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
2753 self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
2756 def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
2757 return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
2759 def _format_routename(self, cr, uid, obj, name, context=None):
2760 return obj.name + ': ' + name
2762 def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
2763 #fetch customer and supplier locations, for references
2764 customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
2767 'one_step': (_('Reception in 1 step'), []),
2768 'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
2769 '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)]),
2770 '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)]),
2771 'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
2772 '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)]),
2773 '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)]),
2776 def _handle_renaming(self, cr, uid, warehouse, name, context=None):
2777 location_obj = self.pool.get('stock.location')
2778 route_obj = self.pool.get('stock.location.route')
2779 pull_obj = self.pool.get('procurement.rule')
2780 push_obj = self.pool.get('stock.location.path')
2782 location_id = warehouse.lot_stock_id.location_id.id
2783 location_obj.write(cr, uid, location_id, {'name': name}, context=context)
2784 #rename route and push-pull rules
2785 for route in warehouse.route_ids:
2786 route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
2787 for pull in route.pull_ids:
2788 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2789 for push in route.push_ids:
2790 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2791 #change the mto pull rule name
2792 pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
2794 def write(self, cr, uid, ids, vals, context=None):
2797 if isinstance(ids, (int, long)):
2799 seq_obj = self.pool.get('ir.sequence')
2800 route_obj = self.pool.get('stock.location.route')
2802 context_with_inactive = context.copy()
2803 context_with_inactive['active_test'] = False
2804 for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
2805 #first of all, check if we need to delete and recreate route
2806 if vals.get('reception_steps') or vals.get('delivery_steps'):
2807 #activate and deactivate location according to reception and delivery option
2808 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
2809 # switch between route
2810 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
2811 if vals.get('code') or vals.get('name'):
2812 name = warehouse.name
2814 if vals.get('name'):
2815 name = vals.get('name')
2816 self._handle_renaming(cr, uid, warehouse, name, context=context_with_inactive)
2817 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)
2818 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)
2819 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)
2820 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)
2821 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)
2822 if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
2823 for cmd in vals.get('resupply_wh_ids'):
2825 new_ids = set(cmd[2])
2826 old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
2827 to_add_wh_ids = new_ids - old_ids
2829 supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
2830 self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
2831 to_remove_wh_ids = old_ids - new_ids
2832 if to_remove_wh_ids:
2833 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)
2834 if to_remove_route_ids:
2835 route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
2839 if 'default_resupply_wh_id' in vals:
2840 if warehouse.default_resupply_wh_id:
2841 #remove the existing resupplying route on all products
2842 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)
2843 for inter_wh_route_id in to_remove_route_ids:
2844 self._unassign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2845 if vals.get('default_resupply_wh_id'):
2846 #assign the new resupplying route on all products
2847 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)
2848 for inter_wh_route_id in to_assign_route_ids:
2849 self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2851 return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
2853 def unlink(self, cr, uid, ids, context=None):
2854 #TODO try to delete location and route and if not possible, put them in inactive
2855 return super(stock_warehouse, self).unlink(cr, uid, ids, context=context)
2857 def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
2858 all_routes = [route.id for route in warehouse.route_ids]
2859 all_routes += [warehouse.mto_pull_id.route_id.id]
2862 def view_all_routes_for_wh(self, cr, uid, ids, context=None):
2864 for wh in self.browse(cr, uid, ids, context=context):
2865 all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
2867 domain = [('id', 'in', all_routes)]
2869 'name': _('Warehouse\'s Routes'),
2871 'res_model': 'stock.location.route',
2872 'type': 'ir.actions.act_window',
2874 'view_mode': 'tree,form',
2875 'view_type': 'form',
2879 class stock_location_path(osv.osv):
2880 _name = "stock.location.path"
2881 _description = "Pushed Flows"
2884 def _get_route(self, cr, uid, ids, context=None):
2885 #WARNING TODO route_id is not required, so a field related seems a bad idea >-<
2891 context_with_inactive = context.copy()
2892 context_with_inactive['active_test'] = False
2893 for route in self.pool.get('stock.location.route').browse(cr, uid, ids, context=context_with_inactive):
2894 for push_rule in route.push_ids:
2895 result[push_rule.id] = True
2896 return result.keys()
2898 def _get_rules(self, cr, uid, ids, context=None):
2900 for route in self.browse(cr, uid, ids):
2901 res += [x.id for x in route.push_ids]
2905 'name': fields.char('Operation Name', size=64, required=True),
2906 'company_id': fields.many2one('res.company', 'Company'),
2907 'route_id': fields.many2one('stock.location.route', 'Route'),
2908 'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
2909 'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
2910 'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
2911 'invoice_state': fields.selection([
2912 ("invoiced", "Invoiced"),
2913 ("2binvoiced", "To Be Invoiced"),
2914 ("none", "Not Applicable")], "Invoice Status",
2916 '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"),
2917 'auto': fields.selection(
2918 [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
2920 required=True, select=1,
2921 help="This is used to define paths the product has to follow within the location tree.\n" \
2922 "The 'Automatic Move' value will create a stock move after the current one that will be "\
2923 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
2924 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
2926 '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'),
2927 'active': fields.related('route_id', 'active', type='boolean', string='Active', store={
2928 'stock.location.route': (_get_route, ['active'], 20),
2929 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 20),},
2930 help="If the active field is set to False, it will allow you to hide the rule without removing it." ),
2931 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
2932 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
2934 'stock.location.route': (_get_rules, ['sequence'], 10),
2935 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
2937 'sequence': fields.integer('Sequence'),
2942 'invoice_state': 'none',
2943 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
2947 def _apply(self, cr, uid, rule, move, context=None):
2948 move_obj = self.pool.get('stock.move')
2949 newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
2950 if rule.auto == 'transparent':
2951 old_dest_location = move.location_dest_id.id
2952 move_obj.write(cr, uid, [move.id], {
2954 'date_expected': newdate,
2955 'location_dest_id': rule.location_dest_id.id
2958 #avoid looping if a push rule is not well configured
2959 if rule.location_dest_id.id != old_dest_location:
2960 #call again push_apply to see if a next step is defined
2961 move_obj._push_apply(cr, uid, [move], context=context)
2964 move_id = move_obj.copy(cr, uid, move.id, {
2965 'location_id': move.location_dest_id.id,
2966 'location_dest_id': rule.location_dest_id.id,
2968 'company_id': rule.company_id and rule.company_id.id or False,
2969 'date_expected': newdate,
2970 'picking_id': False,
2971 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
2972 'propagate': rule.propagate,
2973 'push_rule_id': rule.id,
2974 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
2976 move_obj.write(cr, uid, [move.id], {
2977 'move_dest_id': move_id,
2979 move_obj.action_confirm(cr, uid, [move_id], context=None)
2982 class stock_move_putaway(osv.osv):
2983 _name = 'stock.move.putaway'
2984 _description = 'Proposed Destination'
2986 'move_id': fields.many2one('stock.move', required=True),
2987 'location_id': fields.many2one('stock.location', 'Location', required=True),
2988 'lot_id': fields.many2one('stock.production.lot', 'Lot'),
2989 'quantity': fields.float('Quantity', required=True),
2994 # -------------------------
2995 # Packaging related stuff
2996 # -------------------------
2998 from openerp.report import report_sxw
2999 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
3001 class stock_package(osv.osv):
3003 These are the packages, containing quants and/or other packages
3005 _name = "stock.quant.package"
3006 _description = "Physical Packages"
3007 _parent_name = "parent_id"
3008 _parent_store = True
3009 _parent_order = 'name'
3010 _order = 'parent_left'
3012 def name_get(self, cr, uid, ids, context=None):
3013 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3016 def _complete_name(self, cr, uid, ids, name, args, context=None):
3017 """ Forms complete name of location from parent location to child location.
3018 @return: Dictionary of values
3021 for m in self.browse(cr, uid, ids, context=context):
3023 parent = m.parent_id
3025 res[m.id] = parent.name + ' / ' + res[m.id]
3026 parent = parent.parent_id
3029 def _get_packages(self, cr, uid, ids, context=None):
3030 """Returns packages from quants for store"""
3032 for quant in self.browse(cr, uid, ids, context=context):
3033 if quant.package_id:
3034 res.add(quant.package_id.id)
3037 def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3039 for pack in self.browse(cr, uid, ids, context=context):
3042 res.add(pack.parent_id.id)
3045 # TODO: Problem when package is empty!
3047 def _get_package_info(self, cr, uid, ids, name, args, context=None):
3048 default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3049 res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id})
3050 for pack in self.browse(cr, uid, ids, context=context):
3052 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3053 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3054 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3055 elif pack.children_ids:
3056 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3057 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3058 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3062 'name': fields.char('Package Reference', size=64, select=True),
3063 'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3064 'parent_left': fields.integer('Left Parent', select=1),
3065 'parent_right': fields.integer('Right Parent', select=1),
3066 'packaging_id': fields.many2one('product.packaging', 'Type of Packaging'),
3067 'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3069 'stock.quant': (_get_packages, ['location_id'], 10),
3070 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3072 'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content'),
3073 'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict'),
3074 'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages'),
3075 'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package",
3077 'stock.quant': (_get_packages, ['company_id'], 10),
3078 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3080 'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3082 'stock.quant': (_get_packages, ['owner_id'], 10),
3083 'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3087 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3089 def _check_location(self, cr, uid, ids, context=None):
3090 '''checks that all quants in a package are stored in the same location'''
3091 quant_obj = self.pool.get('stock.quant')
3092 for pack in self.browse(cr, uid, ids, context=context):
3094 while parent.parent_id:
3095 parent = parent.parent_id
3096 quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3097 quants = quant_obj.browse(cr, uid, quant_ids, context=context)
3098 location_id = quants and quants[0].location_id.id or False
3099 if not all([quant.location_id.id == location_id for quant in quants]):
3104 (_check_location, 'Everything inside a package should be in the same location', ['location_id']),
3107 def action_print(self, cr, uid, ids, context=None):
3111 'ids': context.get('active_id') and [context.get('active_id')] or ids,
3112 'model': 'stock.quant.package',
3113 'form': self.read(cr, uid, ids)[0]
3116 'type': 'ir.actions.report.xml',
3117 'report_name': 'stock.quant.package.barcode',
3121 def unpack(self, cr, uid, ids, context=None):
3122 quant_obj = self.pool.get('stock.quant')
3123 for package in self.browse(cr, uid, ids, context=context):
3124 quant_ids = [quant.id for quant in package.quant_ids]
3125 quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3126 children_package_ids = [child_package.id for child_package in package.children_ids]
3127 self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3128 #delete current package since it contains nothing anymore
3129 self.unlink(cr, uid, ids, context=context)
3130 return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3132 def get_content(self, cr, uid, ids, context=None):
3133 child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3134 return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3136 def get_content_package(self, cr, uid, ids, context=None):
3137 quants_ids = self.get_content(cr, uid, ids, context=context)
3138 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3139 res['domain'] = [('id', 'in', quants_ids)]
3142 def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3143 ''' find the total of given product 'product_id' inside the given package 'package_id'''
3144 quant_obj = self.pool.get('stock.quant')
3145 all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3147 for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3148 if quant.product_id.id == product_id:
3152 def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3153 '''This function computes the different product quantities for the given package
3155 quant_obj = self.pool.get('stock.quant')
3157 for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3158 if quant.product_id.id not in res:
3159 res[quant.product_id.id] = 0
3160 res[quant.product_id.id] += quant.qty
3163 class stock_pack_operation(osv.osv):
3164 _name = "stock.pack.operation"
3165 _description = "Packing Operation"
3167 def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3168 '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3169 #if the operation doesn't concern a package, it's not relevant to call this function
3170 if not operation.package_id or operation.product_id:
3171 return {operation.product_id.id: operation.remaining_qty}
3172 #get the total of products the package contains
3173 res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3174 #reduce by the quantities linked to a move
3175 for record in operation.linked_move_operation_ids:
3176 if record.move_id.product_id.id not in res:
3177 res[record.move_id.product_id.id] = 0
3178 res[record.move_id.product_id.id] -= record.qty
3181 def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3182 uom_obj = self.pool.get('product.uom')
3184 for ops in self.browse(cr, uid, ids, context=context):
3187 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3188 #should use _get_remaining_prod_quantities instead
3190 elif ops.product_id:
3191 qty = ops.product_qty
3192 if ops.product_uom_id:
3193 qty = uom_obj._compute_qty(cr, uid, ops.product_uom_id.id, ops.product_qty, ops.product_id.uom_id.id)
3194 for record in ops.linked_move_operation_ids:
3196 #converting the remaining quantity in the pack operation UoM
3197 if ops.product_uom_id:
3198 qty = uom_obj._compute_qty(cr, uid, ops.product_id.uom_id.id, qty, ops.product_uom_id.id)
3202 def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3203 res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3204 if product_id and not product_uom_id:
3205 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3206 res['value']['product_uom_id'] = product.uom_id.id
3209 def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3211 uom_obj = self.pool.get('product.uom')
3213 product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3214 product_uom_id = product_uom_id or product.uom_id.id
3215 selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3216 if selected_uom.category_id.id != product.uom_id.category_id.id:
3218 'title': _('Warning: wrong UoM!'),
3219 '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)
3221 if product_qty and 'warning' not in res:
3222 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3223 if rounded_qty != product_qty:
3225 'title': _('Warning: wrong quantity!'),
3226 'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3231 'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3232 'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"), # 1
3233 'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3234 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3235 'package_id': fields.many2one('stock.quant.package', 'Package'), # 2
3236 'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3237 'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3238 'date': fields.datetime('Date', required=True),
3239 'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3240 #'update_cost': fields.boolean('Need cost update'),
3241 'cost': fields.float("Cost", help="Unit Cost for this product line"),
3242 'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3243 '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'),
3244 'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3248 'date': fields.date.context_today,
3251 def process_packaging(self, cr, uid, operation, quants, context=None):
3252 ''' Process the packaging of a given operation, after the quants have been moved. If there was not enough quants found
3253 a quant already has been with the good package information so we don't consider that case in this method'''
3254 quant_obj = self.pool.get("stock.quant")
3255 pack_obj = self.pool.get("stock.quant.package")
3256 for quant, qty in quants:
3258 if operation.product_id:
3259 #if a product + a package information is given, we consider that we took a part of an existing package (unpacking)
3260 quant_obj.write(cr, SUPERUSER_ID, quant.id, {'package_id': operation.result_package_id.id}, context=context)
3261 elif operation.package_id and operation.result_package_id:
3262 #move the whole pack into the final package if any
3263 pack_obj.write(cr, uid, [operation.package_id.id], {'parent_id': operation.result_package_id.id}, context=context)
3268 #TODO: this function can be refactored
3269 def _search_and_increment(self, cr, uid, picking_id, domain, context=None):
3270 '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3272 :param domain: list of tuple directly reusable as a domain
3273 context can receive a key 'current_package_id' with the package to consider for this operation
3276 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
3277 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3278 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3279 (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)
3284 #if current_package_id is given in the context, we increase the number of items in this package
3285 package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3286 existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3287 if existing_operation_ids:
3288 #existing operation found for the given domain and picking => increment its quantity
3289 operation_id = existing_operation_ids[0]
3290 qty = self.browse(cr, uid, operation_id, context=context).product_qty + 1
3291 self.write(cr, uid, operation_id, {'product_qty': qty}, context=context)
3293 #no existing operation found for the given domain and picking => create a new one
3295 'picking_id': picking_id,
3299 var_name, dummy, value = key
3301 if var_name == 'product_id':
3302 uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3303 update_dict = {var_name: value}
3305 update_dict['product_uom_id'] = uom_id
3306 values.update(update_dict)
3307 operation_id = self.create(cr, uid, values, context=context)
3311 class stock_move_operation_link(osv.osv):
3313 Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3315 _name = "stock.move.operation.link"
3316 _description = "Link between stock moves and pack operations"
3319 '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."),
3320 'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3321 'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3322 'reserved_quant_ids': fields.one2many('stock.quant', 'link_move_operation_id', 'Reserved quants'),
3325 def get_specific_domain(self, cr, uid, record, context=None):
3326 '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3327 having the record given as parameter making the link between the stock move and a pack operation'''
3328 package_obj = self.pool.get('stock.quant.package')
3330 op = record.operation_id
3333 domain.append(('id', 'in', package_obj.get_content(cr, uid, [op.package_id.id], context=context)))
3335 domain.append(('lot_id', '=', op.lot_id.id))
3337 domain.append(('owner_id', '=', op.owner_id.id))
3339 domain.append(('owner_id', '=', False))
3342 class stock_warehouse_orderpoint(osv.osv):
3344 Defines Minimum stock rules.
3346 _name = "stock.warehouse.orderpoint"
3347 _description = "Minimum Inventory Rule"
3349 def get_draft_procurements(self, cr, uid, ids, context=None):
3352 if not isinstance(ids, list):
3354 procurement_obj = self.pool.get('procurement.order')
3355 for orderpoint in self.browse(cr, uid, ids, context=context):
3356 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)
3357 return list(set(procurement_ids))
3359 def _check_product_uom(self, cr, uid, ids, context=None):
3361 Check if the UoM has the same category as the product standard UoM
3366 for rule in self.browse(cr, uid, ids, context=context):
3367 if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3372 def action_view_proc_to_process(self, cr, uid, ids, context=None):
3373 act_obj = self.pool.get('ir.actions.act_window')
3374 mod_obj = self.pool.get('ir.model.data')
3375 draft_ids = self.get_draft_procurements(cr, uid, ids, context=context)
3376 result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3380 result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3381 result['domain'] = "[('id', 'in', [" + ','.join(map(str, draft_ids)) + "])]"
3385 'name': fields.char('Name', size=32, required=True),
3386 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3387 'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3388 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3389 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3390 'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '!=', 'service')]),
3391 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
3392 'product_min_qty': fields.float('Minimum Quantity', required=True,
3393 help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
3394 "a procurement to bring the forecasted quantity to the Max Quantity."),
3395 'product_max_qty': fields.float('Maximum Quantity', required=True,
3396 help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
3397 "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
3398 'qty_multiple': fields.integer('Qty Multiple', required=True,
3399 help="The procurement quantity will be rounded up to this multiple."),
3400 'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
3401 'company_id': fields.many2one('res.company', 'Company', required=True)
3404 'active': lambda *a: 1,
3405 'logic': lambda *a: 'max',
3406 'qty_multiple': lambda *a: 1,
3407 'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3408 'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
3409 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
3411 _sql_constraints = [
3412 ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
3415 (_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']),
3418 def default_get(self, cr, uid, fields, context=None):
3419 res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
3420 # default 'warehouse_id' and 'location_id'
3421 if 'warehouse_id' not in res:
3422 warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
3423 res['warehouse_id'] = warehouse.id
3424 if 'location_id' not in res:
3425 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
3426 res['location_id'] = warehouse.lot_stock_id.id
3429 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
3430 """ Finds location id for changed warehouse.
3431 @param warehouse_id: Changed id of warehouse.
3432 @return: Dictionary of values.
3435 w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
3436 v = {'location_id': w.lot_stock_id.id}
3440 def onchange_product_id(self, cr, uid, ids, product_id, context=None):
3441 """ Finds UoM for changed product.
3442 @param product_id: Changed id of product.
3443 @return: Dictionary of values.
3446 prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3447 d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
3448 v = {'product_uom': prod.uom_id.id}
3449 return {'value': v, 'domain': d}
3450 return {'domain': {'product_uom': []}}
3452 def copy(self, cr, uid, id, default=None, context=None):
3456 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3458 return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
3461 class stock_picking_type(osv.osv):
3462 _name = "stock.picking.type"
3463 _description = "The picking type determines the picking view"
3466 def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
3467 """ Generic method to generate data for bar chart values using SparklineBarWidget.
3468 This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
3470 :param obj: the target model (i.e. crm_lead)
3471 :param domain: the domain applied to the read_group
3472 :param list read_fields: the list of fields to read in the read_group
3473 :param str value_field: the field used to compute the value of the bar slice
3474 :param str groupby_field: the fields used to group
3476 :return list section_result: a list of dicts: [
3477 { 'value': (int) bar_column_value,
3478 'tootip': (str) bar_column_tooltip,
3482 month_begin = date.today().replace(day=1)
3485 'tooltip': (month_begin + relativedelta.relativedelta(months=i)).strftime('%B'),
3486 } for i in range(-2, 2, 1)]
3487 group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
3488 for group in group_obj:
3489 group_begin_date = datetime.strptime(group['__domain'][0][2], DEFAULT_SERVER_DATE_FORMAT)
3490 month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
3491 section_result[-month_delta.months + 2] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
3492 inner_groupby = (group.get('__context', {})).get('group_by',[])
3494 groupby_picking = obj.read_group(cr, uid, group.get('__domain'), read_fields, inner_groupby, context=context)
3495 for groupby in groupby_picking:
3496 section_result[-month_delta.months + 2]['value'] = groupby.get(value_field, 0)
3497 return section_result
3499 def _get_picking_data(self, cr, uid, ids, field_name, arg, context=None):
3500 obj = self.pool.get('stock.picking')
3501 res = dict.fromkeys(ids, False)
3502 month_begin = date.today().replace(day=1)
3503 groupby_begin = (month_begin + relativedelta.relativedelta(months=-2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3504 groupby_end = (month_begin + relativedelta.relativedelta(months=2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3507 ('picking_type_id', '=', id),
3508 ('state', '=', 'assigned'),
3509 ('date', '>=', groupby_begin),
3510 ('date', '<', groupby_end),
3512 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)
3515 def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
3516 obj = self.pool.get('stock.picking')
3518 'count_picking_draft': [('state', '=', 'draft')],
3519 'count_picking_waiting': [('state','in', ('confirmed', 'waiting'))],
3520 'count_picking_ready': [('state','=','assigned')],
3521 'count_picking': [('state','in',('assigned','waiting','confirmed'))],
3522 'count_picking_late': [('min_date','<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state','in',('assigned','waiting','confirmed'))],
3523 'count_picking_backorders': [('backorder_id','!=', False), ('state','in',('confirmed', 'assigned', 'waiting'))],
3526 for field in domains:
3527 data = obj.read_group(cr, uid, domains[field] +
3528 [('state', 'not in',('done','cancel')), ('picking_type_id', 'in', ids)],
3529 ['picking_type_id'], ['picking_type_id'], context=context)
3530 count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
3532 result.setdefault(tid, {})[field] = count.get(tid, 0)
3534 if result[tid]['count_picking']:
3535 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] *100 / result[tid]['count_picking']
3536 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] *100 / result[tid]['count_picking']
3538 result[tid]['rate_picking_late'] = 0
3539 result[tid]['rate_picking_backorders'] = 0
3542 #TODO: not returning valus in required format to show in sparkline library,just added latest_picking_waiting need to add proper logic.
3543 def _get_picking_history(self, cr, uid, ids, field_names, arg, context=None):
3544 obj = self.pool.get('stock.picking')
3548 'latest_picking_late': [],
3549 'latest_picking_backorders': [],
3550 'latest_picking_waiting': []
3553 pick_ids = obj.search(cr, uid, [('state', '=','done'), ('picking_type_id','=',type_id)], limit=12, order="date desc", context=context)
3554 for pick in obj.browse(cr, uid, pick_ids, context=context):
3555 result[type_id]['latest_picking_late'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3556 result[type_id]['latest_picking_backorders'] = bool(pick.backorder_id)
3557 result[type_id]['latest_picking_waiting'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3560 def onchange_picking_code(self, cr, uid, ids, picking_code=False):
3561 if not picking_code:
3564 obj_data = self.pool.get('ir.model.data')
3565 stock_loc = obj_data.get_object_reference(cr, uid, 'stock','stock_location_stock')[1]
3568 'default_location_src_id': stock_loc,
3569 'default_location_dest_id': stock_loc,
3571 if picking_code == 'incoming':
3572 result['default_location_src_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_suppliers')[1]
3573 return {'value': result}
3574 if picking_code == 'outgoing':
3575 result['default_location_dest_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_customers')[1]
3576 return {'value': result}
3578 return {'value': result}
3580 def _get_name(self, cr, uid, ids, field_names, arg, context=None):
3581 return dict(self.name_get(cr, uid, ids, context=context))
3583 def name_get(self, cr, uid, ids, context=None):
3584 """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
3587 if not isinstance(ids, list):
3592 for record in self.browse(cr, uid, ids, context=context):
3594 if record.warehouse_id:
3595 name = record.warehouse_id.name + ': ' +name
3596 if context.get('special_shortened_wh_name'):
3597 if record.warehouse_id:
3598 name = record.warehouse_id.name
3600 name = _('Customer') + ' (' + record.name + ')'
3601 res.append((record.id, name))
3604 def _default_warehouse(self, cr, uid, context=None):
3605 user = self.pool.get('res.users').browse(cr, uid, uid, context)
3606 res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
3607 return res and res[0] or False
3610 'name': fields.char('Name', translate=True, required=True),
3611 'complete_name': fields.function(_get_name, type='char', string='Name'),
3612 'auto_force_assign': fields.boolean('Automatic Availability', help='This picking type does\'t need to check for the availability in source location.'),
3613 'color': fields.integer('Color'),
3614 'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
3615 'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
3616 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
3617 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
3618 'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
3619 'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
3620 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
3621 'active': fields.boolean('Active'),
3623 # Statistics for the kanban view
3624 'weekly_picking': fields.function(_get_picking_data,
3626 string='Scheduled pickings per week'),
3628 'count_picking_draft': fields.function(_get_picking_count,
3629 type='integer', multi='_get_picking_count'),
3630 'count_picking_ready': fields.function(_get_picking_count,
3631 type='integer', multi='_get_picking_count'),
3632 'count_picking': fields.function(_get_picking_count,
3633 type='integer', multi='_get_picking_count'),
3634 'count_picking_waiting': fields.function(_get_picking_count,
3635 type='integer', multi='_get_picking_count'),
3636 'count_picking_late': fields.function(_get_picking_count,
3637 type='integer', multi='_get_picking_count'),
3638 'count_picking_backorders': fields.function(_get_picking_count,
3639 type='integer', multi='_get_picking_count'),
3641 'rate_picking_late': fields.function(_get_picking_count,
3642 type='integer', multi='_get_picking_count'),
3643 'rate_picking_backorders': fields.function(_get_picking_count,
3644 type='integer', multi='_get_picking_count'),
3646 'latest_picking_late': fields.function(_get_picking_history,
3647 type='string', multi='_get_picking_history'),
3648 'latest_picking_backorders': fields.function(_get_picking_history,
3649 type='string', multi='_get_picking_history'),
3650 'latest_picking_waiting': fields.function(_get_picking_history,
3651 type='string', multi='_get_picking_history'),
3655 'warehouse_id': _default_warehouse,
3660 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: