[IMP] Make sure returned action window dictionary is correct
[odoo/odoo.git] / addons / stock / stock.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 from datetime import date, datetime
23 from dateutil import relativedelta
24
25 import time
26
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
33 import logging
34 _logger = logging.getLogger(__name__)
35
36
37 #----------------------------------------------------------
38 # Incoterms
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41     _name = "stock.incoterms"
42     _description = "Incoterms"
43     _columns = {
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."),
47     }
48     _defaults = {
49         'active': True,
50     }
51
52 #----------------------------------------------------------
53 # Stock Location
54 #----------------------------------------------------------
55
56 class stock_location(osv.osv):
57     _name = "stock.location"
58     _description = "Inventory Locations"
59     _parent_name = "location_id"
60     _parent_store = True
61     _parent_order = 'name'
62     _order = 'parent_left'
63     _rec_name = 'complete_name'
64
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
68         """
69         res = {}
70         for m in self.browse(cr, uid, ids, context=context):
71             res[m.id] = m.name
72             parent = m.location_id
73             while parent:
74                 res[m.id] = parent.name + ' / ' + res[m.id]
75                 parent = parent.location_id
76         return res
77
78     def _get_sublocations(self, cr, uid, ids, context=None):
79         """ return all sublocations of the given stock locations (included) """
80         if context is None:
81             context = {}
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)
85
86     _columns = {
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
97                       """, select=True),
98
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'),
103
104         'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
105
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"),
110
111         'parent_left': fields.integer('Left Parent', select=1),
112         'parent_right': fields.integer('Right Parent', select=1),
113
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'),
118     }
119     _defaults = {
120         'active': True,
121         'usage': 'internal',
122         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
123         'posx': 0,
124         'posy': 0,
125         'posz': 0,
126         'scrap_location': False,
127     }
128
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)
136
137         result = pa.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
138         if result:
139             return pa.browse(cr, uid, result[0], context=context)
140
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)
148
149         result = pr.search(cr, uid, [('location_id', '=', location.id), ('product_categ_id', 'in', categs)], context=context)
150         if result:
151             return pr.browse(cr, uid, result[0], context=context).method
152
153
154 #----------------------------------------------------------
155 # Routes
156 #----------------------------------------------------------
157
158 class stock_location_route(osv.osv):
159     _name = 'stock.location.route'
160     _description = "Inventory Routes"
161     _order = 'sequence'
162
163     _columns = {
164         'name': fields.char('Route Name', required=True),
165         'sequence': fields.integer('Sequence'),
166         'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules'),
167         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
168         'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules'),
169         'product_selectable': fields.boolean('Applicable on Product'),
170         'product_categ_selectable': fields.boolean('Applicable on Product Category'),
171         'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
172         'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
173         'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
174     }
175
176     _defaults = {
177         'sequence': lambda self, cr, uid, ctx: 0,
178         'active': True,
179         'product_selectable': True,
180     }
181
182
183 #----------------------------------------------------------
184 # Quants
185 #----------------------------------------------------------
186
187 class stock_quant(osv.osv):
188     """
189     Quants are the smallest unit of stock physical instances
190     """
191     _name = "stock.quant"
192     _description = "Quants"
193
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
197         """
198         res = {}
199         for q in self.browse(cr, uid, ids, context=context):
200
201             res[q.id] = q.product_id.code or ''
202             if q.lot_id:
203                 res[q.id] = q.lot_id.name
204             res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
205         return res
206
207     def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
208         res = {}
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)
218         return res
219
220     def _get_inventory_value(self, cr, uid, quant, context=None):
221         return quant.product_id.standard_price * quant.qty
222
223     _columns = {
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"),
235
236         'create_date': fields.datetime('Creation Date'),
237         'in_date': fields.datetime('Incoming Date'),
238
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),
241
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),
246     }
247
248     _defaults = {
249         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
250     }
251
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:
256             for line in res:
257                 if '__domain' in line:
258                     lines = self.search(cr, uid, line['__domain'], context=context)
259                     inv_value = 0.0
260                     for line2 in self.browse(cr, uid, lines, context=context):
261                         inv_value += line2.inventory_value
262                     line['inventory_value'] = inv_value
263         return res
264
265     def action_view_quant_history(self, cr, uid, ids, context=None):
266         '''
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.
269         '''
270         mod_obj = self.pool.get('ir.model.data')
271         act_obj = self.pool.get('ir.actions.act_window')
272
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]
276
277         move_ids = []
278         for quant in self.browse(cr, uid, ids, context=context):
279             move_ids += [move.id for move in quant.history_ids]
280
281         result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
282         return result
283
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'
287
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)
291         '''
292         toreserve = []
293         #split quants if needed
294         for quant, qty in quants:
295             if not quant:
296                 continue
297             self._quant_split(cr, uid, quant, qty, context=context)
298             toreserve.append(quant.id)
299         #reserve quants
300         if toreserve:
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'
303         move.refresh()
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)
306
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.
309
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
316         """
317         for quant, qty in quants:
318             if not quant:
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)
322
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
326
327         :param move: browse record (stock.move)
328         :param qty: float
329         :returns: list of tuple build as [(browe record (stock.move), float)]
330         '''
331         if move.putaway_ids:
332             res = []
333             for record in move.putaway_ids:
334                 res.append((record.location_id, record.quantity))
335             return res
336         return [(move.location_dest_id, qty)]
337
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.
341
342         :param quant: browse record (stock.quant)
343         :param location_to: browse record (stock.location)
344         :param qty: float
345         :param move: browse record (stock.move)
346         '''
347         new_quant = self._quant_split(cr, uid, quant, qty, context=context)
348         vals = {
349             'location_id': location_to.id,
350             'history_ids': [(4, move.id)],
351         }
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)
356         quant.refresh()
357         return new_quant
358
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)
363         :param qty: float
364         :param move: browse record (stock.move)
365         '''
366         for location_to, qty in self.check_preferred_location(cr, uid, move, qty, context=context):
367             if not quant:
368                 break
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)
371             quant = new_quant
372
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.
377         '''
378         if prefered_domain and fallback_domain:
379             if domain is None:
380                 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)
382             res_qty = qty
383             quant_ids = []
384             for quant in quants:
385                 if quant[0]:
386                     quant_ids.append(quant[0].id)
387                     res_qty -= quant[1]
388             if res_qty > 0:
389                 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
390                 quants.pop()
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:
395                     quants.append(quant)
396             return 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)
398
399     def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
400         """
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.
403
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
407         """
408         result = []
409         domain = domain or [('qty', '>', 0.0)]
410         if restrict_partner_id:
411             domain += [('owner_id', '=', restrict_partner_id)]
412         if restrict_lot_id:
413             domain += [('lot_id', '=', restrict_lot_id)]
414         if location:
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)
420             else:
421                 raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
422         return result
423
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.
426         '''
427         if context is None:
428             context = {}
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
431         vals = {
432             'product_id': move.product_id.id,
433             'location_id': location.id,
434             'qty': qty,
435             'cost': price_unit,
436             'history_ids': [(4, move.id)],
437             'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
438             'company_id': move.company_id.id,
439             'lot_id': lot_id,
440             'owner_id': owner_id,
441             'package_id': dest_package_id,
442         }
443
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})
455
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)
459
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):
463             return False
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)
466         quant.refresh()
467         return self.browse(cr, uid, new_quant, context=context)
468
469     def _get_latest_move(self, cr, uid, quant, context=None):
470         move = False
471         for m in quant.history_ids:
472             if not move or m.date > move.date:
473                 move = m
474         return move
475
476     def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
477         path = []
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)
481
482     def _quant_reconcile_negative(self, cr, uid, quant, context=None):
483         """
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.
487         """
488         if quant.location_id.usage != 'internal':
489             return False
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:
497             if not quant_neg:
498                 continue
499             to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
500             if not to_solve_quant_ids:
501                 continue
502             solving_qty = qty
503             solved_quant_ids = []
504             for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
505                 if solving_qty <= 0:
506                     continue
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
525
526     def _price_update(self, cr, uid, ids, newprice, context=None):
527         self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
528
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)
532
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)
536         '''
537         domain += location and [('location_id', 'child_of', location.id)] or []
538         domain += [('product_id', '=', product.id)] + domain
539         res = []
540         offset = 0
541         while quantity > 0:
542             quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
543             if not quants:
544                 res.append((None, quantity))
545                 break
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)
550                 elif quantity != 0:
551                     res += [(quant, quantity)]
552                     quantity = 0
553                     break
554             offset += 10
555         return res
556
557     def _quants_get_fifo(self, cr, uid, location, product, quantity, domain=[], context=None):
558         order = 'in_date'
559         return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
560
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)
564
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
568
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))
573         return True
574
575     _constraints = [
576         (_check_location, 'You cannot move products to a location of the type view.', ['location_id'])
577     ]
578
579
580 #----------------------------------------------------------
581 # Stock Picking
582 #----------------------------------------------------------
583
584 class stock_picking(osv.osv):
585     _name = "stock.picking"
586     _inherit = ['mail.thread']
587     _description = "Picking List"
588     _order = "priority desc, date desc, id desc"
589
590     def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
591         move_obj = self.pool.get("stock.move")
592         if value:
593             move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
594             move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
595
596     def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
597         """ Finds minimum and maximum dates for picking.
598         @return: Dictionary of values
599         """
600         res = {}
601         for id in ids:
602             res[id] = {'min_date': False, 'max_date': False}
603         if not ids:
604             return res
605         cr.execute("""select
606                 picking_id,
607                 min(date_expected),
608                 max(date_expected)
609             from
610                 stock_move
611             where
612                 picking_id IN %s
613             group by
614                 picking_id""", (tuple(ids),))
615         for pick, dt1, dt2 in cr.fetchall():
616             res[pick]['min_date'] = dt1
617             res[pick]['max_date'] = dt2
618         return res
619
620     def create(self, cr, user, vals, context=None):
621         context = context or {}
622         if ('name' not in vals) or (vals.get('name') in ('/', False)):
623             ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
624             sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
625             vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
626         return super(stock_picking, self).create(cr, user, vals, context)
627
628     def _state_get(self, cr, uid, ids, field_name, arg, context=None):
629         '''The state of a picking depends on the state of its related stock.move
630             draft: the picking has no line or any one of the lines is draft
631             done, draft, cancel: all lines are done / draft / cancel
632             confirmed, auto, assigned depends on move_type (all at once or direct)
633         '''
634         res = {}
635         for pick in self.browse(cr, uid, ids, context=context):
636             if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
637                 res[pick.id] = 'draft'
638                 continue
639             if all([x.state == 'cancel' for x in pick.move_lines]):
640                 res[pick.id] = 'cancel'
641                 continue
642             if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
643                 res[pick.id] = 'done'
644                 continue
645
646             order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
647             order_inv = dict(zip(order.values(), order.keys()))
648             lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
649             if pick.move_lines == 'one':
650                 res[pick.id] = order_inv[min(lst)]
651             else:
652                 res[pick.id] = order_inv[max(lst)]
653         return res
654
655     def _get_pickings(self, cr, uid, ids, context=None):
656         res = set()
657         for move in self.browse(cr, uid, ids, context=context):
658             if move.picking_id:
659                 res.add(move.picking_id.id)
660         return list(res)
661
662     def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
663         res = {}
664         for pick in self.browse(cr, uid, ids, context=context):
665             res[pick.id] = False
666             if pick.pack_operation_ids:
667                 res[pick.id] = True
668         return res
669
670     def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
671         res = {}
672         for pick in self.browse(cr, uid, ids, context=context):
673             res[pick.id] = False
674             for move in pick.move_lines:
675                 if move.reserved_quant_ids:
676                     res[pick.id] = True
677                     continue
678         return res
679
680     def action_assign_owner(self, cr, uid, ids, context=None):
681         for picking in self.browse(cr, uid, ids, context=context):
682             packop_ids = [op.id for op in picking.pack_operation_ids]
683             self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
684
685     _columns = {
686         'name': fields.char('Reference', size=64, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
687         'origin': fields.char('Source Document', size=64, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
688         '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),
689         'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
690         '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"),
691         'state': fields.function(_state_get, type="selection", store={
692             'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type', 'move_lines'], 20),
693             'stock.move': (_get_pickings, ['state', 'picking_id'], 20)}, selection=[
694                 ('draft', 'Draft'),
695                 ('cancel', 'Cancelled'),
696                 ('waiting', 'Waiting Another Operation'),
697                 ('confirmed', 'Waiting Availability'),
698                 ('assigned', 'Ready to Transfer'),
699                 ('done', 'Transferred'),
700                 ], string='Status', readonly=True, select=True, track_visibility='onchange', help="""
701                 * Draft: not confirmed yet and will not be scheduled until confirmed\n
702                 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
703                 * Waiting Availability: still waiting for the availability of products\n
704                 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
705                 * Transferred: has been processed, can't be modified or cancelled anymore\n
706                 * Cancelled: has been cancelled, can't be confirmed anymore"""
707         ),
708         'priority': fields.selection([('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Priority', required=True),
709         'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
710                  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'),
711         'max_date': fields.function(get_min_max_date, multi="min_max_date",
712                  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"),
713         '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'),
714         'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
715         'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
716         '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'),
717         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
718         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
719         'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', string='Related Packing Operations'),
720         'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
721         'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True),
722         '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"),
723
724         'owner_id': fields.many2one('res.partner', 'Owner', help="Default Owner"),
725         # Used to search on pickings
726         'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
727         'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
728         'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
729         'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
730               store={
731                   'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
732                   'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
733               }),
734     }
735
736     _defaults = {
737         'name': lambda self, cr, uid, context: '/',
738         'state': 'draft',
739         'move_type': 'one',
740         'priority': '1',  # normal
741         'date': fields.datetime.now,
742         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
743     }
744     _sql_constraints = [
745         ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
746     ]
747
748     def copy(self, cr, uid, id, default=None, context=None):
749         if default is None:
750             default = {}
751         default = default.copy()
752         picking_obj = self.browse(cr, uid, id, context=context)
753         if ('name' not in default) or (picking_obj.name == '/'):
754             default['name'] = '/'
755         if not default.get('backorder_id'):
756             default['backorder_id'] = False
757         default['pack_operation_ids'] = []
758         default['date_done'] = False
759         return super(stock_picking, self).copy(cr, uid, id, default, context)
760
761     def do_print_delivery(self, cr, uid, ids, context=None):
762         '''This function prints the delivery order'''
763         assert len(ids) == 1, 'This option should only be used for a single id at a time'
764         datas = {
765                  'model': 'stock.picking',
766                  'ids': ids,
767         }
768         return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list', 'datas': datas, 'nodestroy': True}
769
770     def do_print_picking(self, cr, uid, ids, context=None):
771         '''This function prints the picking list'''
772         assert len(ids) == 1, 'This option should only be used for a single id at a time'
773         datas = {
774                  'model': 'stock.picking',
775                  'ids': ids,
776         }
777         return {'type': 'ir.actions.report.xml', 'report_name': 'stock.picking.list.internal', 'datas': datas, 'nodestroy': True}
778
779     def action_confirm(self, cr, uid, ids, context=None):
780         todo = []
781         todo_force_assign = []
782         for picking in self.browse(cr, uid, ids, context=context):
783             if picking.picking_type_id.auto_force_assign:
784                 todo_force_assign.append(picking.id)
785             for r in picking.move_lines:
786                 if r.state == 'draft':
787                     todo.append(r.id)
788         if len(todo):
789             self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
790
791         if todo_force_assign:
792             self.force_assign(cr, uid, todo_force_assign, context=context)
793         return True
794
795     def action_assign(self, cr, uid, ids, context=None):
796         """ Check availability of picking moves.
797         This has the effect of changing the state and reserve quants on available moves, and may
798         also impact the state of the picking as it is computed based on move's states.
799         @return: True
800         """
801         for pick in self.browse(cr, uid, ids, context=context):
802             if pick.state == 'draft':
803                 self.action_confirm(cr, uid, [pick.id], context=context)
804             #skip the moves that don't need to be checked
805             move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
806             if not move_ids:
807                 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
808             self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
809         return True
810
811     def force_assign(self, cr, uid, ids, context=None):
812         """ Changes state of picking to available if moves are confirmed or waiting.
813         @return: True
814         """
815         for pick in self.browse(cr, uid, ids, context=context):
816             move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
817             self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
818         return True
819
820     def cancel_assign(self, cr, uid, ids, context=None):
821         """ Cancels picking and moves.
822         @return: True
823         """
824         for pick in self.browse(cr, uid, ids, context=context):
825             move_ids = [x.id for x in pick.move_lines]
826             self.pool.get('stock.move').cancel_assign(cr, uid, move_ids, context=context)
827         return True
828
829     def action_cancel(self, cr, uid, ids, context=None):
830         for pick in self.browse(cr, uid, ids, context=context):
831             ids2 = [move.id for move in pick.move_lines]
832             self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
833         return True
834
835     def action_done(self, cr, uid, ids, context=None):
836         """Changes picking state to done by processing the Stock Moves of the Picking
837
838         Normally that happens when the button "Done" is pressed on a Picking view.
839         @return: True
840         """
841         for pick in self.browse(cr, uid, ids, context=context):
842             todo = []
843             for move in pick.move_lines:
844                 if move.state == 'draft':
845                     self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
846                         context=context)
847                     todo.append(move.id)
848                 elif move.state in ('assigned', 'confirmed'):
849                     todo.append(move.id)
850             if len(todo):
851                 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
852         return True
853
854     def unlink(self, cr, uid, ids, context=None):
855         #on picking deletion, cancel its move then unlink them too
856         move_obj = self.pool.get('stock.move')
857         context = context or {}
858         for pick in self.browse(cr, uid, ids, context=context):
859             move_ids = [move.id for move in pick.move_lines]
860             move_obj.action_cancel(cr, uid, move_ids, context=context)
861             move_obj.unlink(cr, uid, move_ids, context=context)
862         return super(stock_picking, self).unlink(cr, uid, ids, context=context)
863
864     def write(self, cr, uid, ids, vals, context=None):
865         res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
866         #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
867         if 'move_lines' in vals or 'pack_operation_ids' in vals:
868             self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
869         return res
870
871     def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
872         """ 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.
873         """
874         if not backorder_moves:
875             backorder_moves = picking.move_lines
876         backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
877         if 'do_only_split' in context and context['do_only_split']:
878             backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
879
880         if backorder_move_ids:
881             backorder_id = self.copy(cr, uid, picking.id, {
882                 'name': '/',
883                 'move_lines': [],
884                 'pack_operation_ids': [],
885                 'backorder_id': picking.id,
886             })
887             back_order_name = self.browse(cr, uid, backorder_id, context=context).name
888             self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (back_order_name), context=context)
889             move_obj = self.pool.get("stock.move")
890             move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
891
892             self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
893             self.action_confirm(cr, uid, [backorder_id], context=context)
894             return backorder_id
895         return False
896
897     def do_prepare_partial(self, cr, uid, picking_ids, context=None):
898         #TODO refactore me
899         context = context or {}
900         pack_operation_obj = self.pool.get('stock.pack.operation')
901         pack_obj = self.pool.get("stock.quant.package")
902         quant_obj = self.pool.get("stock.quant")
903         for picking in self.browse(cr, uid, picking_ids, context=context):
904             for move in picking.move_lines:
905                 if move.state != 'assigned':
906                     continue
907                 #Check which of the reserved quants are entirely in packages (can be in separate method)
908                 packages = list(set([x.package_id for x in move.reserved_quant_ids if x.package_id]))
909                 done_packages = []
910                 for pack in packages:
911                     cont = True
912                     good_pack = False
913                     test_pack = pack
914                     while cont:
915                         quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
916                         if all([x.reservation_id.id == move.id for x in quant_obj.browse(cr, uid, quants, context=context) if x.reservation_id]):
917                             good_pack = test_pack.id
918                             if test_pack.parent_id:
919                                 test_pack = test_pack.parent_id
920                             else:
921                                 cont = False
922                         else:
923                             cont = False
924                     if good_pack:
925                         done_packages.append(good_pack)
926                 done_packages = list(set(done_packages))
927
928                 #Create package operations
929                 reserved = set([x.id for x in move.reserved_quant_ids])
930                 remaining_qty = move.product_qty
931                 for pack in pack_obj.browse(cr, uid, done_packages, context=context):
932                     quantl = pack_obj.get_content(cr, uid, [pack.id], context=context)
933                     for quant in quant_obj.browse(cr, uid, quantl, context=context):
934                         remaining_qty -= quant.qty
935                     quants = set(pack_obj.get_content(cr, uid, [pack.id], context=context))
936                     reserved -= quants
937                     pack_operation_obj.create(cr, uid, {
938                         'picking_id': picking.id,
939                         'package_id': pack.id,
940                         'product_qty': 1.0,
941                     }, context=context)
942
943                 yet_to_reserve = list(reserved)
944                 #Create operations based on quants
945                 for quant in quant_obj.browse(cr, uid, yet_to_reserve, context=context):
946                     qty = min(quant.qty, move.product_qty)
947                     remaining_qty -= qty
948                     pack_operation_obj.create(cr, uid, {
949                         'picking_id': picking.id,
950                         'product_qty': qty,
951                         'product_id': quant.product_id.id,
952                         'lot_id': quant.lot_id and quant.lot_id.id or False,
953                         'product_uom_id': quant.product_id.uom_id.id,
954                         'owner_id': quant.owner_id and quant.owner_id.id or False,
955                         'cost': quant.cost,
956                         'package_id': quant.package_id and quant.package_id.id or False,
957                     }, context=context)
958                 if remaining_qty > 0:
959                     pack_operation_obj.create(cr, uid, {
960                         'picking_id': picking.id,
961                         'product_qty': remaining_qty,
962                         'product_id': move.product_id.id,
963                         'product_uom_id': move.product_id.uom_id.id,
964                         'cost': move.product_id.standard_price,
965                     }, context=context)
966
967     def do_unreserve(self, cr, uid, picking_ids, context=None):
968         """
969           Will remove all quants for picking in picking_ids
970         """
971         moves_to_unreserve = []
972         for picking in self.browse(cr, uid, picking_ids, context=context):
973             moves_to_unreserve += [m.id for m in picking.move_lines]
974         if moves_to_unreserve:
975             self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
976
977     def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
978         def _create_link_for_product(product_id, qty):
979             qty_to_assign = qty
980             for move in picking.move_lines:
981                 if move.product_id.id == product_id and move.state not in ['done', 'cancel']:
982                     qty_on_link = min(move.remaining_qty, qty_to_assign)
983                     link_obj.create(cr, uid, {'move_id': move.id, 'operation_id': op.id, 'qty': qty_on_link}, context=context)
984                     qty_to_assign -= qty_on_link
985                     move.refresh()
986                     if qty_to_assign <= 0:
987                         break
988
989         link_obj = self.pool.get('stock.move.operation.link')
990         uom_obj = self.pool.get('product.uom')
991         package_obj = self.pool.get('stock.quant.package')
992         for picking in self.browse(cr, uid, picking_ids, context=context):
993             for op in picking.pack_operation_ids:
994                 to_unlink_ids = [x.id for x in op.linked_move_operation_ids]
995                 if to_unlink_ids:
996                     link_obj.unlink(cr, uid, to_unlink_ids, context=context)
997                 if op.product_id:
998                     normalized_qty = uom_obj._compute_qty(cr, uid, op.product_uom_id.id, op.product_qty, op.product_id.uom_id.id)
999                     _create_link_for_product(op.product_id.id, normalized_qty)
1000                 elif op.package_id:
1001                     for product_id, qty in package_obj._get_all_products_quantities(cr, uid, op.package_id.id, context=context).items():
1002                         _create_link_for_product(product_id, qty)
1003
1004     def _create_extra_moves(self, cr, uid, picking, context=None):
1005         '''This function creates move lines on a picking, at the time of do_transfer, based on
1006         unexpected product transfers (or exceeding quantities) found in the pack operations.
1007         '''
1008         move_obj = self.pool.get('stock.move')
1009         operation_obj = self.pool.get('stock.pack.operation')
1010         for op in picking.pack_operation_ids:
1011             for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1012                 if remaining_qty > 0:
1013                     product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1014                     vals = {
1015                         'picking_id': picking.id,
1016                         'location_id': picking.location_id.id,
1017                         'location_dest_id': picking.location_dest_id.id,
1018                         'product_id': product_id,
1019                         'product_uom': product.uom_id.id,
1020                         'product_uom_qty': remaining_qty,
1021                         'name': _('Extra Move: ') + product.name,
1022                         'state': 'confirmed',
1023                     }
1024                     move_obj.create(cr, uid, vals, context=context)
1025         self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1026
1027     def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1028         """ Unreserve quants then try to reassign quants."""
1029         stock_move_obj = self.pool.get('stock.move')
1030         if not move_ids:
1031             self.do_unreserve(cr, uid, [picking.id], context=context)
1032             self.action_assign(cr, uid, [picking.id], context=context)
1033         else:
1034             stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1035             stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1036
1037     def do_transfer(self, cr, uid, picking_ids, context=None):
1038         """
1039             If no pack operation, we do simple action_done of the picking
1040             Otherwise, do the pack operations
1041         """
1042         if not context:
1043             context = {}
1044         stock_move_obj = self.pool.get('stock.move')
1045         for picking in self.browse(cr, uid, picking_ids, context=context):
1046             if not picking.pack_operation_ids:
1047                 self.action_done(cr, uid, [picking.id], context=context)
1048                 continue
1049             else:
1050                 self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1051                 #create extra moves in the picking (unexpected product moves coming from pack operations)
1052                 self._create_extra_moves(cr, uid, picking, context=context)
1053                 picking.refresh()
1054                 #split move lines eventually
1055                 todo_move_ids = []
1056                 toassign_move_ids = []
1057                 for move in picking.move_lines:
1058                     if move.state in ('done', 'cancel'):
1059                         #ignore stock moves cancelled or already done
1060                         continue
1061                     elif move.state == 'draft':
1062                         toassign_move_ids.append(move.id)
1063                     if move.remaining_qty == 0:
1064                         if move.state in ('draft', 'assigned', 'confirmed'):
1065                             todo_move_ids.append(move.id)
1066                     elif move.remaining_qty > 0:
1067                         new_move = stock_move_obj.split(cr, uid, move, move.remaining_qty, context=context)
1068                         todo_move_ids.append(move.id)
1069                         #Assign move as it was assigned before
1070                         toassign_move_ids.append(new_move)
1071                     elif move.state:
1072                         #this should never happens
1073                         raise
1074                 self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1075                 if todo_move_ids and not context.get('do_only_split'):
1076                     self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1077                 elif context.get('do_only_split'):
1078                     context.update({'split': todo_move_ids})
1079             picking.refresh()
1080             self._create_backorder(cr, uid, picking, context=context)
1081             if toassign_move_ids:
1082                 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1083         return True
1084
1085     def do_split(self, cr, uid, picking_ids, context=None):
1086         """ just split the picking (create a backorder) without making it 'done' """
1087         if context is None:
1088             context = {}
1089         ctx = context.copy()
1090         ctx['do_only_split'] = True
1091         return self.do_transfer(cr, uid, picking_ids, context=ctx)
1092
1093     def get_next_picking_for_ui(self, cr, uid, context=None):
1094         """ returns the next pickings to process. Used in the barcode scanner UI"""
1095         if context is None:
1096             context = {}
1097         domain = [('state', 'in', ('confirmed', 'assigned'))]
1098         if context.get('default_picking_type_id'):
1099             domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1100         return self.search(cr, uid, domain, context=context)
1101
1102     def action_done_from_ui(self, cr, uid, picking_id, context=None):
1103         """ called when button 'done' in pused in the barcode scanner UI """
1104         self.do_transfer(cr, uid, [picking_id], context=context)
1105         #return id of next picking to work on
1106         return self.get_next_picking_for_ui(cr, uid, context=context)
1107
1108     def action_pack(self, cr, uid, picking_ids, context=None):
1109         """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1110         Used in the barcode scanner UI and the normal interface as well. """
1111         stock_operation_obj = self.pool.get('stock.pack.operation')
1112         package_obj = self.pool.get('stock.quant.package')
1113         for picking_id in picking_ids:
1114             operation_ids = stock_operation_obj.search(cr, uid, [('picking_id', '=', picking_id), ('result_package_id', '=', False)], context=context)
1115             if operation_ids:
1116                 package_id = package_obj.create(cr, uid, {}, context=context)
1117                 stock_operation_obj.write(cr, uid, operation_ids, {'result_package_id': package_id}, context=context)
1118         return True
1119
1120     def process_product_id_from_ui(self, cr, uid, picking_id, product_id, context=None):
1121         return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id)], context=context)
1122
1123     def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, context=None):
1124         '''This function is called each time there barcode scanner reads an input'''
1125         lot_obj = self.pool.get('stock.production.lot')
1126         package_obj = self.pool.get('stock.quant.package')
1127         product_obj = self.pool.get('product.product')
1128         stock_operation_obj = self.pool.get('stock.pack.operation')
1129         #check if the barcode correspond to a product
1130         matching_product_ids = product_obj.search(cr, uid, [('ean13', '=', barcode_str)], context=context)
1131         if matching_product_ids:
1132             self.process_product_id_from_ui(cr, uid, picking_id, matching_product_ids[0], context=context)
1133
1134         #check if the barcode correspond to a lot
1135         matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1136         if matching_lot_ids:
1137             lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1138             stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], context=context)
1139
1140         #check if the barcode correspond to a package
1141         matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1142         if matching_package_ids:
1143             stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], context=context)
1144
1145
1146 class stock_production_lot(osv.osv):
1147     _name = 'stock.production.lot'
1148     _inherit = ['mail.thread']
1149     _description = 'Lot/Serial'
1150     _columns = {
1151         'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number"),
1152         'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1153         'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1154         'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants'),
1155         'create_date': fields.datetime('Creation Date'),
1156     }
1157     _defaults = {
1158         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1159         'product_id': lambda x, y, z, c: c.get('product_id', False),
1160     }
1161     _sql_constraints = [
1162         ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1163     ]
1164
1165     def action_traceability(self, cr, uid, ids, context=None):
1166         """ It traces the information of a product
1167         @param self: The object pointer.
1168         @param cr: A database cursor
1169         @param uid: ID of the user currently logged in
1170         @param ids: List of IDs selected
1171         @param context: A standard dictionary
1172         @return: A dictionary of values
1173         """
1174         if not ids or len(ids) == 0:
1175             return False #TODO give warning instead
1176         quant_obj = self.pool.get("stock.quant")
1177         move_obj = self.pool.get("stock.move")
1178         quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1179         moves = set()
1180         for quant in quant_obj.browse(cr, uid, quants, context=context):
1181             for move in quant.history_ids:
1182                 moves.add(move.id)
1183         if moves:
1184             return { 
1185                 'domain': "[('id','in',["+','.join(map(str, list(moves)))+"])]",
1186                 'name': 'Traceability',
1187                 'view_mode': 'tree,form',
1188                 'view_type': 'form',
1189                 'res_model': 'stock.move',
1190                 'type': 'ir.actions.act_window',
1191                     }
1192         else:
1193             return False
1194         
1195
1196
1197 # ----------------------------------------------------
1198 # Move
1199 # ----------------------------------------------------
1200
1201 class stock_move(osv.osv):
1202     _name = "stock.move"
1203     _description = "Stock Move"
1204     _order = 'date_expected desc, id'
1205     _log_create = False
1206
1207     def get_price_unit(self, cr, uid, move, context=None):
1208         """ Returns the unit price to store on the quant """
1209         return move.price_unit or move.product_id.standard_price
1210
1211     def name_get(self, cr, uid, ids, context=None):
1212         res = []
1213         for line in self.browse(cr, uid, ids, context=context):
1214             name = line.location_id.name + ' > ' + line.location_dest_id.name
1215             if line.product_id.code:
1216                 name = line.product_id.code + ': ' + name
1217             if line.picking_id.origin:
1218                 name = line.picking_id.origin + '/ ' + name
1219             res.append((line.id, name))
1220         return res
1221
1222     def create(self, cr, uid, vals, context=None):
1223         if vals.get('product_id') and not vals.get('price_unit'):
1224             prod_obj = self.pool.get('product.product')
1225             vals['price_unit'] = prod_obj.browse(cr, uid, vals['product_id'], context=context).standard_price
1226         return super(stock_move, self).create(cr, uid, vals, context=context)
1227
1228     def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1229         uom_obj = self.pool.get('product.uom')
1230         res = {}
1231         for m in self.browse(cr, uid, ids, context=context):
1232             res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False)
1233         return res
1234
1235     def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1236         uom_obj = self.pool.get('product.uom')
1237         res = {}
1238         for move in self.browse(cr, uid, ids, context=context):
1239             qty = move.product_qty
1240             for record in move.linked_move_operation_ids:
1241                 qty -= record.qty
1242             #converting the remaining quantity in the move UoM
1243             res[move.id] = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1244         return res
1245
1246     def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1247         res = dict.fromkeys(ids, False)
1248         for move in self.browse(cr, uid, ids, context=context):
1249             if move.state == 'done':
1250                 res[move.id] = [q.id for q in move.quant_ids]
1251             else:
1252                 res[move.id] = [q.id for q in move.reserved_quant_ids]
1253         return res
1254
1255     def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1256         quant_obj = self.pool.get('stock.quant')
1257         res = dict.fromkeys(ids, False)
1258         for move in self.browse(cr, uid, ids, context=context):
1259             if move.state == 'done':
1260                 res[move.id] = move.product_qty
1261             else:
1262                 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1263                 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1264                 availability = 0
1265                 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1266                     availability += quant.qty
1267                 res[move.id] = min(move.product_qty, availability)
1268         return res
1269
1270     def _get_move(self, cr, uid, ids, context=None):
1271         res = set()
1272         for quant in self.browse(cr, uid, ids, context=context):
1273             if quant.reservation_id:
1274                 res.add(quant.reservation_id.id)
1275         return list(res)
1276
1277     def _get_move_ids(self, cr, uid, ids, context=None):
1278         res = []
1279         for picking in self.browse(cr, uid, ids, context=context):
1280             res += [x.id for x in picking.move_lines]
1281         return res
1282
1283     _columns = {
1284         'name': fields.char('Description', required=True, select=True),
1285         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1286         'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1287         '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)]}),
1288         'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1289         'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1290         # TODO: improve store to add dependency on product UoM
1291         'product_qty': fields.function(_quantity_normalize, type='float', store=True, string='Quantity',
1292             digits_compute=dp.get_precision('Product Unit of Measure'),
1293             help='Quantity in the default UoM of the product'),
1294         'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1295             required=True, states={'done': [('readonly', True)]},
1296             help="This is the quantity of products from an inventory "
1297                 "point of view. For moves in the state 'done', this is the "
1298                 "quantity of products that were actually moved. For other "
1299                 "moves, this is the quantity of product that is planned to "
1300                 "be moved. Lowering this quantity does not generate a "
1301                 "backorder. Changing this quantity on assigned moves affects "
1302                 "the product reservation, and should be done with care."
1303         ),
1304         'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1305         'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1306         'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1307
1308         'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1309
1310         '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."),
1311         '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."),
1312
1313         # FP Note: should we remove this?
1314         '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"),
1315
1316
1317         'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1318         'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1319
1320         'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1321         'picking_priority': fields.related('picking_id', 'priority', type='selection', selection=[('0', 'Low'), ('1', 'Normal'), ('2', 'High')], string='Picking Priority', store={'stock.picking': (_get_move_ids, ['priority'], 10)}),
1322         'note': fields.text('Notes'),
1323         'state': fields.selection([('draft', 'New'),
1324                                    ('cancel', 'Cancelled'),
1325                                    ('waiting', 'Waiting Another Move'),
1326                                    ('confirmed', 'Waiting Availability'),
1327                                    ('assigned', 'Available'),
1328                                    ('done', 'Done'),
1329                                    ], 'Status', readonly=True, select=True,
1330                  help= "* New: When the stock move is created and not yet confirmed.\n"\
1331                        "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1332                        "* 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"\
1333                        "* Available: When products are reserved, it is set to \'Available\'.\n"\
1334                        "* Done: When the shipment is processed, the state is \'Done\'."),
1335
1336         '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
1337
1338         'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1339         'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1340         'origin': fields.char("Source"),
1341         '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."),
1342
1343         # used for colors in tree views:
1344         'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1345
1346         'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1347         'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1348         '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'),
1349         'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1350                                          digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1351         'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1352         'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1353         'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1354         'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1355         'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1356         'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1357         'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1358         'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.quant', string='Lots'),
1359         'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move'),
1360         'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1361         'availability': fields.function(_get_product_availability, type='float', string='Availability'),
1362         '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'"),
1363         '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'"),
1364         'putaway_ids': fields.one2many('stock.move.putaway', 'move_id', 'Put Away Suggestions'),
1365         '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"),
1366         '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)."),
1367     }
1368
1369     def _default_location_destination(self, cr, uid, context=None):
1370         context = context or {}
1371         if context.get('default_picking_type_id', False):
1372             pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1373             return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1374         return False
1375
1376     def _default_location_source(self, cr, uid, context=None):
1377         context = context or {}
1378         if context.get('default_picking_type_id', False):
1379             pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1380             return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1381         return False
1382
1383     def _default_destination_address(self, cr, uid, context=None):
1384         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1385         return user.company_id.partner_id.id
1386
1387     _defaults = {
1388         'location_id': _default_location_source,
1389         'location_dest_id': _default_location_destination,
1390         'partner_id': _default_destination_address,
1391         'state': 'draft',
1392         'priority': '1',
1393         'product_qty': 1.0,
1394         'product_uom_qty': 1.0,
1395         'scrapped': False,
1396         'date': fields.datetime.now,
1397         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1398         'date_expected': fields.datetime.now,
1399         'procure_method': 'make_to_stock',
1400         'propagate': True,
1401     }
1402
1403     def _check_uom(self, cr, uid, ids, context=None):
1404         for move in self.browse(cr, uid, ids, context=context):
1405             if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1406                 return False
1407         return True
1408
1409     _constraints = [
1410         (_check_uom,
1411             '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.',
1412             ['product_uom'])]
1413
1414     def copy_data(self, cr, uid, id, default=None, context=None):
1415         if default is None:
1416             default = {}
1417         default = default.copy()
1418         default['move_orig_ids'] = []
1419         default['quant_ids'] = []
1420         default['reserved_quant_ids'] = []
1421         default['returned_move_ids'] = []
1422         default['linked_move_operation_ids'] = []
1423         default['origin_returned_move_id'] = False
1424         default['state'] = 'draft'
1425         return super(stock_move, self).copy_data(cr, uid, id, default, context)
1426
1427     def do_unreserve(self, cr, uid, move_ids, context=None):
1428         quant_obj = self.pool.get("stock.quant")
1429         for move in self.browse(cr, uid, move_ids, context=context):
1430             quant_obj.quants_unreserve(cr, uid, move, context=context)
1431             putaway_values = []
1432             for putaway_rec in move.putaway_ids:
1433                 putaway_values.append((2, putaway_rec.id))
1434             self.write(cr, uid, [move.id], {'state': 'confirmed', 'putaway_ids': putaway_values}, context=context)
1435
1436     def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1437         origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or "/")
1438         group_id = move.group_id and move.group_id.id or False
1439         if move.rule_id:
1440             if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1441                 group_id = move.rule_id.group_id.id
1442             elif move.rule_id.group_propagation_option == 'none':
1443                 group_id = False
1444         return {
1445             'name': move.rule_id and move.rule_id.name or "/",
1446             'origin': origin,
1447             'company_id': move.company_id and move.company_id.id or False,
1448             'date_planned': move.date,
1449             'product_id': move.product_id.id,
1450             'product_qty': move.product_qty,
1451             'product_uom': move.product_uom.id,
1452             'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1453             'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1454             'location_id': move.location_id.id,
1455             'move_dest_id': move.id,
1456             'group_id': group_id,
1457             'route_ids': [(4, x.id) for x in move.route_ids],
1458             'warehouse_id': move.warehouse_id and move.warehouse_id.id or False,
1459         }
1460
1461     def _push_apply(self, cr, uid, moves, context=None):
1462         push_obj = self.pool.get("stock.location.path")
1463         for move in moves:
1464             if not move.move_dest_id:
1465                 domain = [('location_from_id', '=', move.location_dest_id.id)]
1466                 if move.warehouse_id:
1467                     domain += ['|', ('warehouse_id', '=', move.warehouse_id.id), ('warehouse_id', '=', False)]
1468                 #priority goes to the route defined on the product and product category
1469                 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1470                 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1471                 if not rules:
1472                     #but if there's no rule matching, we try without filtering on routes
1473                     rules = push_obj.search(cr, uid, domain, order='route_sequence, sequence', context=context)
1474                 if rules:
1475                     rule = push_obj.browse(cr, uid, rules[0], context=context)
1476                     push_obj._apply(cr, uid, rule, move, context=context)
1477         return True
1478
1479     # Create the stock.move.putaway records
1480     def _putaway_apply(self, cr, uid, move, putaway, context=None):
1481         # Should call different methods here in later versions
1482         moveputaway_obj = self.pool.get('stock.move.putaway')
1483         quant_obj = self.pool.get('stock.quant')
1484         if putaway.method == 'fixed' and putaway.location_spec_id:
1485             for row in quant_obj.read_group(cr, uid, [('reservation_id', '=', move.id)], ['qty', 'lot_id'], ['lot_id'], context=context):
1486                 vals = {
1487                     'move_id': move.id,
1488                     'location_id': putaway.location_spec_id.id,
1489                     'quantity': row['qty'],
1490                     'lot_id': row.get('lot_id') and row['lot_id'][0] or False,
1491                 }
1492                 moveputaway_obj.create(cr, SUPERUSER_ID, vals, context=context)
1493
1494     def _putaway_check(self, cr, uid, ids, context=None):
1495         for move in self.browse(cr, uid, ids, context=context):
1496             putaway = self.pool.get('stock.location').get_putaway_strategy(cr, uid, move.location_dest_id, move.product_id, context=context)
1497             if putaway:
1498                 self._putaway_apply(cr, uid, move, putaway, context=context)
1499
1500     def _create_procurement(self, cr, uid, move, context=None):
1501         """ This will create a procurement order """
1502         return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1503
1504     def write(self, cr, uid, ids, vals, context=None):
1505         if context is None:
1506             context = {}
1507         if isinstance(ids, (int, long)):
1508             ids = [ids]
1509         # Check that we do not modify a stock.move which is done
1510         frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1511         for move in self.browse(cr, uid, ids, context=context):
1512             if move.state == 'done':
1513                 if frozen_fields.intersection(vals):
1514                     raise osv.except_osv(_('Operation Forbidden!'),
1515                         _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1516         propagated_changes_dict = {}
1517         #propagation of quantity change
1518         if vals.get('product_uom_qty'):
1519             propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1520         if vals.get('product_uom_id'):
1521             propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1522         #propagation of expected date:
1523         propagated_date_field = False
1524         if vals.get('date_expected'):
1525             #propagate any manual change of the expected date
1526             propagated_date_field = 'date_expected'
1527         elif (vals.get('state', '') == 'done' and vals.get('date')):
1528             #propagate also any delta observed when setting the move as done
1529             propagated_date_field = 'date'
1530
1531         if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1532             #any propagation is (maybe) needed
1533             for move in self.browse(cr, uid, ids, context=context):
1534                 if move.move_dest_id and move.propagate:
1535                     if 'date_expected' in propagated_changes_dict:
1536                         propagated_changes_dict.pop('date_expected')
1537                     if propagated_date_field:
1538                         current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1539                         new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1540                         delta = new_date - current_date
1541                         if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1542                             old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1543                             new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1544                             propagated_changes_dict['date_expected'] = new_move_date
1545                     #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1546                     #Note that, for pulled moves we intentionally don't propagate on the procurement.
1547                     if propagated_changes_dict:
1548                         self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1549         return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1550
1551     def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1552         """ On change of product quantity finds UoM and UoS quantities
1553         @param product_id: Product id
1554         @param product_qty: Changed Quantity of product
1555         @param product_uom: Unit of measure of product
1556         @param product_uos: Unit of sale of product
1557         @return: Dictionary of values
1558         """
1559         result = {
1560             'product_uos_qty': 0.00
1561         }
1562         warning = {}
1563
1564         if (not product_id) or (product_qty <= 0.0):
1565             result['product_qty'] = 0.0
1566             return {'value': result}
1567
1568         product_obj = self.pool.get('product.product')
1569         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1570
1571         # Warn if the quantity was decreased
1572         if ids:
1573             for move in self.read(cr, uid, ids, ['product_qty']):
1574                 if product_qty < move['product_qty']:
1575                     warning.update({
1576                         'title': _('Information'),
1577                         'message': _("By changing this quantity here, you accept the "
1578                                 "new quantity as complete: OpenERP will not "
1579                                 "automatically generate a back order.")})
1580                 break
1581
1582         if product_uos and product_uom and (product_uom != product_uos):
1583             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1584         else:
1585             result['product_uos_qty'] = product_qty
1586
1587         return {'value': result, 'warning': warning}
1588
1589     def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1590                           product_uos, product_uom):
1591         """ On change of product quantity finds UoM and UoS quantities
1592         @param product_id: Product id
1593         @param product_uos_qty: Changed UoS Quantity of product
1594         @param product_uom: Unit of measure of product
1595         @param product_uos: Unit of sale of product
1596         @return: Dictionary of values
1597         """
1598         result = {
1599             'product_uom_qty': 0.00
1600         }
1601         warning = {}
1602
1603         if (not product_id) or (product_uos_qty <= 0.0):
1604             result['product_uos_qty'] = 0.0
1605             return {'value': result}
1606
1607         product_obj = self.pool.get('product.product')
1608         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1609
1610         # Warn if the quantity was decreased
1611         for move in self.read(cr, uid, ids, ['product_uos_qty']):
1612             if product_uos_qty < move['product_uos_qty']:
1613                 warning.update({
1614                     'title': _('Warning: No Back Order'),
1615                     'message': _("By changing the quantity here, you accept the "
1616                                 "new quantity as complete: OpenERP will not "
1617                                 "automatically generate a Back Order.")})
1618                 break
1619
1620         if product_uos and product_uom and (product_uom != product_uos):
1621             result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1622         else:
1623             result['product_uom_qty'] = product_uos_qty
1624         return {'value': result, 'warning': warning}
1625
1626     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1627         """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1628         @param prod_id: Changed Product id
1629         @param loc_id: Source location id
1630         @param loc_dest_id: Destination location id
1631         @param partner_id: Address id of partner
1632         @return: Dictionary of values
1633         """
1634         if not prod_id:
1635             return {}
1636         user = self.pool.get('res.users').browse(cr, uid, uid)
1637         lang = user and user.lang or False
1638         if partner_id:
1639             addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1640             if addr_rec:
1641                 lang = addr_rec and addr_rec.lang or False
1642         ctx = {'lang': lang}
1643
1644         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1645         uos_id = product.uos_id and product.uos_id.id or False
1646         result = {
1647             'product_uom': product.uom_id.id,
1648             'product_uos': uos_id,
1649             'product_uom_qty': 1.00,
1650             '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'],
1651         }
1652         if not ids:
1653             result['name'] = product.partner_ref
1654         if loc_id:
1655             result['location_id'] = loc_id
1656         if loc_dest_id:
1657             result['location_dest_id'] = loc_dest_id
1658         return {'value': result}
1659
1660     def _picking_assign(self, cr, uid, move, context=None):
1661         if move.picking_id or not move.picking_type_id:
1662             return False
1663         context = context or {}
1664         pick_obj = self.pool.get("stock.picking")
1665         picks = []
1666         group = move.group_id and move.group_id.id or False
1667         picks = pick_obj.search(cr, uid, [
1668                 ('group_id', '=', group),
1669                 ('location_id', '=', move.location_id.id),
1670                 ('location_dest_id', '=', move.location_dest_id.id),
1671                 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
1672         if picks:
1673             pick = picks[0]
1674         else:
1675             values = {
1676                 'origin': move.origin,
1677                 'company_id': move.company_id and move.company_id.id or False,
1678                 'move_type': move.group_id and move.group_id.move_type or 'one',
1679                 'partner_id': move.group_id and move.group_id.partner_id and move.group_id.partner_id.id or False,
1680                 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
1681             }
1682             pick = pick_obj.create(cr, uid, values, context=context)
1683         move.write({'picking_id': pick})
1684         return True
1685
1686     def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1687         """ On change of Scheduled Date gives a Move date.
1688         @param date_expected: Scheduled Date
1689         @param date: Move Date
1690         @return: Move Date
1691         """
1692         if not date_expected:
1693             date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1694         return {'value': {'date': date_expected}}
1695
1696     def action_confirm(self, cr, uid, ids, context=None):
1697         """ Confirms stock move or put it in waiting if it's linked to another move.
1698         @return: List of ids.
1699         """
1700         states = {
1701             'confirmed': [],
1702             'waiting': []
1703         }
1704         for move in self.browse(cr, uid, ids, context=context):
1705             state = 'confirmed'
1706             for m in move.move_orig_ids:
1707                 if m.state not in ('done', 'cancel'):
1708                     state = 'waiting'
1709             states[state].append(move.id)
1710             self._picking_assign(cr, uid, move, context=context)
1711
1712         for state, write_ids in states.items():
1713             if len(write_ids):
1714                 self.write(cr, uid, write_ids, {'state': state})
1715                 if state == 'confirmed':
1716                     for move in self.browse(cr, uid, write_ids, context=context):
1717                         if move.procure_method == 'make_to_order':
1718                             self._create_procurement(cr, uid, move, context=context)
1719         moves = self.browse(cr, uid, ids, context=context)
1720         self._push_apply(cr, uid, moves, context=context)
1721         return True
1722
1723     def force_assign(self, cr, uid, ids, context=None):
1724         """ Changes the state to assigned.
1725         @return: True
1726         """
1727         return self.write(cr, uid, ids, {'state': 'assigned'})
1728
1729     def cancel_assign(self, cr, uid, ids, context=None):
1730         """ Changes the state to confirmed.
1731         @return: True
1732         """
1733         return self.write(cr, uid, ids, {'state': 'confirmed'})
1734
1735     def check_tracking(self, cr, uid, move, lot_id, context=None):
1736         """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
1737         """
1738         check = False
1739         if move.product_id.track_all and not move.location_dest_id.usage == 'inventory':
1740             check = True
1741         elif move.product_id.track_incoming and move.location_id.usage in ('supplier', 'transit', 'inventory') and move.location_dest_id.usage == 'internal':
1742             check = True
1743         elif move.product_id.track_outgoing and move.location_dest_id.usage in ('customer', 'transit') and move.location_id.usage == 'internal':
1744             check = True
1745         if check and not lot_id:
1746             raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (move.product_id.name))
1747
1748     def action_assign(self, cr, uid, ids, context=None):
1749         """ Checks the product type and accordingly writes the state.
1750         """
1751         context = context or {}
1752         quant_obj = self.pool.get("stock.quant")
1753         to_assign_moves = []
1754         for move in self.browse(cr, uid, ids, context=context):
1755             if move.state not in ('confirmed', 'waiting', 'assigned'):
1756                 continue
1757             if move.product_id.type == 'consu':
1758                 to_assign_moves.append(move.id)
1759                 continue
1760             else:
1761                 #build the prefered domain based on quants that moved in previous linked done move
1762                 prev_quant_ids = []
1763                 for m2 in move.move_orig_ids:
1764                     for q in m2.quant_ids:
1765                         prev_quant_ids.append(q.id)
1766                 prefered_domain = prev_quant_ids and [('id', 'in', prev_quant_ids)] or []
1767                 fallback_domain = prev_quant_ids and [('id', 'not in', prev_quant_ids)] or []
1768                 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
1769                 main_domain = [('reservation_id', '=', False), ('qty', '>', 0)]
1770                 #first try to find quants based on specific domains given by linked operations
1771                 for record in move.linked_move_operation_ids:
1772                     domain = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1773                     qty_already_assigned = sum([q.qty for q in record.reserved_quant_ids])
1774                     qty = record.qty - qty_already_assigned
1775                     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)
1776                     quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
1777                 #then if the move isn't totally assigned, try to find quants without any specific domain
1778                 if move.state != 'assigned':
1779                     qty_already_assigned = sum([q.qty for q in move.reserved_quant_ids])
1780                     qty = move.product_qty - qty_already_assigned
1781                     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)
1782                     quant_obj.quants_reserve(cr, uid, quants, move, context=context)
1783
1784         #force assignation of consumable products
1785         if to_assign_moves:
1786             self.force_assign(cr, uid, to_assign_moves, context=context)
1787         #check if a putaway rule is likely to be processed and store result on the move
1788         self._putaway_check(cr, uid, ids, context=context)
1789
1790     def action_cancel(self, cr, uid, ids, context=None):
1791         """ Cancels the moves and if all moves are cancelled it cancels the picking.
1792         @return: True
1793         """
1794         procurement_obj = self.pool.get('procurement.order')
1795         context = context or {}
1796         for move in self.browse(cr, uid, ids, context=context):
1797             if move.state == 'done':
1798                 raise osv.except_osv(_('Operation Forbidden!'),
1799                         _('You cannot cancel a stock move that has been set to \'Done\'.'))
1800             if move.reserved_quant_ids:
1801                 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
1802             if context.get('cancel_procurement'):
1803                 if move.propagate:
1804                     procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
1805                     procurement_obj.cancel(cr, uid, procurement_ids, context=context)
1806             elif move.move_dest_id:
1807                 #cancel chained moves
1808                 if move.propagate:
1809                     self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
1810                 elif move.move_dest_id.state == 'waiting':
1811                     self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'})
1812         return self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1813
1814     def action_done(self, cr, uid, ids, context=None):
1815         """ Makes the move done and if all moves are done, it will finish the picking.
1816         It assumes that quants are already assigned to stock moves.
1817         Putaway strategies should be applied
1818         @return:
1819         """
1820         context = context or {}
1821         picking_obj = self.pool.get("stock.picking")
1822         quant_obj = self.pool.get("stock.quant")
1823         pack_op_obj = self.pool.get("stock.pack.operation")
1824         todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
1825         if todo:
1826             self.action_confirm(cr, uid, todo, context=context)
1827
1828         pickings = set()
1829         procurement_ids = []
1830         for move in self.browse(cr, uid, ids, context=context):
1831             if move.picking_id:
1832                 pickings.add(move.picking_id.id)
1833             qty = move.product_qty
1834             main_domain = [('qty', '>', 0)]
1835             prefered_domain = [('reservation_id', '=', move.id)]
1836             fallback_domain = [('reservation_id', '=', False)]
1837             #first, process the move per linked operation first because it may imply some specific domains to consider
1838             for record in move.linked_move_operation_ids:
1839                 self.check_tracking(cr, uid, move, record.operation_id.lot_id.id, context=context)
1840                 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
1841                 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, record.qty, domain=dom, prefered_domain=prefered_domain, fallback_domain=fallback_domain, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
1842                 package_id = False
1843                 if not record.operation_id.package_id:
1844                     #if a package and a result_package is given, we don't enter here because it will be processed by process_packaging() later
1845                     #but for operations having only result_package_id, we will create new quants in the final package directly
1846                     package_id = record.operation_id.result_package_id.id or False
1847                 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)
1848                 #packaging process
1849                 pack_op_obj.process_packaging(cr, uid, record.operation_id, quants, context=context)
1850                 qty -= record.qty
1851             #then if the total quantity processed this way isn't enough, process the remaining quantity without any specific domain
1852             if qty > 0:
1853                 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
1854                 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)
1855                 quant_obj.quants_move(cr, uid, quants, move, context=context)
1856             #unreserve the quants and make them available for other operations/moves
1857             quant_obj.quants_unreserve(cr, uid, move, context=context)
1858
1859             #Check moves that were pushed
1860             if move.move_dest_id.state in ('waiting', 'confirmed'):
1861                 other_upstream_move_ids = self.search(cr, uid, [('id', '!=', move.id), ('state', 'not in', ['done', 'cancel']),
1862                                             ('move_dest_id', '=', move.move_dest_id.id)], context=context)
1863                 #If no other moves for the move that got pushed:
1864                 if not other_upstream_move_ids and move.move_dest_id.state in ('waiting', 'confirmed'):
1865                     self.action_assign(cr, uid, [move.move_dest_id.id], context=context)
1866             if move.procurement_id:
1867                 procurement_ids.append(move.procurement_id.id)
1868         self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1869         self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
1870         #check picking state to set the date_done is needed
1871         done_picking = []
1872         for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
1873             if picking.state == 'done' and not picking.date_done:
1874                 done_picking.append(picking.id)
1875         if done_picking:
1876             picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
1877         return True
1878
1879     def unlink(self, cr, uid, ids, context=None):
1880         context = context or {}
1881         for move in self.browse(cr, uid, ids, context=context):
1882             if move.state not in ('draft', 'cancel'):
1883                 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
1884         return super(stock_move, self).unlink(cr, uid, ids, context=context)
1885
1886     def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, context=None):
1887         """ Move the scrap/damaged product into scrap location
1888         @param cr: the database cursor
1889         @param uid: the user id
1890         @param ids: ids of stock move object to be scrapped
1891         @param quantity : specify scrap qty
1892         @param location_id : specify scrap location
1893         @param context: context arguments
1894         @return: Scraped lines
1895         """
1896         #quantity should be given in MOVE UOM
1897         if quantity <= 0:
1898             raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
1899         res = []
1900         for move in self.browse(cr, uid, ids, context=context):
1901             source_location = move.location_id
1902             if move.state == 'done':
1903                 source_location = move.location_dest_id
1904             #Previously used to prevent scraping from virtual location but not necessary anymore
1905             #if source_location.usage != 'internal':
1906                 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
1907                 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
1908             move_qty = move.product_qty
1909             uos_qty = quantity / move_qty * move.product_uos_qty
1910             default_val = {
1911                 'location_id': source_location.id,
1912                 'product_uom_qty': quantity,
1913                 'product_uos_qty': uos_qty,
1914                 'state': move.state,
1915                 'scrapped': True,
1916                 'location_dest_id': location_id,
1917                 'restrict_lot_id': restrict_lot_id,
1918             }
1919             new_move = self.copy(cr, uid, move.id, default_val)
1920
1921             res += [new_move]
1922             product_obj = self.pool.get('product.product')
1923             for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
1924                 if move.picking_id:
1925                     uom = product.uom_id.name if product.uom_id else ''
1926                     message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
1927                     move.picking_id.message_post(body=message)
1928
1929         self.action_done(cr, uid, res, context=context)
1930         return res
1931
1932     def action_consume(self, cr, uid, ids, quantity, location_id=False, restrict_lot_id=False, context=None):
1933         """ 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
1934         @param ids: ids of stock move object to be consumed
1935         @param quantity : specify consume quantity (given in move UoM)
1936         @param location_id : specify source location
1937         @return: Consumed lines
1938         """
1939         uom_obj = self.pool.get('product.uom')
1940         if context is None:
1941             context = {}
1942         if quantity <= 0:
1943             raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
1944         res = []
1945         for move in self.browse(cr, uid, ids, context=context):
1946             move_qty = move.product_qty
1947             uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, quantity, move.product_uom.id)
1948             if move_qty <= 0:
1949                 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
1950             quantity_rest = move.product_qty - uom_qty
1951             if quantity_rest > 0:
1952                 ctx = context.copy()
1953                 if location_id:
1954                     ctx['source_location_id'] = location_id
1955                 res.append(self.split(cr, uid, move, move_qty - quantity_rest, restrict_lot_id=restrict_lot_id, context=ctx))
1956             else:
1957                 res.append(move.id)
1958                 if location_id:
1959                     self.write(cr, uid, [move.id], {'location_id': location_id, 'restrict_lot_id': restrict_lot_id}, context=context)
1960
1961         self.action_done(cr, uid, res, context=context)
1962         return res
1963
1964     def split(self, cr, uid, move, qty, restrict_lot_id=False, context=None):
1965         """ Splits qty from move move into a new move
1966         :param move: browse record
1967         :param qty: float. quantity to split (given in product UoM)
1968         :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
1969         """
1970         if move.product_qty <= qty or qty == 0:
1971             return move.id
1972
1973         uom_obj = self.pool.get('product.uom')
1974         context = context or {}
1975
1976         uom_qty = uom_obj._compute_qty(cr, uid, move.product_id.uom_id.id, qty, move.product_uom.id)
1977         uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
1978
1979         if move.state in ('done', 'cancel'):
1980             raise osv.except_osv(_('Error'), _('You cannot split a move done'))
1981
1982         defaults = {
1983             'product_uom_qty': uom_qty,
1984             'product_uos_qty': uos_qty,
1985             'state': move.state,
1986             'procure_method': 'make_to_stock',
1987             'move_dest_id': False,
1988             'reserved_quant_ids': [],
1989             'restrict_lot_id': restrict_lot_id,
1990         }
1991         if context.get('source_location_id'):
1992             defaults['location_id'] = context['source_location_id']
1993         new_move = self.copy(cr, uid, move.id, defaults)
1994
1995         ctx = context.copy()
1996         ctx['do_not_propagate'] = True
1997         self.write(cr, uid, [move.id], {
1998             'product_uom_qty': move.product_uom_qty - uom_qty,
1999             'product_uos_qty': move.product_uos_qty - uos_qty,
2000             #'reserved_quant_ids': [(6,0,[])]  SHOULD NOT CHANGE as it has been reserved already
2001         }, context=ctx)
2002
2003         if move.move_dest_id and move.propagate:
2004             new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2005             self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2006
2007         self.action_confirm(cr, uid, [new_move], context=context)
2008         return new_move
2009
2010 class stock_inventory(osv.osv):
2011     _name = "stock.inventory"
2012     _description = "Inventory"
2013
2014     def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2015         res = {}
2016         for inv in self.browse(cr, uid, ids, context=context):
2017             res[inv.id] = False
2018             if inv.move_ids:
2019                 res[inv.id] = True
2020         return res
2021
2022     def _get_available_filters(self, cr, uid, context=None):
2023         """
2024            This function will return the list of filter allowed according to the options checked
2025            in 'Settings\Warehouse'.
2026
2027            :rtype: list of tuple
2028         """
2029         #default available choices
2030         res_filter = [('none', _('All products of a whole location')), ('product', _('One product only'))]
2031         settings_obj = self.pool.get('stock.config.settings')
2032         config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2033         #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2034         if not config_ids:
2035             return res_filter
2036
2037         stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2038         if stock_settings.group_stock_tracking_owner:
2039             res_filter.append(('owner', _('One owner only')))
2040             res_filter.append(('product_owner', _('One product for a specific owner')))
2041         if stock_settings.group_stock_tracking_lot:
2042             res_filter.append(('lot', _('One Lot/Serial Number')))
2043         if stock_settings.group_stock_packaging:
2044             res_filter.append(('pack', _('A Pack')))
2045         return res_filter
2046
2047     _columns = {
2048         'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2049         'date': fields.datetime('Inventory Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Create Date."),
2050         'date_done': fields.datetime('Date done', help="Inventory Validation Date."),
2051         'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines."),
2052         'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves."),
2053         'state': fields.selection([('draft', 'Draft'), ('cancel', 'Cancelled'), ('confirm', 'In Progress'), ('done', 'Validated')], 'Status', readonly=True, select=True),
2054         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2055         'location_id': fields.many2one('stock.location', 'Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2056         'product_id': fields.many2one('product.product', 'Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2057         '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."),
2058         'partner_id': fields.many2one('res.partner', 'Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2059         '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."),
2060         'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2061         'filter': fields.selection(_get_available_filters, 'Selection Filter'),
2062     }
2063
2064     def _default_stock_location(self, cr, uid, context=None):
2065         try:
2066             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2067             return warehouse.lot_stock_id.id
2068         except:
2069             return False
2070
2071     _defaults = {
2072         'date': fields.datetime.now,
2073         'state': 'draft',
2074         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2075         'location_id': _default_stock_location,
2076     }
2077
2078     def set_checked_qty(self, cr, uid, ids, context=None):
2079         inventory = self.browse(cr, uid, ids[0], context=context)
2080         line_ids = [line.id for line in inventory.line_ids]
2081         self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2082         return True
2083
2084     def copy(self, cr, uid, id, default=None, context=None):
2085         if default is None:
2086             default = {}
2087         default = default.copy()
2088         default.update({'move_ids': [], 'date_done': False})
2089         return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2090
2091     def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2092         """ Creates a stock move from an inventory line
2093         @param inventory_line:
2094         @param move_vals:
2095         @return:
2096         """
2097         return self.pool.get('stock.move').create(cr, uid, move_vals)
2098
2099     def action_done(self, cr, uid, ids, context=None):
2100         """ Finish the inventory
2101         @return: True
2102         """
2103         if context is None:
2104             context = {}
2105         move_obj = self.pool.get('stock.move')
2106         for inv in self.browse(cr, uid, ids, context=context):
2107             if not inv.move_ids:
2108                 self.action_check(cr, uid, [inv.id], context=context)
2109             inv.refresh()
2110             #the action_done on stock_move has to be done in 2 steps:
2111             #first, we start moving the products from stock to inventory loss
2112             move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage == 'internal'], context=context)
2113             #then, we move from inventory loss. This 2 steps process is needed because some moved quant may need to be put again in stock
2114             move_obj.action_done(cr, uid, [x.id for x in inv.move_ids if x.location_id.usage != 'internal'], context=context)
2115             self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2116         return True
2117
2118     def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2119         stock_move_obj = self.pool.get('stock.move')
2120         product_obj = self.pool.get('product.product')
2121         inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2122         vals = {
2123             'name': _('INV:') + (inventory.name or ''),
2124             'product_id': todo_line['product_id'],
2125             'product_uom': todo_line['product_uom_id'],
2126             'date': inventory.date,
2127             'company_id': inventory.company_id.id,
2128             'inventory_id': inventory.id,
2129             'state': 'assigned',
2130             'restrict_lot_id': todo_line.get('prod_lot_id'),
2131             'restrict_partner_id': todo_line.get('partner_id'),
2132          }
2133
2134         if todo_line['product_qty'] < 0:
2135             #found more than expected
2136             vals['location_id'] = inventory_location_id
2137             vals['location_dest_id'] = todo_line['location_id']
2138             vals['product_uom_qty'] = -todo_line['product_qty']
2139         else:
2140             #found less than expected
2141             vals['location_id'] = todo_line['location_id']
2142             vals['location_dest_id'] = inventory_location_id
2143             vals['product_uom_qty'] = todo_line['product_qty']
2144         return stock_move_obj.create(cr, uid, vals, context=context)
2145
2146     def action_check(self, cr, uid, ids, context=None):
2147         """ Checks the inventory and computes the stock move to do
2148         @return: True
2149         """
2150         inventory_line_obj = self.pool.get('stock.inventory.line')
2151         stock_move_obj = self.pool.get('stock.move')
2152         for inventory in self.browse(cr, uid, ids, context=context):
2153             #first remove the existing stock moves linked to this inventory
2154             move_ids = [move.id for move in inventory.move_ids]
2155             stock_move_obj.unlink(cr, uid, move_ids, context=context)
2156             #compute what should be in the inventory lines
2157             theorical_lines = self._get_inventory_lines(cr, uid, inventory, context=context)
2158             for line in inventory.line_ids:
2159                 #compare the inventory lines to the theorical ones and store the diff in theorical_lines
2160                 inventory_line_obj._resolve_inventory_line(cr, uid, line, theorical_lines, context=context)
2161             #each theorical_lines where product_qty is not 0 is a difference for which we need to create a stock move
2162             for todo_line in theorical_lines:
2163                 if todo_line['product_qty'] != 0:
2164                     self._create_stock_move(cr, uid, inventory, todo_line, context=context)
2165
2166     def action_cancel_draft(self, cr, uid, ids, context=None):
2167         """ Cancels the stock move and change inventory state to draft.
2168         @return: True
2169         """
2170         for inv in self.browse(cr, uid, ids, context=context):
2171             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2172             self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2173         return True
2174
2175     def action_cancel_inventory(self, cr, uid, ids, context=None):
2176         self.action_cancel_draft(cr, uid, ids, context=context)
2177
2178     def prepare_inventory(self, cr, uid, ids, context=None):
2179         inventory_line_obj = self.pool.get('stock.inventory.line')
2180         for inventory in self.browse(cr, uid, ids, context=context):
2181             #clean the existing inventory lines before redoing an inventory proposal
2182             line_ids = [line.id for line in inventory.line_ids]
2183             inventory_line_obj.unlink(cr, uid, line_ids, context=context)
2184             #compute the inventory lines and create them
2185             vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2186             for product_line in vals:
2187                 inventory_line_obj.create(cr, uid, product_line, context=context)
2188         return self.write(cr, uid, ids, {'state': 'confirm'})
2189
2190     def _get_inventory_lines(self, cr, uid, inventory, context=None):
2191         location_obj = self.pool.get('stock.location')
2192         product_obj = self.pool.get('product.product')
2193         location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2194         domain = ' location_id in %s'
2195         args = (tuple(location_ids),)
2196         if inventory.partner_id:
2197             domain += ' and owner_id = %s'
2198             args += (inventory.partner_id.id,)
2199         if inventory.lot_id:
2200             domain += ' and lot_id = %s'
2201             args += (inventory.lot_id.id,)
2202         if inventory.product_id:
2203             domain += 'and product_id = %s'
2204             args += (inventory.product_id.id,)
2205         if inventory.package_id:
2206             domain += ' and package_id = %s'
2207             args += (inventory.package_id.id,)
2208         cr.execute('''
2209            SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2210            FROM stock_quant WHERE''' + domain + '''
2211            GROUP BY product_id, location_id, lot_id, package_id, partner_id
2212         ''', args)
2213         vals = []
2214         for product_line in cr.dictfetchall():
2215             #replace the None the dictionary by False, because falsy values are tested later on
2216             for key, value in product_line.items():
2217                 if not value:
2218                     product_line[key] = False
2219             product_line['inventory_id'] = inventory.id
2220             product_line['th_qty'] = product_line['product_qty']
2221             if product_line['product_id']:
2222                 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2223                 product_line['product_uom_id'] = product.uom_id.id
2224             vals.append(product_line)
2225         return vals
2226
2227 class stock_inventory_line(osv.osv):
2228     _name = "stock.inventory.line"
2229     _description = "Inventory Line"
2230     _rec_name = "inventory_id"
2231     _order = "inventory_id, location_name, product_code, product_name, prod_lot_id"
2232
2233     def _get_product_name_change(self, cr, uid, ids, context=None):
2234         return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2235
2236     def _get_location_change(self, cr, uid, ids, context=None):
2237         return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2238
2239     _columns = {
2240         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2241         'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2242         'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2243         'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2244         'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2245         'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2246         'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2247         'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2248         'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2249         'th_qty': fields.float('Theoretical Quantity', readonly=True),
2250         'partner_id': fields.many2one('res.partner', 'Owner'),
2251         'product_name': fields.related('product_id', 'name', type='char', string='Product name', store={
2252                                                                                             'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2253                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2254         'product_code': fields.related('product_id', 'default_code', type='char', string='Product code', store={
2255                                                                                             'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2256                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2257         'location_name': fields.related('location_id', 'complete_name', type='char', string='Location name', store={
2258                                                                                             'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2259                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2260     }
2261
2262     _defaults = {
2263         'product_qty': 1,
2264     }
2265
2266     def _resolve_inventory_line(self, cr, uid, inventory_line, theorical_lines, context=None):
2267         #TODO : package_id management !
2268         found = False
2269         uom_obj = self.pool.get('product.uom')
2270         for th_line in theorical_lines:
2271             #We try to match the inventory line with a theorical line with same product, lot, location and owner
2272             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:
2273                 uom_reference = inventory_line.product_id.uom_id
2274                 real_qty = uom_obj._compute_qty_obj(cr, uid, inventory_line.product_uom_id, inventory_line.product_qty, uom_reference)
2275                 th_line['product_qty'] -= real_qty
2276                 found = True
2277                 break
2278         #if it was still not found, we add it to the theorical lines so that it will create a stock move for it
2279         if not found:
2280             vals = {
2281                 'inventory_id': inventory_line.inventory_id.id,
2282                 'location_id': inventory_line.location_id.id,
2283                 'product_id': inventory_line.product_id.id,
2284                 'product_uom_id': inventory_line.product_id.uom_id.id,
2285                 'product_qty': -inventory_line.product_qty,
2286                 'prod_lot_id': inventory_line.prod_lot_id.id,
2287                 'partner_id': inventory_line.partner_id.id,
2288             }
2289             theorical_lines.append(vals)
2290
2291     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):
2292         """ Changes UoM and name if product_id changes.
2293         @param location_id: Location id
2294         @param product: Changed product_id
2295         @param uom: UoM product
2296         @return:  Dictionary of changed values
2297         """
2298         context = context or {}
2299         if not product:
2300             return {'value': {'product_qty': 0.0, 'product_uom_id': False}}
2301         uom_obj = self.pool.get('product.uom')
2302         ctx = context.copy()
2303         ctx['location'] = location_id
2304         ctx['lot_id'] = lot_id
2305         ctx['owner_id'] = owner_id
2306         ctx['package_id'] = package_id
2307         obj_product = self.pool.get('product.product').browse(cr, uid, product, context=ctx)
2308         th_qty = obj_product.qty_available
2309         if uom and uom != obj_product.uom_id.id:
2310             uom_record = uom_obj.browse(cr, uid, uom, context=context)
2311             th_qty = uom_obj._compute_qty_obj(cr, uid, obj_product.uom_id, th_qty, uom_record)
2312         return {'value': {'th_qty': th_qty, 'product_uom_id': uom or obj_product.uom_id.id}}
2313
2314
2315 #----------------------------------------------------------
2316 # Stock Warehouse
2317 #----------------------------------------------------------
2318 class stock_warehouse(osv.osv):
2319     _name = "stock.warehouse"
2320     _description = "Warehouse"
2321
2322     _columns = {
2323         'name': fields.char('Name', size=128, required=True, select=True),
2324         'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2325         'partner_id': fields.many2one('res.partner', 'Address'),
2326         'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2327         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage', '=', 'internal')]),
2328         'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2329         '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'),
2330         'reception_steps': fields.selection([
2331             ('one_step', 'Receive goods directly in stock (1 step)'),
2332             ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2333             ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', required=True),
2334         'delivery_steps': fields.selection([
2335             ('ship_only', 'Ship directly from stock (Ship only)'),
2336             ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2337             ('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),
2338         'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2339         'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2340         'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2341         'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2342         'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2343         'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2344         'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2345         'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2346         'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2347         'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2348         'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2349         'reception_route_id': fields.many2one('stock.location.route', 'Reception Route'),
2350         'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2351         'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2352         'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2353         'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes'),
2354         'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse'),
2355     }
2356
2357     def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2358         resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2359         if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id 
2360             resupply_wh_ids.add(default_resupply_wh_id)
2361         resupply_wh_ids = list(resupply_wh_ids)        
2362         return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2363
2364     def _get_inter_wh_location(self, cr, uid, warehouse, context=None):
2365         ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2366         data_obj = self.pool.get('ir.model.data')
2367         try:
2368             inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2369         except:
2370             inter_wh_loc = False
2371         return inter_wh_loc
2372
2373     def _get_all_products_to_resupply(self, cr, uid, warehouse, context=None):
2374         return self.pool.get('product.product').search(cr, uid, [], context=context)
2375
2376     def _assign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2377         product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2378         self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2379
2380     def _unassign_route_on_products(self, cr, uid, warehouse, inter_wh_route_id, context=None):
2381         product_ids = self._get_all_products_to_resupply(cr, uid, warehouse, context=context)
2382         self.pool.get('product.product').write(cr, uid, product_ids, {'route_ids': [(3, inter_wh_route_id)]}, context=context)
2383
2384     def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2385         return {
2386             'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2387             'warehouse_selectable': False,
2388             'product_selectable': True,
2389             'product_categ_selectable': True,
2390             'supplied_wh_id': warehouse.id,
2391             'supplier_wh_id': wh.id,
2392         }
2393
2394     def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2395         location_obj = self.pool.get('stock.location')
2396         route_obj = self.pool.get('stock.location.route')
2397         pull_obj = self.pool.get('procurement.rule')
2398         #create route selectable on the product to resupply the warehouse from another one
2399         inter_wh_location_id = self._get_inter_wh_location(cr, uid, warehouse, context=context)
2400         if inter_wh_location_id:
2401             input_loc = warehouse.wh_input_stock_loc_id
2402             if warehouse.reception_steps == 'one_step':
2403                 input_loc = warehouse.lot_stock_id
2404             inter_wh_location = location_obj.browse(cr, uid, inter_wh_location_id, context=context)
2405             for wh in supplier_warehouses:
2406                 output_loc = wh.wh_output_stock_loc_id
2407                 if wh.delivery_steps == 'ship_only':
2408                     output_loc = wh.lot_stock_id
2409                 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2410                 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2411                 values = [(output_loc, inter_wh_location, wh.out_type_id.id, wh), (inter_wh_location, input_loc, warehouse.in_type_id.id, warehouse)]
2412                 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2413                 for pull_rule in pull_rules_list:
2414                     pull_obj.create(cr, uid, vals=pull_rule, context=context)
2415                 #if the warehouse is also set as default resupply method, assign this route automatically to all product
2416                 if default_resupply_wh and default_resupply_wh.id == wh.id:
2417                     self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2418                 #finally, save the route on the warehouse
2419                 self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2420
2421     def _default_stock_id(self, cr, uid, context=None):
2422         #lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2423         try:
2424             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2425             return warehouse.lot_stock_id.id
2426         except:
2427             return False
2428
2429     _defaults = {
2430         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2431         'lot_stock_id': _default_stock_id,
2432         'reception_steps': 'one_step',
2433         'delivery_steps': 'ship_only',
2434     }
2435     _sql_constraints = [
2436         ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2437         ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2438         ('default_resupply_wh_diff', 'check (id != default_resupply_wh_id)', 'The default resupply warehouse should be different that the warehouse itself!'),
2439     ]
2440
2441     def _get_partner_locations(self, cr, uid, ids, context=None):
2442         ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2443         data_obj = self.pool.get('ir.model.data')
2444         location_obj = self.pool.get('stock.location')
2445         try:
2446             customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2447             supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2448         except:
2449             customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2450             customer_loc = customer_loc and customer_loc[0] or False
2451             supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2452             supplier_loc = supplier_loc and supplier_loc[0] or False
2453         if not (customer_loc and supplier_loc):
2454             raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2455         return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2456
2457     def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2458         location_obj = self.pool.get('stock.location')
2459
2460         new_reception_step = new_reception_step or warehouse.reception_steps
2461         new_delivery_step = new_delivery_step or warehouse.delivery_steps
2462         if warehouse.reception_steps != new_reception_step:
2463             location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2464             if new_reception_step != 'one_step':
2465                 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2466             if new_reception_step == 'three_steps':
2467                 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2468
2469         if warehouse.delivery_steps != new_delivery_step:
2470             location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2471             if new_delivery_step != 'ship_only':
2472                 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2473             if new_delivery_step == 'pick_pack_ship':
2474                 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2475         return True
2476
2477     def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2478         return {
2479             'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2480             'product_categ_selectable': True,
2481             'product_selectable': False,
2482             'sequence': 10,
2483         }
2484
2485     def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2486         pull_rules_list = []
2487         for from_loc, dest_loc, pick_type_id, warehouse in values:
2488             pull_rules_list.append({
2489                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2490                 'location_src_id': from_loc.id,
2491                 'location_id': dest_loc.id,
2492                 'route_id': new_route_id,
2493                 'action': 'move',
2494                 'picking_type_id': pick_type_id,
2495                 'procure_method': 'make_to_order',
2496                 'warehouse_id': supplied_warehouse.id,
2497                 'propagate_warehouse_id': warehouse.id,
2498             })
2499         return pull_rules_list
2500
2501     def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
2502         first_rule = True
2503         push_rules_list = []
2504         pull_rules_list = []
2505         for from_loc, dest_loc, pick_type_id in values:
2506             push_rules_list.append({
2507                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2508                 'location_from_id': from_loc.id,
2509                 'location_dest_id': dest_loc.id,
2510                 'route_id': new_route_id,
2511                 'auto': 'manual',
2512                 'picking_type_id': pick_type_id,
2513                 'active': active,
2514                 'warehouse_id': warehouse.id,
2515             })
2516             pull_rules_list.append({
2517                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2518                 'location_src_id': from_loc.id,
2519                 'location_id': dest_loc.id,
2520                 'route_id': new_route_id,
2521                 'action': 'move',
2522                 'picking_type_id': pick_type_id,
2523                 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
2524                 'active': active,
2525                 'warehouse_id': warehouse.id,
2526             })
2527             first_rule = False
2528         return push_rules_list, pull_rules_list
2529
2530     def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
2531         route_obj = self.pool.get('stock.location.route')
2532         data_obj = self.pool.get('ir.model.data')
2533         try:
2534             mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
2535         except:
2536             mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
2537             mto_route_id = mto_route_id and mto_route_id[0] or False
2538         if not mto_route_id:
2539             raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
2540
2541         from_loc, dest_loc, pick_type_id = values[0]
2542         return {
2543             'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
2544             'location_src_id': from_loc.id,
2545             'location_id': dest_loc.id,
2546             'route_id': mto_route_id,
2547             'action': 'move',
2548             'picking_type_id': pick_type_id,
2549             'procure_method': 'make_to_order',
2550             'active': True,
2551             'warehouse_id': warehouse.id,
2552         }
2553
2554     def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
2555         return {
2556             'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2557             'warehouse_selectable': False,
2558             'product_selectable': True,
2559             'product_categ_selectable': True,
2560             'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
2561             'sequence': 20,
2562         }
2563
2564     def create_routes(self, cr, uid, ids, warehouse, context=None):
2565         wh_route_ids = []
2566         route_obj = self.pool.get('stock.location.route')
2567         pull_obj = self.pool.get('procurement.rule')
2568         push_obj = self.pool.get('stock.location.path')
2569         routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2570         #create reception route and rules
2571         route_name, values = routes_dict[warehouse.reception_steps]
2572         route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2573         reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
2574         wh_route_ids.append((4, reception_route_id))
2575         push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
2576         #create the push/pull rules
2577         for push_rule in push_rules_list:
2578             push_obj.create(cr, uid, vals=push_rule, context=context)
2579         for pull_rule in pull_rules_list:
2580             #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
2581             pull_rule['procure_method'] = 'make_to_order'
2582             pull_obj.create(cr, uid, vals=pull_rule, context=context)
2583
2584         #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
2585         route_name, values = routes_dict[warehouse.delivery_steps]
2586         route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
2587         #create the route and its pull rules
2588         delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
2589         wh_route_ids.append((4, delivery_route_id))
2590         dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
2591         for pull_rule in pull_rules_list:
2592             pull_obj.create(cr, uid, vals=pull_rule, context=context)
2593         #create MTO pull rule and link it to the generic MTO route
2594         mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2595         mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
2596
2597         #create a route for cross dock operations, that can be set on products and product categories
2598         route_name, values = routes_dict['crossdock']
2599         crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
2600         crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
2601         wh_route_ids.append((4, crossdock_route_id))
2602         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)
2603         for pull_rule in pull_rules_list:
2604             pull_obj.create(cr, uid, vals=pull_rule, context=context)
2605
2606         #create route selectable on the product to resupply the warehouse from another one
2607         self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
2608
2609         #return routes and mto pull rule to store on the warehouse
2610         return {
2611             'route_ids': wh_route_ids,
2612             'mto_pull_id': mto_pull_id,
2613             'reception_route_id': reception_route_id,
2614             'delivery_route_id': delivery_route_id,
2615             'crossdock_route_id': crossdock_route_id,
2616         }
2617
2618     def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2619         picking_type_obj = self.pool.get('stock.picking.type')
2620         pull_obj = self.pool.get('procurement.rule')
2621         push_obj = self.pool.get('stock.location.path')
2622         route_obj = self.pool.get('stock.location.route')
2623         new_reception_step = new_reception_step or warehouse.reception_steps
2624         new_delivery_step = new_delivery_step or warehouse.delivery_steps
2625
2626         #change the default source and destination location and (de)activate picking types
2627         input_loc = warehouse.wh_input_stock_loc_id
2628         if new_reception_step == 'one_step':
2629             input_loc = warehouse.lot_stock_id
2630         output_loc = warehouse.wh_output_stock_loc_id
2631         if new_delivery_step == 'ship_only':
2632             output_loc = warehouse.lot_stock_id
2633         picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
2634         picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
2635         picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
2636         picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
2637
2638         routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
2639         #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
2640         pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
2641         route_name, values = routes_dict[new_delivery_step]
2642         route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2643         dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
2644         #create the pull rules
2645         for pull_rule in pull_rules_list:
2646             pull_obj.create(cr, uid, vals=pull_rule, context=context)
2647
2648         #update reception route and rules: unlink the existing rules of the warehouse reception route and recreate it
2649         pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
2650         push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
2651         route_name, values = routes_dict[new_reception_step]
2652         route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
2653         push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
2654         #create the push/pull rules
2655         for push_rule in push_rules_list:
2656             push_obj.create(cr, uid, vals=push_rule, context=context)
2657         for pull_rule in pull_rules_list:
2658             #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
2659             pull_rule['procure_method'] = 'make_to_order'
2660             pull_obj.create(cr, uid, vals=pull_rule, context=context)
2661
2662         route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
2663
2664         #change MTO rule
2665         dummy, values = routes_dict[new_delivery_step]
2666         mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)
2667         pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
2668         return True
2669
2670     def create(self, cr, uid, vals, context=None):
2671         if context is None:
2672             context = {}
2673         if vals is None:
2674             vals = {}
2675         data_obj = self.pool.get('ir.model.data')
2676         seq_obj = self.pool.get('ir.sequence')
2677         picking_type_obj = self.pool.get('stock.picking.type')
2678         location_obj = self.pool.get('stock.location')
2679
2680         #create view location for warehouse
2681         wh_loc_id = location_obj.create(cr, uid, {
2682                 'name': _(vals.get('name')),
2683                 'usage': 'view',
2684                 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
2685             }, context=context)
2686         vals['view_location_id'] = wh_loc_id
2687         #create all location
2688         def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
2689         reception_steps = vals.get('reception_steps',  def_values['reception_steps'])
2690         delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
2691         context_with_inactive = context.copy()
2692         context_with_inactive['active_test'] = False
2693         sub_locations = [
2694             {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
2695             {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
2696             {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
2697             {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
2698             {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
2699         ]
2700         for values in sub_locations:
2701             location_id = location_obj.create(cr, uid, {
2702                 'name': values['name'],
2703                 'usage': 'internal',
2704                 'location_id': wh_loc_id,
2705                 'active': values['active'],
2706             }, context=context_with_inactive)
2707             vals[values['field']] = location_id
2708
2709         #create new sequences
2710         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)
2711         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)
2712         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)
2713         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)
2714         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)
2715
2716         #create WH
2717         new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
2718
2719         warehouse = self.browse(cr, uid, new_id, context=context)
2720         wh_stock_loc = warehouse.lot_stock_id
2721         wh_input_stock_loc = warehouse.wh_input_stock_loc_id
2722         wh_output_stock_loc = warehouse.wh_output_stock_loc_id
2723         wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
2724
2725         #fetch customer and supplier locations, for references
2726         customer_loc, supplier_loc = self._get_partner_locations(cr, uid, new_id, context=context)
2727
2728         #create in, out, internal picking types for warehouse
2729         input_loc = wh_input_stock_loc
2730         if warehouse.reception_steps == 'one_step':
2731             input_loc = wh_stock_loc
2732         output_loc = wh_output_stock_loc
2733         if warehouse.delivery_steps == 'ship_only':
2734             output_loc = wh_stock_loc
2735
2736         #choose the next available color for the picking types of this warehouse
2737         color = 0
2738         available_colors = [c%9 for c in range(3, 12)]  # put flashy colors first
2739         all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
2740         #don't use sets to preserve the list order
2741         for x in all_used_colors:
2742             if x['color'] in available_colors:
2743                 available_colors.remove(x['color'])
2744         if available_colors:
2745             color = available_colors[0]
2746
2747         #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship. 
2748         max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
2749         max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
2750
2751         in_type_id = picking_type_obj.create(cr, uid, vals={
2752             'name': _('Receptions'),
2753             'warehouse_id': new_id,
2754             'code': 'incoming',
2755             'auto_force_assign': True,
2756             'sequence_id': in_seq_id,
2757             'default_location_src_id': supplier_loc.id,
2758             'default_location_dest_id': input_loc.id,
2759             'sequence': max_sequence + 1,
2760             'color': color}, context=context)
2761         out_type_id = picking_type_obj.create(cr, uid, vals={
2762             'name': _('Delivery Orders'),
2763             'warehouse_id': new_id,
2764             'code': 'outgoing',
2765             'sequence_id': out_seq_id,
2766             'return_picking_type_id': in_type_id,
2767             'default_location_src_id': output_loc.id,
2768             'default_location_dest_id': customer_loc.id,
2769             'sequence': max_sequence + 4,
2770             'color': color}, context=context)
2771         picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
2772         int_type_id = picking_type_obj.create(cr, uid, vals={
2773             'name': _('Internal Transfers'),
2774             'warehouse_id': new_id,
2775             'code': 'internal',
2776             'sequence_id': int_seq_id,
2777             'default_location_src_id': wh_stock_loc.id,
2778             'default_location_dest_id': wh_stock_loc.id,
2779             'active': True,
2780             'sequence': max_sequence + 2,
2781             'color': color}, context=context)
2782         pack_type_id = picking_type_obj.create(cr, uid, vals={
2783             'name': _('Pack'),
2784             'warehouse_id': new_id,
2785             'code': 'internal',
2786             'sequence_id': pack_seq_id,
2787             'default_location_src_id': wh_pack_stock_loc.id,
2788             'default_location_dest_id': output_loc.id,
2789             'active': delivery_steps == 'pick_pack_ship',
2790             'sequence': max_sequence + 3,
2791             'color': color}, context=context)
2792         pick_type_id = picking_type_obj.create(cr, uid, vals={
2793             'name': _('Pick'),
2794             'warehouse_id': new_id,
2795             'code': 'internal',
2796             'sequence_id': pick_seq_id,
2797             'default_location_src_id': wh_stock_loc.id,
2798             'default_location_dest_id': wh_pack_stock_loc.id,
2799             'active': delivery_steps != 'ship_only',
2800             'sequence': max_sequence + 2,
2801             'color': color}, context=context)
2802
2803         #write picking types on WH
2804         vals = {
2805             'in_type_id': in_type_id,
2806             'out_type_id': out_type_id,
2807             'pack_type_id': pack_type_id,
2808             'pick_type_id': pick_type_id,
2809             'int_type_id': int_type_id,
2810         }
2811         super(stock_warehouse, self).write(cr, uid, new_id, vals=vals, context=context)
2812         warehouse.refresh()
2813
2814         #create routes and push/pull rules
2815         new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
2816         self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
2817         return new_id
2818
2819     def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
2820         return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
2821
2822     def _format_routename(self, cr, uid, obj, name, context=None):
2823         return obj.name + ': ' + name
2824
2825     def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
2826         #fetch customer and supplier locations, for references
2827         customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
2828
2829         return {
2830             'one_step': (_('Reception in 1 step'), []),
2831             'two_steps': (_('Reception in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
2832             '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)]),
2833             '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)]),
2834             'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
2835             '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)]),
2836             '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)]),
2837         }
2838
2839     def _handle_renaming(self, cr, uid, warehouse, name, context=None):
2840         location_obj = self.pool.get('stock.location')
2841         route_obj = self.pool.get('stock.location.route')
2842         pull_obj = self.pool.get('procurement.rule')
2843         push_obj = self.pool.get('stock.location.path')
2844         #rename location
2845         location_id = warehouse.lot_stock_id.location_id.id
2846         location_obj.write(cr, uid, location_id, {'name': name}, context=context)
2847         #rename route and push-pull rules
2848         for route in warehouse.route_ids:
2849             route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
2850             for pull in route.pull_ids:
2851                 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2852             for push in route.push_ids:
2853                 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
2854         #change the mto pull rule name
2855         pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
2856
2857     def write(self, cr, uid, ids, vals, context=None):
2858         if context is None:
2859             context = {}
2860         if isinstance(ids, (int, long)):
2861             ids = [ids]
2862         seq_obj = self.pool.get('ir.sequence')
2863         route_obj = self.pool.get('stock.location.route')
2864
2865         context_with_inactive = context.copy()
2866         context_with_inactive['active_test'] = False
2867         for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
2868             #first of all, check if we need to delete and recreate route
2869             if vals.get('reception_steps') or vals.get('delivery_steps'):
2870                 #activate and deactivate location according to reception and delivery option
2871                 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
2872                 # switch between route
2873                 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
2874             if vals.get('code') or vals.get('name'):
2875                 name = warehouse.name
2876                 #rename sequence
2877                 if vals.get('name'):
2878                     name = vals.get('name')
2879                     self._handle_renaming(cr, uid, warehouse, name, context=context_with_inactive)
2880                 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)
2881                 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)
2882                 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)
2883                 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)
2884                 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)
2885         if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
2886             for cmd in vals.get('resupply_wh_ids'):
2887                 if cmd[0] == 6:
2888                     new_ids = set(cmd[2])
2889                     old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
2890                     to_add_wh_ids = new_ids - old_ids
2891                     if to_add_wh_ids:
2892                         supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
2893                         self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
2894                     to_remove_wh_ids = old_ids - new_ids
2895                     if to_remove_wh_ids:
2896                         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)
2897                         if to_remove_route_ids:
2898                             route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
2899                 else:
2900                     #not implemented
2901                     pass
2902         if 'default_resupply_wh_id' in vals:
2903             if warehouse.default_resupply_wh_id:
2904                 #remove the existing resupplying route on all products
2905                 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)
2906                 for inter_wh_route_id in to_remove_route_ids:
2907                     self._unassign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2908             if vals.get('default_resupply_wh_id'):
2909                 #assign the new resupplying route on all products
2910                 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)
2911                 for inter_wh_route_id in to_assign_route_ids:
2912                     self._assign_route_on_products(cr, uid, warehouse, inter_wh_route_id, context=context)
2913
2914         return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
2915
2916     def unlink(self, cr, uid, ids, context=None):
2917         #TODO try to delete location and route and if not possible, put them in inactive
2918         return super(stock_warehouse, self).unlink(cr, uid, ids, context=context)
2919
2920     def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
2921         all_routes = [route.id for route in warehouse.route_ids]
2922         all_routes += [warehouse.mto_pull_id.route_id.id]
2923         return all_routes
2924
2925     def view_all_routes_for_wh(self, cr, uid, ids, context=None):
2926         all_routes = []
2927         for wh in self.browse(cr, uid, ids, context=context):
2928             all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
2929
2930         domain = [('id', 'in', all_routes)]
2931         return {
2932             'name': _('Warehouse\'s Routes'),
2933             'domain': domain,
2934             'res_model': 'stock.location.route',
2935             'type': 'ir.actions.act_window',
2936             'view_id': False,
2937             'view_mode': 'tree,form',
2938             'view_type': 'form',
2939             'limit': 20
2940         }
2941
2942 class stock_location_path(osv.osv):
2943     _name = "stock.location.path"
2944     _description = "Pushed Flows"
2945     _order = "name"
2946
2947     def _get_route(self, cr, uid, ids, context=None):
2948         #WARNING TODO route_id is not required, so a field related seems a bad idea >-< 
2949         if context is None:
2950             context = {}
2951         result = {}
2952         if context is None:
2953             context = {}
2954         context_with_inactive = context.copy()
2955         context_with_inactive['active_test'] = False
2956         for route in self.pool.get('stock.location.route').browse(cr, uid, ids, context=context_with_inactive):
2957             for push_rule in route.push_ids:
2958                 result[push_rule.id] = True
2959         return result.keys()
2960
2961     def _get_rules(self, cr, uid, ids, context=None):
2962         res = []
2963         for route in self.browse(cr, uid, ids, context=context):
2964             res += [x.id for x in route.push_ids]
2965         return res
2966
2967     _columns = {
2968         'name': fields.char('Operation Name', size=64, required=True),
2969         'company_id': fields.many2one('res.company', 'Company'),
2970         'route_id': fields.many2one('stock.location.route', 'Route'),
2971         'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
2972         'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
2973         'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
2974         'invoice_state': fields.selection([
2975             ("invoiced", "Invoiced"),
2976             ("2binvoiced", "To Be Invoiced"),
2977             ("none", "Not Applicable")], "Invoice Status",
2978             required=True,), 
2979         '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"), 
2980         'auto': fields.selection(
2981             [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
2982             'Automatic Move',
2983             required=True, select=1,
2984             help="This is used to define paths the product has to follow within the location tree.\n" \
2985                 "The 'Automatic Move' value will create a stock move after the current one that will be "\
2986                 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
2987                 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
2988             ),
2989         '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'),
2990         'active': fields.related('route_id', 'active', type='boolean', string='Active', store={
2991                     'stock.location.route': (_get_route, ['active'], 20),
2992                     'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 20),},
2993                 help="If the active field is set to False, it will allow you to hide the rule without removing it." ),
2994         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
2995         'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
2996             store={
2997                 'stock.location.route': (_get_rules, ['sequence'], 10),
2998                 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
2999         }),
3000         'sequence': fields.integer('Sequence'),
3001     }
3002     _defaults = {
3003         'auto': 'auto',
3004         'delay': 1,
3005         'invoice_state': 'none',
3006         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3007         'propagate': True,
3008         'active': True,
3009     }
3010     def _apply(self, cr, uid, rule, move, context=None):
3011         move_obj = self.pool.get('stock.move')
3012         newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3013         if rule.auto == 'transparent':
3014             old_dest_location = move.location_dest_id.id
3015             move_obj.write(cr, uid, [move.id], {
3016                 'date': newdate,
3017                 'date_expected': newdate,
3018                 'location_dest_id': rule.location_dest_id.id
3019             })
3020             move.refresh()
3021             #avoid looping if a push rule is not well configured
3022             if rule.location_dest_id.id != old_dest_location:
3023                 #call again push_apply to see if a next step is defined
3024                 move_obj._push_apply(cr, uid, [move], context=context)
3025             return move.id
3026         else:
3027             move_id = move_obj.copy(cr, uid, move.id, {
3028                 'location_id': move.location_dest_id.id,
3029                 'location_dest_id': rule.location_dest_id.id,
3030                 'date': newdate,
3031                 'company_id': rule.company_id and rule.company_id.id or False,
3032                 'date_expected': newdate,
3033                 'picking_id': False,
3034                 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3035                 'propagate': rule.propagate,
3036                 'push_rule_id': rule.id,
3037                 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3038             })
3039             move_obj.write(cr, uid, [move.id], {
3040                 'move_dest_id': move_id,
3041             })
3042             move_obj.action_confirm(cr, uid, [move_id], context=None)
3043             return move_id
3044
3045 class stock_move_putaway(osv.osv):
3046     _name = 'stock.move.putaway'
3047     _description = 'Proposed Destination'
3048     _columns = {
3049         'move_id': fields.many2one('stock.move', required=True),
3050         'location_id': fields.many2one('stock.location', 'Location', required=True),
3051         'lot_id': fields.many2one('stock.production.lot', 'Lot'),
3052         'quantity': fields.float('Quantity', required=True),
3053     }
3054
3055
3056
3057 # -------------------------
3058 # Packaging related stuff
3059 # -------------------------
3060
3061 from openerp.report import report_sxw
3062 report_sxw.report_sxw('report.stock.quant.package.barcode', 'stock.quant.package', 'addons/stock/report/package_barcode.rml')
3063
3064 class stock_package(osv.osv):
3065     """
3066     These are the packages, containing quants and/or other packages
3067     """
3068     _name = "stock.quant.package"
3069     _description = "Physical Packages"
3070     _parent_name = "parent_id"
3071     _parent_store = True
3072     _parent_order = 'name'
3073     _order = 'parent_left'
3074
3075     def name_get(self, cr, uid, ids, context=None):
3076         res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3077         return res.items()
3078
3079     def _complete_name(self, cr, uid, ids, name, args, context=None):
3080         """ Forms complete name of location from parent location to child location.
3081         @return: Dictionary of values
3082         """
3083         res = {}
3084         for m in self.browse(cr, uid, ids, context=context):
3085             res[m.id] = m.name
3086             parent = m.parent_id
3087             while parent:
3088                 res[m.id] = parent.name + ' / ' + res[m.id]
3089                 parent = parent.parent_id
3090         return res
3091
3092     def _get_packages(self, cr, uid, ids, context=None):
3093         """Returns packages from quants for store"""
3094         res = set()
3095         for quant in self.browse(cr, uid, ids, context=context):
3096             if quant.package_id:
3097                 res.add(quant.package_id.id)
3098         return list(res)
3099
3100     def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3101         res = set()
3102         for pack in self.browse(cr, uid, ids, context=context):
3103             res.add(pack.id)
3104             if pack.parent_id:
3105                 res.add(pack.parent_id.id)
3106         return list(res)
3107
3108     # TODO: Problem when package is empty!
3109     #
3110     def _get_package_info(self, cr, uid, ids, name, args, context=None):
3111         default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3112         res = {}.fromkeys(ids, {'location_id': False, 'company_id': default_company_id})
3113         for pack in self.browse(cr, uid, ids, context=context):
3114             if pack.quant_ids:
3115                 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3116                 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3117                 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3118             elif pack.children_ids:
3119                 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3120                 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3121                 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3122         return res
3123
3124     _columns = {
3125         'name': fields.char('Package Reference', size=64, select=True),
3126         'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3127         'parent_left': fields.integer('Left Parent', select=1),
3128         'parent_right': fields.integer('Right Parent', select=1),
3129         'packaging_id': fields.many2one('product.packaging', 'Type of Packaging'),
3130         'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3131                                     store={
3132                                        'stock.quant': (_get_packages, ['location_id'], 10),
3133                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3134                                     }, readonly=True),
3135         'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content'),
3136         'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict'),
3137         'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages'),
3138         'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package", 
3139                                     store={
3140                                        'stock.quant': (_get_packages, ['company_id'], 10),
3141                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3142                                     }, readonly=True),
3143         'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3144                                 store={
3145                                        'stock.quant': (_get_packages, ['owner_id'], 10),
3146                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3147                                     }, readonly=True),
3148     }
3149     _defaults = {
3150         'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3151     }
3152     def _check_location(self, cr, uid, ids, context=None):
3153         '''checks that all quants in a package are stored in the same location'''
3154         quant_obj = self.pool.get('stock.quant')
3155         for pack in self.browse(cr, uid, ids, context=context):
3156             parent = pack
3157             while parent.parent_id:
3158                 parent = parent.parent_id
3159             quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3160             quants = quant_obj.browse(cr, uid, quant_ids, context=context)
3161             location_id = quants and quants[0].location_id.id or False
3162             if not all([quant.location_id.id == location_id for quant in quants]):
3163                 return False
3164         return True
3165
3166     _constraints = [
3167         (_check_location, 'Everything inside a package should be in the same location', ['location_id']),
3168     ]
3169
3170     def action_print(self, cr, uid, ids, context=None):
3171         if context is None:
3172             context = {}
3173         datas = {
3174             'ids': context.get('active_id') and [context.get('active_id')] or ids,
3175             'model': 'stock.quant.package',
3176             'form': self.read(cr, uid, ids)[0]
3177         }
3178         return {
3179             'type': 'ir.actions.report.xml',
3180             'report_name': 'stock.quant.package.barcode',
3181             'datas': datas
3182         }
3183
3184     def unpack(self, cr, uid, ids, context=None):
3185         quant_obj = self.pool.get('stock.quant')
3186         for package in self.browse(cr, uid, ids, context=context):
3187             quant_ids = [quant.id for quant in package.quant_ids]
3188             quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3189             children_package_ids = [child_package.id for child_package in package.children_ids]
3190             self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3191         #delete current package since it contains nothing anymore
3192         self.unlink(cr, uid, ids, context=context)
3193         return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3194
3195     def get_content(self, cr, uid, ids, context=None):
3196         child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3197         return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3198
3199     def get_content_package(self, cr, uid, ids, context=None):
3200         quants_ids = self.get_content(cr, uid, ids, context=context)
3201         res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3202         res['domain'] = [('id', 'in', quants_ids)]
3203         return res
3204
3205     def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3206         ''' find the total of given product 'product_id' inside the given package 'package_id'''
3207         quant_obj = self.pool.get('stock.quant')
3208         all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3209         total = 0
3210         for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3211             if quant.product_id.id == product_id:
3212                 total += quant.qty
3213         return total
3214
3215     def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3216         '''This function computes the different product quantities for the given package
3217         '''
3218         quant_obj = self.pool.get('stock.quant')
3219         res = {}
3220         for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3221             if quant.product_id.id not in res:
3222                 res[quant.product_id.id] = 0
3223             res[quant.product_id.id] += quant.qty
3224         return res
3225
3226 class stock_pack_operation(osv.osv):
3227     _name = "stock.pack.operation"
3228     _description = "Packing Operation"
3229
3230     def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3231         '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3232         #if the operation doesn't concern a package, it's not relevant to call this function
3233         if not operation.package_id or operation.product_id:
3234             return {operation.product_id.id: operation.remaining_qty}
3235         #get the total of products the package contains
3236         res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3237         #reduce by the quantities linked to a move
3238         for record in operation.linked_move_operation_ids:
3239             if record.move_id.product_id.id not in res:
3240                 res[record.move_id.product_id.id] = 0
3241             res[record.move_id.product_id.id] -= record.qty
3242         return res
3243
3244     def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3245         uom_obj = self.pool.get('product.uom')
3246         res = {}
3247         for ops in self.browse(cr, uid, ids, context=context):
3248             res[ops.id] = 0
3249             if ops.package_id:
3250                 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3251                 #should use _get_remaining_prod_quantities instead
3252                 continue
3253             elif ops.product_id:
3254                 qty = ops.product_qty
3255                 if ops.product_uom_id:
3256                     qty = uom_obj._compute_qty(cr, uid, ops.product_uom_id.id, ops.product_qty, ops.product_id.uom_id.id)
3257                 for record in ops.linked_move_operation_ids:
3258                     qty -= record.qty
3259                 #converting the remaining quantity in the pack operation UoM
3260                 if ops.product_uom_id:
3261                     qty = uom_obj._compute_qty(cr, uid, ops.product_id.uom_id.id, qty, ops.product_uom_id.id)
3262                 res[ops.id] = qty
3263         return res
3264
3265     def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3266         res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3267         if product_id and not product_uom_id:
3268             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3269             res['value']['product_uom_id'] = product.uom_id.id
3270         return res
3271
3272     def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3273         res = {'value': {}}
3274         uom_obj = self.pool.get('product.uom')
3275         if product_id:
3276             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3277             product_uom_id = product_uom_id or product.uom_id.id
3278             selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3279             if selected_uom.category_id.id != product.uom_id.category_id.id:
3280                 res['warning'] = {
3281                     'title': _('Warning: wrong UoM!'),
3282                     '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)
3283                 }
3284             if product_qty and 'warning' not in res:
3285                 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3286                 if rounded_qty != product_qty:
3287                     res['warning'] = {
3288                         'title': _('Warning: wrong quantity!'),
3289                         'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3290                     }
3291         return res
3292
3293     _columns = {
3294         'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3295         'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"),  # 1
3296         'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3297         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3298         'package_id': fields.many2one('stock.quant.package', 'Package'),  # 2
3299         'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3300         'result_package_id': fields.many2one('stock.quant.package', 'Container Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3301         'date': fields.datetime('Date', required=True),
3302         'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3303         #'update_cost': fields.boolean('Need cost update'),
3304         'cost': fields.float("Cost", help="Unit Cost for this product line"),
3305         'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3306         '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'),
3307         'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3308     }
3309
3310     _defaults = {
3311         'date': fields.date.context_today,
3312     }
3313
3314     def process_packaging(self, cr, uid, operation, quants, context=None):
3315         ''' Process the packaging of a given operation, after the quants have been moved. If there was not enough quants found
3316         a quant already has been with the good package information so we don't consider that case in this method'''
3317         quant_obj = self.pool.get("stock.quant")
3318         pack_obj = self.pool.get("stock.quant.package")
3319         for quant, qty in quants:
3320             if quant:
3321                 if operation.product_id:
3322                     #if a product + a package information is given, we consider that we took a part of an existing package (unpacking)
3323                     quant_obj.write(cr, SUPERUSER_ID, quant.id, {'package_id': operation.result_package_id.id}, context=context)
3324                 elif operation.package_id and operation.result_package_id:
3325                     #move the whole pack into the final package if any
3326                     pack_obj.write(cr, uid, [operation.package_id.id], {'parent_id': operation.result_package_id.id}, context=context)
3327
3328
3329
3330
3331     #TODO: this function can be refactored
3332     def _search_and_increment(self, cr, uid, picking_id, domain, context=None):
3333         '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3334
3335         :param domain: list of tuple directly reusable as a domain
3336         context can receive a key 'current_package_id' with the package to consider for this operation
3337         returns True
3338
3339         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
3340                  (0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
3341                  (1, ID, { values })    update the linked record with id = ID (write *values* on it)
3342                  (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)
3343         '''
3344         if context is None:
3345             context = {}
3346
3347         #if current_package_id is given in the context, we increase the number of items in this package
3348         package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3349         existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3350         if existing_operation_ids:
3351             #existing operation found for the given domain and picking => increment its quantity
3352             operation_id = existing_operation_ids[0]
3353             qty = self.browse(cr, uid, operation_id, context=context).product_qty + 1
3354             self.write(cr, uid, operation_id, {'product_qty': qty}, context=context)
3355         else:
3356             #no existing operation found for the given domain and picking => create a new one
3357             values = {
3358                 'picking_id': picking_id,
3359                 'product_qty': 1,
3360             }
3361             for key in domain:
3362                 var_name, dummy, value = key
3363                 uom_id = False
3364                 if var_name == 'product_id':
3365                     uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3366                 update_dict = {var_name: value}
3367                 if uom_id:
3368                     update_dict['product_uom_id'] = uom_id
3369                 values.update(update_dict)
3370             operation_id = self.create(cr, uid, values, context=context)
3371         return True
3372
3373
3374 class stock_move_operation_link(osv.osv):
3375     """
3376     Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3377     """
3378     _name = "stock.move.operation.link"
3379     _description = "Link between stock moves and pack operations"
3380
3381     _columns = {
3382         '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."),
3383         'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3384         'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3385         'reserved_quant_ids': fields.one2many('stock.quant', 'link_move_operation_id', 'Reserved quants'),
3386     }
3387
3388     def get_specific_domain(self, cr, uid, record, context=None):
3389         '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
3390         having the record given as parameter making the link between the stock move and a pack operation'''
3391         package_obj = self.pool.get('stock.quant.package')
3392
3393         op = record.operation_id
3394         domain = []
3395         if op.package_id:
3396             domain.append(('id', 'in', package_obj.get_content(cr, uid, [op.package_id.id], context=context)))
3397         if op.lot_id:
3398             domain.append(('lot_id', '=', op.lot_id.id))
3399         if op.owner_id:
3400             domain.append(('owner_id', '=', op.owner_id.id))
3401         else:
3402             domain.append(('owner_id', '=', False))
3403         return domain
3404
3405 class stock_warehouse_orderpoint(osv.osv):
3406     """
3407     Defines Minimum stock rules.
3408     """
3409     _name = "stock.warehouse.orderpoint"
3410     _description = "Minimum Inventory Rule"
3411
3412     def get_draft_procurements(self, cr, uid, ids, context=None):
3413         if context is None:
3414             context = {}
3415         if not isinstance(ids, list):
3416             ids = [ids]
3417         procurement_obj = self.pool.get('procurement.order')
3418         for orderpoint in self.browse(cr, uid, ids, context=context):
3419             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)            
3420         return list(set(procurement_ids))
3421
3422     def _check_product_uom(self, cr, uid, ids, context=None):
3423         '''
3424         Check if the UoM has the same category as the product standard UoM
3425         '''
3426         if not context:
3427             context = {}
3428
3429         for rule in self.browse(cr, uid, ids, context=context):
3430             if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
3431                 return False
3432
3433         return True
3434
3435     def action_view_proc_to_process(self, cr, uid, ids, context=None):        
3436         act_obj = self.pool.get('ir.actions.act_window')
3437         mod_obj = self.pool.get('ir.model.data')
3438         draft_ids = self.get_draft_procurements(cr, uid, ids, context=context)
3439         result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
3440         if not result:
3441             return False
3442  
3443         result = act_obj.read(cr, uid, [result[1]], context=context)[0]
3444         result['domain'] = "[('id', 'in', [" + ','.join(map(str, draft_ids)) + "])]"
3445         return result
3446
3447     _columns = {
3448         'name': fields.char('Name', size=32, required=True),
3449         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
3450         'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
3451         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
3452         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
3453         'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '!=', 'service')]),
3454         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
3455         'product_min_qty': fields.float('Minimum Quantity', required=True,
3456             help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
3457             "a procurement to bring the forecasted quantity to the Max Quantity."),
3458         'product_max_qty': fields.float('Maximum Quantity', required=True,
3459             help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
3460             "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
3461         'qty_multiple': fields.integer('Qty Multiple', required=True,
3462             help="The procurement quantity will be rounded up to this multiple."),
3463         'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
3464         'company_id': fields.many2one('res.company', 'Company', required=True)        
3465     }
3466     _defaults = {
3467         'active': lambda *a: 1,
3468         'logic': lambda *a: 'max',
3469         'qty_multiple': lambda *a: 1,
3470         'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3471         'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
3472         'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
3473     }
3474     _sql_constraints = [
3475         ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
3476     ]
3477     _constraints = [
3478         (_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']),
3479     ]
3480
3481     def default_get(self, cr, uid, fields, context=None):
3482         res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
3483         # default 'warehouse_id' and 'location_id'
3484         if 'warehouse_id' not in res:
3485             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
3486             res['warehouse_id'] = warehouse.id
3487         if 'location_id' not in res:
3488             warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
3489             res['location_id'] = warehouse.lot_stock_id.id
3490         return res
3491
3492     def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
3493         """ Finds location id for changed warehouse.
3494         @param warehouse_id: Changed id of warehouse.
3495         @return: Dictionary of values.
3496         """
3497         if warehouse_id:
3498             w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
3499             v = {'location_id': w.lot_stock_id.id}
3500             return {'value': v}
3501         return {}
3502
3503     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
3504         """ Finds UoM for changed product.
3505         @param product_id: Changed id of product.
3506         @return: Dictionary of values.
3507         """
3508         if product_id:
3509             prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3510             d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
3511             v = {'product_uom': prod.uom_id.id}
3512             return {'value': v, 'domain': d}
3513         return {'domain': {'product_uom': []}}
3514
3515     def copy(self, cr, uid, id, default=None, context=None):
3516         if not default:
3517             default = {}
3518         default.update({
3519             'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
3520         })
3521         return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
3522
3523
3524 class stock_picking_type(osv.osv):
3525     _name = "stock.picking.type"
3526     _description = "The picking type determines the picking view"
3527     _order = 'sequence'
3528
3529     def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
3530         """ Generic method to generate data for bar chart values using SparklineBarWidget.
3531             This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
3532
3533             :param obj: the target model (i.e. crm_lead)
3534             :param domain: the domain applied to the read_group
3535             :param list read_fields: the list of fields to read in the read_group
3536             :param str value_field: the field used to compute the value of the bar slice
3537             :param str groupby_field: the fields used to group
3538
3539             :return list section_result: a list of dicts: [
3540                                                 {   'value': (int) bar_column_value,
3541                                                     'tootip': (str) bar_column_tooltip,
3542                                                 }
3543                                             ]
3544         """
3545         month_begin = date.today().replace(day=1)
3546         section_result = [{
3547             'value': 0,
3548             'tooltip': (month_begin + relativedelta.relativedelta(months=i)).strftime('%B'),
3549         } for i in range(-2, 2, 1)]
3550         group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
3551         for group in group_obj:
3552             group_begin_date = datetime.strptime(group['__domain'][0][2], DEFAULT_SERVER_DATE_FORMAT)
3553             month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
3554             section_result[-month_delta.months + 2] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
3555             inner_groupby = (group.get('__context', {})).get('group_by',[])
3556             if inner_groupby:
3557                 groupby_picking = obj.read_group(cr, uid, group.get('__domain'), read_fields, inner_groupby, context=context)
3558                 for groupby in groupby_picking:
3559                     section_result[-month_delta.months + 2]['value'] = groupby.get(value_field, 0)
3560         return section_result
3561
3562     def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
3563         picking_obj = self.pool.get('stock.picking')
3564         res = dict.fromkeys(ids, [])
3565         for picking_type_id in ids:
3566             #get last 10 pickings of this type
3567             picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
3568             tristates = []
3569             for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
3570                 if picking.date_done > picking.date:
3571                     tristates.insert(0, {'tooltip': picking.name + _(': Late'), 'value': -1})
3572                 elif picking.backorder_id:
3573                     tristates.insert(0, {'tooltip': picking.name + _(': Backorder exists'), 'value': 0})
3574                 else:
3575                     tristates.insert(0, {'tooltip': picking.name + _(': OK'), 'value': 1})
3576             res[picking_type_id] = tristates
3577         return res
3578
3579
3580
3581     def _get_monthly_pickings(self, cr, uid, ids, field_name, arg, context=None):
3582         obj = self.pool.get('stock.picking')
3583         res = dict.fromkeys(ids, False)
3584         month_begin = date.today().replace(day=1)
3585         groupby_begin = (month_begin + relativedelta.relativedelta(months=-2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3586         groupby_end = (month_begin + relativedelta.relativedelta(months=2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
3587         for id in ids:
3588             created_domain = [
3589                 ('picking_type_id', '=', id),
3590                 ('state', '=', 'done'),
3591                 ('date', '>=', groupby_begin),
3592                 ('date', '<', groupby_end),
3593             ]
3594             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)
3595         return res
3596
3597     def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
3598         obj = self.pool.get('stock.picking')
3599         domains = {
3600             'count_picking_draft': [('state', '=', 'draft')],
3601             'count_picking_waiting': [('state','=', 'confirmed')],
3602             'count_picking_ready': [('state','=','assigned')],
3603             'count_picking': [('state','in',('assigned','waiting','confirmed'))],
3604             'count_picking_late': [('min_date','<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state','in',('assigned','waiting','confirmed'))],
3605             'count_picking_backorders': [('backorder_id','!=', False), ('state','in',('confirmed', 'assigned', 'waiting'))],
3606         }
3607         result = {}
3608         for field in domains:
3609             data = obj.read_group(cr, uid, domains[field] +
3610                 [('state', 'not in',('done','cancel')), ('picking_type_id', 'in', ids)],
3611                 ['picking_type_id'], ['picking_type_id'], context=context)
3612             count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
3613             for tid in ids:
3614                 result.setdefault(tid, {})[field] = count.get(tid, 0)
3615         for tid in ids:
3616             if result[tid]['count_picking']:
3617                 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] *100 / result[tid]['count_picking']
3618                 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] *100 / result[tid]['count_picking']
3619             else:
3620                 result[tid]['rate_picking_late'] = 0
3621                 result[tid]['rate_picking_backorders'] = 0
3622         return result
3623
3624     #TODO: not returning valus in required format to show in sparkline library,just added latest_picking_waiting need to add proper logic.
3625     def _get_picking_history(self, cr, uid, ids, field_names, arg, context=None):
3626         obj = self.pool.get('stock.picking')
3627         result = {}
3628         for id in ids:
3629             result[id] = {
3630                 'latest_picking_late': [],
3631                 'latest_picking_backorders': [],
3632                 'latest_picking_waiting': []
3633             }
3634         for type_id in ids:
3635             pick_ids = obj.search(cr, uid, [('state', '=','done'), ('picking_type_id','=',type_id)], limit=12, order="date desc", context=context)
3636             for pick in obj.browse(cr, uid, pick_ids, context=context):
3637                 result[type_id]['latest_picking_late'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3638                 result[type_id]['latest_picking_backorders'] = bool(pick.backorder_id)
3639                 result[type_id]['latest_picking_waiting'] = cmp(pick.date[:10], time.strftime('%Y-%m-%d'))
3640         return result
3641
3642     def onchange_picking_code(self, cr, uid, ids, picking_code=False):
3643         if not picking_code:
3644             return False
3645         
3646         obj_data = self.pool.get('ir.model.data')
3647         stock_loc = obj_data.get_object_reference(cr, uid, 'stock','stock_location_stock')[1]
3648         
3649         result = {
3650             'default_location_src_id': stock_loc,
3651             'default_location_dest_id': stock_loc,
3652         }
3653         if picking_code == 'incoming':
3654             result['default_location_src_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_suppliers')[1]
3655             return {'value': result}
3656         if picking_code == 'outgoing':
3657             result['default_location_dest_id'] = obj_data.get_object_reference(cr, uid, 'stock','stock_location_customers')[1]
3658             return {'value': result}
3659         else:
3660             return {'value': result}
3661
3662     def _get_name(self, cr, uid, ids, field_names, arg, context=None):
3663         return dict(self.name_get(cr, uid, ids, context=context))
3664
3665     def name_get(self, cr, uid, ids, context=None):
3666         """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
3667         if context is None:
3668             context = {}
3669         if not isinstance(ids, list):
3670             ids = [ids]
3671         res = []
3672         if not ids:
3673             return res
3674         for record in self.browse(cr, uid, ids, context=context):
3675             name = record.name
3676             if record.warehouse_id:
3677                 name = record.warehouse_id.name + ': ' +name
3678             if context.get('special_shortened_wh_name'):
3679                 if record.warehouse_id:
3680                     name = record.warehouse_id.name
3681                 else:
3682                     name = _('Customer') + ' (' + record.name + ')'
3683             res.append((record.id, name))
3684         return res
3685
3686     def _default_warehouse(self, cr, uid, context=None):
3687         user = self.pool.get('res.users').browse(cr, uid, uid, context)
3688         res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
3689         return res and res[0] or False
3690
3691     _columns = {
3692         'name': fields.char('Name', translate=True, required=True),
3693         'complete_name': fields.function(_get_name, type='char', string='Name'),
3694         'auto_force_assign': fields.boolean('Automatic Availability', help='This picking type does\'t need to check for the availability in source location.'),
3695         'color': fields.integer('Color'),
3696         'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
3697         'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
3698         'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
3699         'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
3700         'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
3701         'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
3702         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
3703         'active': fields.boolean('Active'),
3704
3705         # Statistics for the kanban view
3706         'monthly_picking': fields.function(_get_monthly_pickings,
3707             type='string',
3708             string='Done Pickings per Month'),
3709         'last_done_picking': fields.function(_get_tristate_values,
3710             type='string',
3711             string='Last 10 Done Pickings'),
3712
3713         'count_picking_draft': fields.function(_get_picking_count,
3714             type='integer', multi='_get_picking_count'),
3715         'count_picking_ready': fields.function(_get_picking_count,
3716             type='integer', multi='_get_picking_count'),
3717         'count_picking': fields.function(_get_picking_count,
3718             type='integer', multi='_get_picking_count'),
3719         'count_picking_waiting': fields.function(_get_picking_count,
3720             type='integer', multi='_get_picking_count'),
3721         'count_picking_late': fields.function(_get_picking_count,
3722             type='integer', multi='_get_picking_count'),
3723         'count_picking_backorders': fields.function(_get_picking_count,
3724             type='integer', multi='_get_picking_count'),
3725
3726         'rate_picking_late': fields.function(_get_picking_count,
3727             type='integer', multi='_get_picking_count'),
3728         'rate_picking_backorders': fields.function(_get_picking_count,
3729             type='integer', multi='_get_picking_count'),
3730
3731         'latest_picking_late': fields.function(_get_picking_history,
3732             type='string', multi='_get_picking_history'),
3733         'latest_picking_backorders': fields.function(_get_picking_history,
3734             type='string', multi='_get_picking_history'),
3735         'latest_picking_waiting': fields.function(_get_picking_history,
3736             type='string', multi='_get_picking_history'),
3737
3738     }
3739     _defaults = {
3740         'warehouse_id': _default_warehouse,
3741         'active': True,
3742     }
3743
3744
3745 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: