cb690e8cc9e2b34e385113149de463db3ffdf04b
[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 import json
25 import time
26
27 from openerp.osv import fields, osv
28 from openerp.tools.float_utils import float_compare
29 from openerp.tools.translate import _
30 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
31 from openerp import SUPERUSER_ID, api
32 import openerp.addons.decimal_precision as dp
33 from openerp.addons.procurement import procurement
34 import logging
35
36
37 _logger = logging.getLogger(__name__)
38 #----------------------------------------------------------
39 # Incoterms
40 #----------------------------------------------------------
41 class stock_incoterms(osv.osv):
42     _name = "stock.incoterms"
43     _description = "Incoterms"
44     _columns = {
45         'name': fields.char('Name', 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."),
46         'code': fields.char('Code', size=3, required=True, help="Incoterm Standard Code"),
47         'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM you will not use."),
48     }
49     _defaults = {
50         'active': True,
51     }
52
53 #----------------------------------------------------------
54 # Stock Location
55 #----------------------------------------------------------
56
57 class stock_location(osv.osv):
58     _name = "stock.location"
59     _description = "Inventory Locations"
60     _parent_name = "location_id"
61     _parent_store = True
62     _parent_order = 'name'
63     _order = 'parent_left'
64     _rec_name = 'complete_name'
65
66     def _location_owner(self, cr, uid, location, context=None):
67         ''' Return the company owning the location if any '''
68         return location and (location.usage == 'internal') and location.company_id or False
69
70     def _complete_name(self, cr, uid, ids, name, args, context=None):
71         """ Forms complete name of location from parent location to child location.
72         @return: Dictionary of values
73         """
74         res = {}
75         for m in self.browse(cr, uid, ids, context=context):
76             res[m.id] = m.name
77             parent = m.location_id
78             while parent:
79                 res[m.id] = parent.name + ' / ' + res[m.id]
80                 parent = parent.location_id
81         return res
82
83     def _get_sublocations(self, cr, uid, ids, context=None):
84         """ return all sublocations of the given stock locations (included) """
85         if context is None:
86             context = {}
87         context_with_inactive = context.copy()
88         context_with_inactive['active_test'] = False
89         return self.search(cr, uid, [('id', 'child_of', ids)], context=context_with_inactive)
90
91     def _name_get(self, cr, uid, location, context=None):
92         name = location.name
93         while location.location_id and location.usage != 'view':
94             location = location.location_id
95             name = location.name + '/' + name
96         return name
97
98     def name_get(self, cr, uid, ids, context=None):
99         res = []
100         for location in self.browse(cr, uid, ids, context=context):
101             res.append((location.id, self._name_get(cr, uid, location, context=context)))
102         return res
103
104     _columns = {
105         'name': fields.char('Location Name', required=True, translate=True),
106         'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
107         'usage': fields.selection([
108                         ('supplier', 'Supplier Location'),
109                         ('view', 'View'),
110                         ('internal', 'Internal Location'),
111                         ('customer', 'Customer Location'),
112                         ('inventory', 'Inventory'),
113                         ('procurement', 'Procurement'),
114                         ('production', 'Production'),
115                         ('transit', 'Transit Location')],
116                 'Location Type', required=True,
117                 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
118                        \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
119                        \n* Internal Location: Physical locations inside your own warehouses,
120                        \n* Customer Location: Virtual location representing the destination location for products sent to your customers
121                        \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
122                        \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.
123                        \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
124                        \n* Transit Location: Counterpart location that should be used in inter-companies or inter-warehouses operations
125                       """, select=True),
126         'complete_name': fields.function(_complete_name, type='char', string="Location Name",
127                             store={'stock.location': (_get_sublocations, ['name', 'location_id', 'active'], 10)}),
128         'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
129         'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
130
131         'partner_id': fields.many2one('res.partner', 'Owner', help="Owner of the location if not internal"),
132
133         'comment': fields.text('Additional Information'),
134         'posx': fields.integer('Corridor (X)', help="Optional localization details, for information purpose only"),
135         'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
136         'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
137
138         'parent_left': fields.integer('Left Parent', select=1),
139         'parent_right': fields.integer('Right Parent', select=1),
140
141         'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between companies'),
142         'scrap_location': fields.boolean('Is a Scrap Location?', help='Check this box to allow using this location to put scrapped/damaged goods.'),
143         'removal_strategy_id': fields.many2one('product.removal', 'Removal Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to take the products from, which lot etc. for this location. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
144         'putaway_strategy_id': fields.many2one('product.putaway', 'Put Away Strategy', help="Defines the default method used for suggesting the exact location (shelf) where to store the products. This method can be enforced at the product category level, and a fallback is made on the parent locations if none is set here."),
145         'loc_barcode': fields.char('Location Barcode'),
146     }
147     _defaults = {
148         'active': True,
149         'usage': 'internal',
150         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
151         'posx': 0,
152         'posy': 0,
153         'posz': 0,
154         'scrap_location': False,
155     }
156     _sql_constraints = [('loc_barcode_company_uniq', 'unique (loc_barcode,company_id)', 'The barcode for a location must be unique per company !')]
157
158     def create(self, cr, uid, default, context=None):
159         if not default.get('loc_barcode', False):
160             default.update({'loc_barcode': default.get('complete_name', False)})
161         return super(stock_location, self).create(cr, uid, default, context=context)
162
163     def get_putaway_strategy(self, cr, uid, location, product, context=None):
164         ''' Returns the location where the product has to be put, if any compliant putaway strategy is found. Otherwise returns None.'''
165         putaway_obj = self.pool.get('product.putaway')
166         loc = location
167         while loc:
168             if loc.putaway_strategy_id:
169                 res = putaway_obj.putaway_apply(cr, uid, loc.putaway_strategy_id, product, context=context)
170                 if res:
171                     return res
172             loc = loc.location_id
173
174     def _default_removal_strategy(self, cr, uid, context=None):
175         return 'fifo'
176
177     def get_removal_strategy(self, cr, uid, location, product, context=None):
178         ''' Returns the removal strategy to consider for the given product and location.
179             :param location: browse record (stock.location)
180             :param product: browse record (product.product)
181             :rtype: char
182         '''
183         if product.categ_id.removal_strategy_id:
184             return product.categ_id.removal_strategy_id.method
185         loc = location
186         while loc:
187             if loc.removal_strategy_id:
188                 return loc.removal_strategy_id.method
189             loc = loc.location_id
190         return self._default_removal_strategy(cr, uid, context=context)
191
192
193     def get_warehouse(self, cr, uid, location, context=None):
194         """
195             Returns warehouse id of warehouse that contains location
196             :param location: browse record (stock.location)
197         """
198         wh_obj = self.pool.get("stock.warehouse")
199         whs = wh_obj.search(cr, uid, [('view_location_id.parent_left', '<=', location.parent_left), 
200                                 ('view_location_id.parent_right', '>=', location.parent_left)], context=context)
201         return whs and whs[0] or False
202
203 #----------------------------------------------------------
204 # Routes
205 #----------------------------------------------------------
206
207 class stock_location_route(osv.osv):
208     _name = 'stock.location.route'
209     _description = "Inventory Routes"
210     _order = 'sequence'
211
212     _columns = {
213         'name': fields.char('Route Name', required=True),
214         'sequence': fields.integer('Sequence'),
215         'pull_ids': fields.one2many('procurement.rule', 'route_id', 'Pull Rules', copy=True),
216         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the route without removing it."),
217         'push_ids': fields.one2many('stock.location.path', 'route_id', 'Push Rules', copy=True),
218         'product_selectable': fields.boolean('Applicable on Product'),
219         'product_categ_selectable': fields.boolean('Applicable on Product Category'),
220         'warehouse_selectable': fields.boolean('Applicable on Warehouse'),
221         'supplied_wh_id': fields.many2one('stock.warehouse', 'Supplied Warehouse'),
222         'supplier_wh_id': fields.many2one('stock.warehouse', 'Supplier Warehouse'),
223         'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this route is shared between all companies'),
224     }
225
226     _defaults = {
227         'sequence': lambda self, cr, uid, ctx: 0,
228         'active': True,
229         'product_selectable': True,
230         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location.route', context=c),
231     }
232
233     def write(self, cr, uid, ids, vals, context=None):
234         '''when a route is deactivated, deactivate also its pull and push rules'''
235         if isinstance(ids, (int, long)):
236             ids = [ids]
237         res = super(stock_location_route, self).write(cr, uid, ids, vals, context=context)
238         if 'active' in vals:
239             push_ids = []
240             pull_ids = []
241             for route in self.browse(cr, uid, ids, context=context):
242                 if route.push_ids:
243                     push_ids += [r.id for r in route.push_ids if r.active != vals['active']]
244                 if route.pull_ids:
245                     pull_ids += [r.id for r in route.pull_ids if r.active != vals['active']]
246             if push_ids:
247                 self.pool.get('stock.location.path').write(cr, uid, push_ids, {'active': vals['active']}, context=context)
248             if pull_ids:
249                 self.pool.get('procurement.rule').write(cr, uid, pull_ids, {'active': vals['active']}, context=context)
250         return res
251
252 #----------------------------------------------------------
253 # Quants
254 #----------------------------------------------------------
255
256 class stock_quant(osv.osv):
257     """
258     Quants are the smallest unit of stock physical instances
259     """
260     _name = "stock.quant"
261     _description = "Quants"
262
263     def _get_quant_name(self, cr, uid, ids, name, args, context=None):
264         """ Forms complete name of location from parent location to child location.
265         @return: Dictionary of values
266         """
267         res = {}
268         for q in self.browse(cr, uid, ids, context=context):
269
270             res[q.id] = q.product_id.code or ''
271             if q.lot_id:
272                 res[q.id] = q.lot_id.name
273             res[q.id] += ': ' + str(q.qty) + q.product_id.uom_id.name
274         return res
275
276     def _calc_inventory_value(self, cr, uid, ids, name, attr, context=None):
277         context = dict(context or {})
278         res = {}
279         uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
280         for quant in self.browse(cr, uid, ids, context=context):
281             context.pop('force_company', None)
282             if quant.company_id.id != uid_company_id:
283                 #if the company of the quant is different than the current user company, force the company in the context
284                 #then re-do a browse to read the property fields for the good company.
285                 context['force_company'] = quant.company_id.id
286                 quant = self.browse(cr, uid, quant.id, context=context)
287             res[quant.id] = self._get_inventory_value(cr, uid, quant, context=context)
288         return res
289
290     def _get_inventory_value(self, cr, uid, quant, context=None):
291         return quant.product_id.standard_price * quant.qty
292
293     _columns = {
294         'name': fields.function(_get_quant_name, type='char', string='Identifier'),
295         'product_id': fields.many2one('product.product', 'Product', required=True, ondelete="restrict", readonly=True, select=True),
296         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="restrict", readonly=True, select=True),
297         'qty': fields.float('Quantity', required=True, help="Quantity of products in this quant, in the default unit of measure of the product", readonly=True, select=True),
298         'package_id': fields.many2one('stock.quant.package', string='Package', help="The package containing this quant", readonly=True, select=True),
299         'packaging_type_id': fields.related('package_id', 'packaging_id', type='many2one', relation='product.packaging', string='Type of packaging', readonly=True, store=True),
300         'reservation_id': fields.many2one('stock.move', 'Reserved for Move', help="The move the quant is reserved for", readonly=True, select=True),
301         'lot_id': fields.many2one('stock.production.lot', 'Lot', readonly=True, select=True),
302         'cost': fields.float('Unit Cost'),
303         'owner_id': fields.many2one('res.partner', 'Owner', help="This is the owner of the quant", readonly=True, select=True),
304
305         'create_date': fields.datetime('Creation Date', readonly=True),
306         'in_date': fields.datetime('Incoming Date', readonly=True, select=True),
307
308         'history_ids': fields.many2many('stock.move', 'stock_quant_move_rel', 'quant_id', 'move_id', 'Moves', help='Moves that operate(d) on this quant'),
309         'company_id': fields.many2one('res.company', 'Company', help="The company to which the quants belong", required=True, readonly=True, select=True),
310         'inventory_value': fields.function(_calc_inventory_value, string="Inventory Value", type='float', readonly=True),
311
312         # Used for negative quants to reconcile after compensated by a new positive one
313         'propagated_from_id': fields.many2one('stock.quant', 'Linked Quant', help='The negative quant this is coming from', readonly=True, select=True),
314         'negative_move_id': fields.many2one('stock.move', 'Move Negative Quant', help='If this is a negative quant, this will be the move that caused this negative quant.', readonly=True),
315         'negative_dest_location_id': fields.related('negative_move_id', 'location_dest_id', type='many2one', relation='stock.location', string="Negative Destination Location", readonly=True, 
316                                                     help="Technical field used to record the destination location of a move that created a negative quant"),
317     }
318
319     _defaults = {
320         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.quant', context=c),
321     }
322
323     def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
324         ''' Overwrite the read_group in order to sum the function field 'inventory_value' in group by'''
325         res = super(stock_quant, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
326         if 'inventory_value' in fields:
327             for line in res:
328                 if '__domain' in line:
329                     lines = self.search(cr, uid, line['__domain'], context=context)
330                     inv_value = 0.0
331                     for line2 in self.browse(cr, uid, lines, context=context):
332                         inv_value += line2.inventory_value
333                     line['inventory_value'] = inv_value
334         return res
335
336     def action_view_quant_history(self, cr, uid, ids, context=None):
337         '''
338         This function returns an action that display the history of the quant, which
339         mean all the stock moves that lead to this quant creation with this quant quantity.
340         '''
341         mod_obj = self.pool.get('ir.model.data')
342         act_obj = self.pool.get('ir.actions.act_window')
343
344         result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_move_form2')
345         id = result and result[1] or False
346         result = act_obj.read(cr, uid, [id], context={})[0]
347
348         move_ids = []
349         for quant in self.browse(cr, uid, ids, context=context):
350             move_ids += [move.id for move in quant.history_ids]
351
352         result['domain'] = "[('id','in',[" + ','.join(map(str, move_ids)) + "])]"
353         return result
354
355     def quants_reserve(self, cr, uid, quants, move, link=False, context=None):
356         '''This function reserves quants for the given move (and optionally given link). If the total of quantity reserved is enough, the move's state
357         is also set to 'assigned'
358
359         :param quants: list of tuple(quant browse record or None, qty to reserve). If None is given as first tuple element, the item will be ignored. Negative quants should not be received as argument
360         :param move: browse record
361         :param link: browse record (stock.move.operation.link)
362         '''
363         toreserve = []
364         reserved_availability = move.reserved_availability
365         #split quants if needed
366         for quant, qty in quants:
367             if qty <= 0.0 or (quant and quant.qty <= 0.0):
368                 raise osv.except_osv(_('Error!'), _('You can not reserve a negative quantity or a negative quant.'))
369             if not quant:
370                 continue
371             self._quant_split(cr, uid, quant, qty, context=context)
372             toreserve.append(quant.id)
373             reserved_availability += quant.qty
374         #reserve quants
375         if toreserve:
376             self.write(cr, SUPERUSER_ID, toreserve, {'reservation_id': move.id}, context=context)
377             #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
378             if move.picking_id:
379                 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
380         #check if move'state needs to be set as 'assigned'
381         if float_compare(reserved_availability, move.product_qty, precision_rounding=move.product_uom.rounding) == 0 and move.state in ('confirmed', 'waiting')  :
382             self.pool.get('stock.move').write(cr, uid, [move.id], {'state': 'assigned'}, context=context)
383         elif float_compare(reserved_availability, 0, precision_rounding=move.product_uom.rounding) > 0 and not move.partially_available:
384             self.pool.get('stock.move').write(cr, uid, [move.id], {'partially_available': True}, context=context)
385
386     def quants_move(self, cr, uid, quants, move, location_to, location_from=False, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, context=None):
387         """Moves all given stock.quant in the given destination location.  Unreserve from current move.
388         :param quants: list of tuple(browse record(stock.quant) or None, quantity to move)
389         :param move: browse record (stock.move)
390         :param location_to: browse record (stock.location) depicting where the quants have to be moved
391         :param location_from: optional browse record (stock.location) explaining where the quant has to be taken (may differ from the move source location in case a removal strategy applied). This parameter is only used to pass to _quant_create if a negative quant must be created
392         :param lot_id: ID of the lot that must be set on the quants to move
393         :param owner_id: ID of the partner that must own the quants to move
394         :param src_package_id: ID of the package that contains the quants to move
395         :param dest_package_id: ID of the package that must be set on the moved quant
396         """
397         quants_reconcile = []
398         to_move_quants = []
399         self._check_location(cr, uid, location_to, context=context)
400         for quant, qty in quants:
401             if not quant:
402                 #If quant is None, we will create a quant to move (and potentially a negative counterpart too)
403                 quant = self._quant_create(cr, uid, qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id, force_location_from=location_from, force_location_to=location_to, context=context)
404             else:
405                 self._quant_split(cr, uid, quant, qty, context=context)
406                 quant.refresh()
407                 to_move_quants.append(quant)
408             quants_reconcile.append(quant)
409         if to_move_quants:
410             to_recompute_move_ids = [x.reservation_id.id for x in to_move_quants if x.reservation_id and x.reservation_id.id != move.id]
411             self.move_quants_write(cr, uid, to_move_quants, move, location_to, dest_package_id, context=context)
412             self.pool.get('stock.move').recalculate_move_state(cr, uid, to_recompute_move_ids, context=context)
413         if location_to.usage == 'internal':
414             if self.search(cr, uid, [('product_id', '=', move.product_id.id), ('qty','<', 0)], limit=1, context=context):
415                 for quant in quants_reconcile:
416                     quant.refresh()
417                     self._quant_reconcile_negative(cr, uid, quant, move, context=context)
418
419     def move_quants_write(self, cr, uid, quants, move, location_dest_id, dest_package_id, context=None):
420         vals = {'location_id': location_dest_id.id,
421                 'history_ids': [(4, move.id)],
422                 'package_id': dest_package_id,
423                 'reservation_id': False}
424         self.write(cr, SUPERUSER_ID, [q.id for q in quants], vals, context=context)
425
426     def quants_get_prefered_domain(self, cr, uid, location, product, qty, domain=None, prefered_domain_list=[], restrict_lot_id=False, restrict_partner_id=False, context=None):
427         ''' This function tries to find quants in the given location for the given domain, by trying to first limit
428             the choice on the quants that match the first item of prefered_domain_list as well. But if the qty requested is not reached
429             it tries to find the remaining quantity by looping on the prefered_domain_list (tries with the second item and so on).
430             Make sure the quants aren't found twice => all the domains of prefered_domain_list should be orthogonal
431         '''
432         if domain is None:
433             domain = []
434         quants = [(None, qty)]
435         #don't look for quants in location that are of type production, supplier or inventory.
436         if location.usage in ['inventory', 'production', 'supplier']:
437             return quants
438         res_qty = qty
439         if not prefered_domain_list:
440             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)
441         for prefered_domain in prefered_domain_list:
442             res_qty_cmp = float_compare(res_qty, 0, precision_rounding=product.uom_id.rounding)
443             if res_qty_cmp > 0:
444                 #try to replace the last tuple (None, res_qty) with something that wasn't chosen at first because of the prefered order
445                 quants.pop()
446                 tmp_quants = self.quants_get(cr, uid, location, product, res_qty, domain=domain + prefered_domain, restrict_lot_id=restrict_lot_id, restrict_partner_id=restrict_partner_id, context=context)
447                 for quant in tmp_quants:
448                     if quant[0]:
449                         res_qty -= quant[1]
450                 quants += tmp_quants
451         return quants
452
453     def quants_get(self, cr, uid, location, product, qty, domain=None, restrict_lot_id=False, restrict_partner_id=False, context=None):
454         """
455         Use the removal strategies of product to search for the correct quants
456         If you inherit, put the super at the end of your method.
457
458         :location: browse record of the parent location where the quants have to be found
459         :product: browse record of the product to find
460         :qty in UoM of product
461         """
462         result = []
463         domain = domain or [('qty', '>', 0.0)]
464         if restrict_partner_id:
465             domain += [('owner_id', '=', restrict_partner_id)]
466         if restrict_lot_id:
467             domain += [('lot_id', '=', restrict_lot_id)]
468         if location:
469             removal_strategy = self.pool.get('stock.location').get_removal_strategy(cr, uid, location, product, context=context)
470             result += self.apply_removal_strategy(cr, uid, location, product, qty, domain, removal_strategy, context=context)
471         return result
472
473     def apply_removal_strategy(self, cr, uid, location, product, quantity, domain, removal_strategy, context=None):
474         if removal_strategy == 'fifo':
475             order = 'in_date, id'
476             return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
477         elif removal_strategy == 'lifo':
478             order = 'in_date desc, id desc'
479             return self._quants_get_order(cr, uid, location, product, quantity, domain, order, context=context)
480         raise osv.except_osv(_('Error!'), _('Removal strategy %s not implemented.' % (removal_strategy,)))
481
482     def _quant_create(self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False,
483                       force_location_from=False, force_location_to=False, context=None):
484         '''Create a quant in the destination location and create a negative quant in the source location if it's an internal location.
485         '''
486         if context is None:
487             context = {}
488         price_unit = self.pool.get('stock.move').get_price_unit(cr, uid, move, context=context)
489         location = force_location_to or move.location_dest_id
490         vals = {
491             'product_id': move.product_id.id,
492             'location_id': location.id,
493             'qty': qty,
494             'cost': price_unit,
495             'history_ids': [(4, move.id)],
496             'in_date': datetime.now().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
497             'company_id': move.company_id.id,
498             'lot_id': lot_id,
499             'owner_id': owner_id,
500             'package_id': dest_package_id,
501         }
502
503         if move.location_id.usage == 'internal':
504             #if we were trying to move something from an internal location and reach here (quant creation),
505             #it means that a negative quant has to be created as well.
506             negative_vals = vals.copy()
507             negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id
508             negative_vals['qty'] = -qty
509             negative_vals['cost'] = price_unit
510             negative_vals['negative_move_id'] = move.id
511             negative_vals['package_id'] = src_package_id
512             negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context)
513             vals.update({'propagated_from_id': negative_quant_id})
514
515         #create the quant as superuser, because we want to restrict the creation of quant manually: we should always use this method to create quants
516         quant_id = self.create(cr, SUPERUSER_ID, vals, context=context)
517         return self.browse(cr, uid, quant_id, context=context)
518
519     def _quant_split(self, cr, uid, quant, qty, context=None):
520         context = context or {}
521
522         if (quant.qty > 0 and float_compare(quant.qty, qty, precision_rounding=quant.product_id.uom_id.rounding) <= 0)\
523                 or (quant.qty <= 0 and float_compare(quant.qty, qty, precision_rounding=quant.product_id.uom_id.rounding) >= 0) :
524                 #(quant.qty > 0 and quant.qty <= qty) or (quant.qty <= 0 and quant.qty >= qty):
525             return False
526         new_quant = self.copy(cr, SUPERUSER_ID, quant.id, default={'qty': quant.qty - qty, 'history_ids': [(4, x.id) for x in quant.history_ids]}, context=context)
527         self.write(cr, SUPERUSER_ID, quant.id, {'qty': qty}, context=context)
528         quant.refresh()
529         return self.browse(cr, uid, new_quant, context=context)
530
531     def _get_latest_move(self, cr, uid, quant, context=None):
532         move = False
533         for m in quant.history_ids:
534             if not move or m.date > move.date:
535                 move = m
536         return move
537
538     @api.cr_uid_ids_context
539     def _quants_merge(self, cr, uid, solved_quant_ids, solving_quant, context=None):
540         path = []
541         for move in solving_quant.history_ids:
542             path.append((4, move.id))
543         self.write(cr, SUPERUSER_ID, solved_quant_ids, {'history_ids': path}, context=context)
544
545     def _quant_reconcile_negative(self, cr, uid, quant, move, context=None):
546         """
547             When new quant arrive in a location, try to reconcile it with
548             negative quants. If it's possible, apply the cost of the new
549             quant to the conter-part of the negative quant.
550         """
551         solving_quant = quant
552         dom = [('qty', '<', 0)]
553         prod = quant.product_id.id
554         if quant.lot_id:
555             dom += [('lot_id', '=', quant.lot_id.id)]
556         dom += [('owner_id', '=', quant.owner_id.id)]
557         dom += [('package_id', '=', quant.package_id.id)]
558         dom += [('id', '!=', quant.propagated_from_id.id)]
559         quants = self.quants_get(cr, uid, quant.location_id, quant.product_id, quant.qty, dom, context=context)
560         product_uom_rounding = quant.product_id.uom_id.rounding
561         for quant_neg, qty in quants:
562             if not quant_neg or not solving_quant:
563                 continue
564             to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id)], context=context)
565             if not to_solve_quant_ids:
566                 continue
567             solving_qty = qty
568             solved_quant_ids = []
569             for to_solve_quant in self.browse(cr, uid, to_solve_quant_ids, context=context):
570                 if float_compare(solving_qty, 0, precision_rounding=product_uom_rounding) <= 0:
571                     continue
572                 solved_quant_ids.append(to_solve_quant.id)
573                 self._quant_split(cr, uid, to_solve_quant, min(solving_qty, to_solve_quant.qty), context=context)
574                 solving_qty -= min(solving_qty, to_solve_quant.qty)
575             remaining_solving_quant = self._quant_split(cr, uid, solving_quant, qty, context=context)
576             remaining_neg_quant = self._quant_split(cr, uid, quant_neg, -qty, context=context)
577             #if the reconciliation was not complete, we need to link together the remaining parts
578             if remaining_neg_quant:
579                 remaining_to_solve_quant_ids = self.search(cr, uid, [('propagated_from_id', '=', quant_neg.id), ('id', 'not in', solved_quant_ids)], context=context)
580                 if remaining_to_solve_quant_ids:
581                     self.write(cr, SUPERUSER_ID, remaining_to_solve_quant_ids, {'propagated_from_id': remaining_neg_quant.id}, context=context)
582             if solving_quant.propagated_from_id:
583                 self.write(cr, uid, solved_quant_ids, {'propagated_from_id': solving_quant.propagated_from_id.id})
584             #delete the reconciled quants, as it is replaced by the solved quants
585             self.unlink(cr, SUPERUSER_ID, [quant_neg.id], context=context)
586             #price update + accounting entries adjustments
587             self._price_update(cr, uid, solved_quant_ids, solving_quant.cost, context=context)
588             #merge history (and cost?)
589             self._quants_merge(cr, uid, solved_quant_ids, solving_quant, context=context)
590             self.unlink(cr, SUPERUSER_ID, [solving_quant.id], context=context)
591             solving_quant = remaining_solving_quant
592
593
594
595     def _price_update(self, cr, uid, ids, newprice, context=None):
596         self.write(cr, SUPERUSER_ID, ids, {'cost': newprice}, context=context)
597
598     def quants_unreserve(self, cr, uid, move, context=None):
599         related_quants = [x.id for x in move.reserved_quant_ids]
600         if related_quants:
601             #if move has a picking_id, write on that picking that pack_operation might have changed and need to be recomputed
602             if move.picking_id:
603                 self.pool.get('stock.picking').write(cr, uid, [move.picking_id.id], {'recompute_pack_op': True}, context=context)
604             if move.partially_available:
605                 self.pool.get("stock.move").write(cr, uid, [move.id], {'partially_available': False}, context=context)
606             self.write(cr, SUPERUSER_ID, related_quants, {'reservation_id': False}, context=context)
607
608     def _quants_get_order(self, cr, uid, location, product, quantity, domain=[], orderby='in_date', context=None):
609         ''' Implementation of removal strategies
610             If it can not reserve, it will return a tuple (None, qty)
611         '''
612         if context is None:
613             context = {}
614         domain += location and [('location_id', 'child_of', location.id)] or []
615         domain += [('product_id', '=', product.id)]
616         if context.get('force_company'):
617             domain += [('company_id', '=', context.get('force_company'))]
618         else:
619             domain += [('company_id', '=', self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id)]
620         res = []
621         offset = 0
622         while float_compare(quantity, 0, precision_rounding=product.uom_id.rounding) > 0:
623             quants = self.search(cr, uid, domain, order=orderby, limit=10, offset=offset, context=context)
624             if not quants:
625                 res.append((None, quantity))
626                 break
627             for quant in self.browse(cr, uid, quants, context=context):
628                 qty_cmp = float_compare(quantity, abs(quant.qty), precision_rounding=product.uom_id.rounding)
629                 qty0_cmp = float_compare(quantity, 0.0, precision_rounding=product.uom_id.rounding)
630                 if qty_cmp >= 0:
631                     res += [(quant, abs(quant.qty))]
632                     quantity -= abs(quant.qty)
633                 elif qty0_cmp != 0:
634                     res += [(quant, quantity)]
635                     quantity = 0
636                     break
637             offset += 10
638         return res
639
640     def _check_location(self, cr, uid, location, context=None):
641         if location.usage == 'view':
642             raise osv.except_osv(_('Error'), _('You cannot move to a location of type view %s.') % (location.name))
643         return True
644
645 #----------------------------------------------------------
646 # Stock Picking
647 #----------------------------------------------------------
648
649 class stock_picking(osv.osv):
650     _name = "stock.picking"
651     _inherit = ['mail.thread']
652     _description = "Picking List"
653     _order = "priority desc, date asc, id desc"
654
655     def _set_min_date(self, cr, uid, id, field, value, arg, context=None):
656         move_obj = self.pool.get("stock.move")
657         if value:
658             move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
659             move_obj.write(cr, uid, move_ids, {'date_expected': value}, context=context)
660
661     def _set_priority(self, cr, uid, id, field, value, arg, context=None):
662         move_obj = self.pool.get("stock.move")
663         if value:
664             move_ids = [move.id for move in self.browse(cr, uid, id, context=context).move_lines]
665             move_obj.write(cr, uid, move_ids, {'priority': value}, context=context)
666
667     def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
668         """ Finds minimum and maximum dates for picking.
669         @return: Dictionary of values
670         """
671         res = {}
672         for id in ids:
673             res[id] = {'min_date': False, 'max_date': False, 'priority': '1'}
674         if not ids:
675             return res
676         cr.execute("""select
677                 picking_id,
678                 min(date_expected),
679                 max(date_expected),
680                 max(priority)
681             from
682                 stock_move
683             where
684                 picking_id IN %s
685             group by
686                 picking_id""", (tuple(ids),))
687         for pick, dt1, dt2, prio in cr.fetchall():
688             res[pick]['min_date'] = dt1
689             res[pick]['max_date'] = dt2
690             res[pick]['priority'] = prio
691         return res
692
693     def create(self, cr, user, vals, context=None):
694         context = context or {}
695         if ('name' not in vals) or (vals.get('name') in ('/', False)):
696             ptype_id = vals.get('picking_type_id', context.get('default_picking_type_id', False))
697             sequence_id = self.pool.get('stock.picking.type').browse(cr, user, ptype_id, context=context).sequence_id.id
698             vals['name'] = self.pool.get('ir.sequence').get_id(cr, user, sequence_id, 'id', context=context)
699         return super(stock_picking, self).create(cr, user, vals, context)
700
701     def _state_get(self, cr, uid, ids, field_name, arg, context=None):
702         '''The state of a picking depends on the state of its related stock.move
703             draft: the picking has no line or any one of the lines is draft
704             done, draft, cancel: all lines are done / draft / cancel
705             confirmed, waiting, assigned, partially_available depends on move_type (all at once or partial)
706         '''
707         res = {}
708         for pick in self.browse(cr, uid, ids, context=context):
709             if (not pick.move_lines) or any([x.state == 'draft' for x in pick.move_lines]):
710                 res[pick.id] = 'draft'
711                 continue
712             if all([x.state == 'cancel' for x in pick.move_lines]):
713                 res[pick.id] = 'cancel'
714                 continue
715             if all([x.state in ('cancel', 'done') for x in pick.move_lines]):
716                 res[pick.id] = 'done'
717                 continue
718
719             order = {'confirmed': 0, 'waiting': 1, 'assigned': 2}
720             order_inv = {0: 'confirmed', 1: 'waiting', 2: 'assigned'}
721             lst = [order[x.state] for x in pick.move_lines if x.state not in ('cancel', 'done')]
722             if pick.move_type == 'one':
723                 res[pick.id] = order_inv[min(lst)]
724             else:
725                 #we are in the case of partial delivery, so if all move are assigned, picking
726                 #should be assign too, else if one of the move is assigned, or partially available, picking should be
727                 #in partially available state, otherwise, picking is in waiting or confirmed state
728                 res[pick.id] = order_inv[max(lst)]
729                 if not all(x == 2 for x in lst):
730                     if any(x == 2 for x in lst):
731                         res[pick.id] = 'partially_available'
732                     else:
733                         #if all moves aren't assigned, check if we have one product partially available
734                         for move in pick.move_lines:
735                             if move.partially_available:
736                                 res[pick.id] = 'partially_available'
737                                 break
738         return res
739
740     def _get_pickings(self, cr, uid, ids, context=None):
741         res = set()
742         for move in self.browse(cr, uid, ids, context=context):
743             if move.picking_id:
744                 res.add(move.picking_id.id)
745         return list(res)
746
747     def _get_pack_operation_exist(self, cr, uid, ids, field_name, arg, context=None):
748         res = {}
749         for pick in self.browse(cr, uid, ids, context=context):
750             res[pick.id] = False
751             if pick.pack_operation_ids:
752                 res[pick.id] = True
753         return res
754
755     def _get_quant_reserved_exist(self, cr, uid, ids, field_name, arg, context=None):
756         res = {}
757         for pick in self.browse(cr, uid, ids, context=context):
758             res[pick.id] = False
759             for move in pick.move_lines:
760                 if move.reserved_quant_ids:
761                     res[pick.id] = True
762                     continue
763         return res
764
765     def check_group_lot(self, cr, uid, context=None):
766         """ This function will return true if we have the setting to use lots activated. """
767         return self.pool.get('res.users').has_group(cr, uid, 'stock.group_production_lot')
768
769     def check_group_pack(self, cr, uid, context=None):
770         """ This function will return true if we have the setting to use package activated. """
771         return self.pool.get('res.users').has_group(cr, uid, 'stock.group_tracking_lot')
772
773     def action_assign_owner(self, cr, uid, ids, context=None):
774         for picking in self.browse(cr, uid, ids, context=context):
775             packop_ids = [op.id for op in picking.pack_operation_ids]
776             self.pool.get('stock.pack.operation').write(cr, uid, packop_ids, {'owner_id': picking.owner_id.id}, context=context)
777
778     _columns = {
779         'name': fields.char('Reference', select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
780         'origin': fields.char('Source Document', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Reference of the document", select=True),
781         '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, copy=False),
782         'note': fields.text('Notes', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
783         '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"),
784         'state': fields.function(_state_get, type="selection", copy=False,
785             store={
786                 'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_type'], 20),
787                 'stock.move': (_get_pickings, ['state', 'picking_id', 'partially_available'], 20)},
788             selection=[
789                 ('draft', 'Draft'),
790                 ('cancel', 'Cancelled'),
791                 ('waiting', 'Waiting Another Operation'),
792                 ('confirmed', 'Waiting Availability'),
793                 ('partially_available', 'Partially Available'),
794                 ('assigned', 'Ready to Transfer'),
795                 ('done', 'Transferred'),
796                 ], string='Status', readonly=True, select=True, track_visibility='onchange',
797             help="""
798                 * Draft: not confirmed yet and will not be scheduled until confirmed\n
799                 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
800                 * Waiting Availability: still waiting for the availability of products\n
801                 * Partially Available: some products are available and reserved\n
802                 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
803                 * Transferred: has been processed, can't be modified or cancelled anymore\n
804                 * Cancelled: has been cancelled, can't be confirmed anymore"""
805         ),
806         'priority': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_priority, type='selection', selection=procurement.PROCUREMENT_PRIORITIES, string='Priority',
807                                     store={'stock.move': (_get_pickings, ['priority', 'picking_id'], 20)}, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, select=1, help="Priority for this picking. Setting manually a value here would set it as priority for all the moves",
808                                     track_visibility='onchange', required=True),
809         'min_date': fields.function(get_min_max_date, multi="min_max_date", fnct_inv=_set_min_date,
810                  store={'stock.move': (_get_pickings, ['date_expected', 'picking_id'], 20)}, type='datetime', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Scheduled Date', select=1, help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.", track_visibility='onchange'),
811         'max_date': fields.function(get_min_max_date, multi="min_max_date",
812                  store={'stock.move': (_get_pickings, ['date_expected', 'picking_id'], 20)}, type='datetime', string='Max. Expected Date', select=2, help="Scheduled time for the last part of the shipment to be processed"),
813         'date': fields.datetime('Creation Date', help="Creation Date, usually the time of the order", select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, track_visibility='onchange'),
814         'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=False),
815         'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, copy=True),
816         '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'),
817         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
818         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
819         'pack_operation_ids': fields.one2many('stock.pack.operation', 'picking_id', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, string='Related Packing Operations'),
820         'pack_operation_exist': fields.function(_get_pack_operation_exist, type='boolean', string='Pack Operation Exists?', help='technical field for attrs in view'),
821         'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True),
822         '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"),
823
824         'owner_id': fields.many2one('res.partner', 'Owner', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, help="Default Owner"),
825         # Used to search on pickings
826         'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
827         'recompute_pack_op': fields.boolean('Recompute pack operation?', help='True if reserved quants changed, which mean we might need to recompute the package operations', copy=False),
828         'location_id': fields.related('move_lines', 'location_id', type='many2one', relation='stock.location', string='Location', readonly=True),
829         'location_dest_id': fields.related('move_lines', 'location_dest_id', type='many2one', relation='stock.location', string='Destination Location', readonly=True),
830         'group_id': fields.related('move_lines', 'group_id', type='many2one', relation='procurement.group', string='Procurement Group', readonly=True,
831               store={
832                   'stock.picking': (lambda self, cr, uid, ids, ctx: ids, ['move_lines'], 10),
833                   'stock.move': (_get_pickings, ['group_id', 'picking_id'], 10),
834               }),
835     }
836
837     _defaults = {
838         'name': '/',
839         'state': 'draft',
840         'move_type': 'direct',
841         'priority': '1',  # normal
842         'date': fields.datetime.now,
843         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c),
844         'recompute_pack_op': True,
845     }
846     _sql_constraints = [
847         ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
848     ]
849
850     def do_print_picking(self, cr, uid, ids, context=None):
851         '''This function prints the picking list'''
852         context = dict(context or {}, active_ids=ids)
853         return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_picking', context=context)
854
855
856     def action_confirm(self, cr, uid, ids, context=None):
857         todo = []
858         todo_force_assign = []
859         for picking in self.browse(cr, uid, ids, context=context):
860             if picking.location_id.usage in ('supplier', 'inventory', 'production'):
861                 todo_force_assign.append(picking.id)
862             for r in picking.move_lines:
863                 if r.state == 'draft':
864                     todo.append(r.id)
865         if len(todo):
866             self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
867
868         if todo_force_assign:
869             self.force_assign(cr, uid, todo_force_assign, context=context)
870         return True
871
872     def action_assign(self, cr, uid, ids, context=None):
873         """ Check availability of picking moves.
874         This has the effect of changing the state and reserve quants on available moves, and may
875         also impact the state of the picking as it is computed based on move's states.
876         @return: True
877         """
878         for pick in self.browse(cr, uid, ids, context=context):
879             if pick.state == 'draft':
880                 self.action_confirm(cr, uid, [pick.id], context=context)
881             pick.refresh()
882             #skip the moves that don't need to be checked
883             move_ids = [x.id for x in pick.move_lines if x.state not in ('draft', 'cancel', 'done')]
884             if not move_ids:
885                 raise osv.except_osv(_('Warning!'), _('Nothing to check the availability for.'))
886             self.pool.get('stock.move').action_assign(cr, uid, move_ids, context=context)
887         return True
888
889     def force_assign(self, cr, uid, ids, context=None):
890         """ Changes state of picking to available if moves are confirmed or waiting.
891         @return: True
892         """
893         for pick in self.browse(cr, uid, ids, context=context):
894             move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed', 'waiting']]
895             self.pool.get('stock.move').force_assign(cr, uid, move_ids, context=context)
896         #pack_operation might have changed and need to be recomputed
897         self.write(cr, uid, ids, {'recompute_pack_op': True}, context=context)
898         return True
899
900     def action_cancel(self, cr, uid, ids, context=None):
901         for pick in self.browse(cr, uid, ids, context=context):
902             ids2 = [move.id for move in pick.move_lines]
903             self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
904         return True
905
906     def action_done(self, cr, uid, ids, context=None):
907         """Changes picking state to done by processing the Stock Moves of the Picking
908
909         Normally that happens when the button "Done" is pressed on a Picking view.
910         @return: True
911         """
912         for pick in self.browse(cr, uid, ids, context=context):
913             todo = []
914             for move in pick.move_lines:
915                 if move.state == 'draft':
916                     todo.extend(self.pool.get('stock.move').action_confirm(cr, uid, [move.id], context=context))
917                 elif move.state in ('assigned', 'confirmed'):
918                     todo.append(move.id)
919             if len(todo):
920                 self.pool.get('stock.move').action_done(cr, uid, todo, context=context)
921         return True
922
923     def unlink(self, cr, uid, ids, context=None):
924         #on picking deletion, cancel its move then unlink them too
925         move_obj = self.pool.get('stock.move')
926         context = context or {}
927         for pick in self.browse(cr, uid, ids, context=context):
928             move_ids = [move.id for move in pick.move_lines]
929             move_obj.action_cancel(cr, uid, move_ids, context=context)
930             move_obj.unlink(cr, uid, move_ids, context=context)
931         return super(stock_picking, self).unlink(cr, uid, ids, context=context)
932
933     def write(self, cr, uid, ids, vals, context=None):
934         res = super(stock_picking, self).write(cr, uid, ids, vals, context=context)
935         #if we changed the move lines or the pack operations, we need to recompute the remaining quantities of both
936         if 'move_lines' in vals or 'pack_operation_ids' in vals:
937             self.do_recompute_remaining_quantities(cr, uid, ids, context=context)
938         return res
939
940     def _create_backorder(self, cr, uid, picking, backorder_moves=[], context=None):
941         """ 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.
942         """
943         if not backorder_moves:
944             backorder_moves = picking.move_lines
945         backorder_move_ids = [x.id for x in backorder_moves if x.state not in ('done', 'cancel')]
946         if 'do_only_split' in context and context['do_only_split']:
947             backorder_move_ids = [x.id for x in backorder_moves if x.id not in context.get('split', [])]
948
949         if backorder_move_ids:
950             backorder_id = self.copy(cr, uid, picking.id, {
951                 'name': '/',
952                 'move_lines': [],
953                 'pack_operation_ids': [],
954                 'backorder_id': picking.id,
955             })
956             backorder = self.browse(cr, uid, backorder_id, context=context)
957             self.message_post(cr, uid, picking.id, body=_("Back order <em>%s</em> <b>created</b>.") % (backorder.name), context=context)
958             move_obj = self.pool.get("stock.move")
959             move_obj.write(cr, uid, backorder_move_ids, {'picking_id': backorder_id}, context=context)
960
961             self.write(cr, uid, [picking.id], {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
962             self.action_confirm(cr, uid, [backorder_id], context=context)
963             return backorder_id
964         return False
965
966     @api.cr_uid_ids_context
967     def recheck_availability(self, cr, uid, picking_ids, context=None):
968         self.action_assign(cr, uid, picking_ids, context=context)
969         self.do_prepare_partial(cr, uid, picking_ids, context=context)
970
971     def _get_top_level_packages(self, cr, uid, quants_suggested_locations, context=None):
972         """This method searches for the higher level packages that can be moved as a single operation, given a list of quants
973            to move and their suggested destination, and returns the list of matching packages.
974         """
975         # Try to find as much as possible top-level packages that can be moved
976         pack_obj = self.pool.get("stock.quant.package")
977         quant_obj = self.pool.get("stock.quant")
978         top_lvl_packages = set()
979         quants_to_compare = quants_suggested_locations.keys()
980         for pack in list(set([x.package_id for x in quants_suggested_locations.keys() if x and x.package_id])):
981             loop = True
982             test_pack = pack
983             good_pack = False
984             pack_destination = False
985             while loop:
986                 pack_quants = pack_obj.get_content(cr, uid, [test_pack.id], context=context)
987                 all_in = True
988                 for quant in quant_obj.browse(cr, uid, pack_quants, context=context):
989                     # If the quant is not in the quants to compare and not in the common location
990                     if not quant in quants_to_compare:
991                         all_in = False
992                         break
993                     else:
994                         #if putaway strat apply, the destination location of each quant may be different (and thus the package should not be taken as a single operation)
995                         if not pack_destination:
996                             pack_destination = quants_suggested_locations[quant]
997                         elif pack_destination != quants_suggested_locations[quant]:
998                             all_in = False
999                             break
1000                 if all_in:
1001                     good_pack = test_pack
1002                     if test_pack.parent_id:
1003                         test_pack = test_pack.parent_id
1004                     else:
1005                         #stop the loop when there's no parent package anymore
1006                         loop = False
1007                 else:
1008                     #stop the loop when the package test_pack is not totally reserved for moves of this picking
1009                     #(some quants may be reserved for other picking or not reserved at all)
1010                     loop = False
1011             if good_pack:
1012                 top_lvl_packages.add(good_pack)
1013         return list(top_lvl_packages)
1014
1015     def _prepare_pack_ops(self, cr, uid, picking, quants, forced_qties, context=None):
1016         """ returns a list of dict, ready to be used in create() of stock.pack.operation.
1017
1018         :param picking: browse record (stock.picking)
1019         :param quants: browse record list (stock.quant). List of quants associated to the picking
1020         :param forced_qties: dictionary showing for each product (keys) its corresponding quantity (value) that is not covered by the quants associated to the picking
1021         """
1022         def _picking_putaway_apply(product):
1023             location = False
1024             # Search putaway strategy
1025             if product_putaway_strats.get(product.id):
1026                 location = product_putaway_strats[product.id]
1027             else:
1028                 location = self.pool.get('stock.location').get_putaway_strategy(cr, uid, picking.location_dest_id, product, context=context)
1029                 product_putaway_strats[product.id] = location
1030             return location or picking.location_dest_id.id
1031
1032         pack_obj = self.pool.get("stock.quant.package")
1033         quant_obj = self.pool.get("stock.quant")
1034         vals = []
1035         qtys_grouped = {}
1036         #for each quant of the picking, find the suggested location
1037         quants_suggested_locations = {}
1038         product_putaway_strats = {}
1039         for quant in quants:
1040             if quant.qty <= 0:
1041                 continue
1042             suggested_location_id = _picking_putaway_apply(quant.product_id)
1043             quants_suggested_locations[quant] = suggested_location_id
1044
1045         #find the packages we can movei as a whole
1046         top_lvl_packages = self._get_top_level_packages(cr, uid, quants_suggested_locations, context=context)
1047         # and then create pack operations for the top-level packages found
1048         for pack in top_lvl_packages:
1049             pack_quant_ids = pack_obj.get_content(cr, uid, [pack.id], context=context)
1050             pack_quants = quant_obj.browse(cr, uid, pack_quant_ids, context=context)
1051             vals.append({
1052                     'picking_id': picking.id,
1053                     'package_id': pack.id,
1054                     'product_qty': 1.0,
1055                     'location_id': pack.location_id.id,
1056                     'location_dest_id': quants_suggested_locations[pack_quants[0]],
1057                 })
1058             #remove the quants inside the package so that they are excluded from the rest of the computation
1059             for quant in pack_quants:
1060                 del quants_suggested_locations[quant]
1061
1062         # Go through all remaining reserved quants and group by product, package, lot, owner, source location and dest location
1063         for quant, dest_location_id in quants_suggested_locations.items():
1064             key = (quant.product_id.id, quant.package_id.id, quant.lot_id.id, quant.owner_id.id, quant.location_id.id, dest_location_id)
1065             if qtys_grouped.get(key):
1066                 qtys_grouped[key] += quant.qty
1067             else:
1068                 qtys_grouped[key] = quant.qty
1069
1070         # Do the same for the forced quantities (in cases of force_assign or incomming shipment for example)
1071         for product, qty in forced_qties.items():
1072             if qty <= 0:
1073                 continue
1074             suggested_location_id = _picking_putaway_apply(product)
1075             key = (product.id, False, False, False, picking.location_id.id, suggested_location_id)
1076             if qtys_grouped.get(key):
1077                 qtys_grouped[key] += qty
1078             else:
1079                 qtys_grouped[key] = qty
1080
1081         # Create the necessary operations for the grouped quants and remaining qtys
1082         for key, qty in qtys_grouped.items():
1083             vals.append({
1084                 'picking_id': picking.id,
1085                 'product_qty': qty,
1086                 'product_id': key[0],
1087                 'package_id': key[1],
1088                 'lot_id': key[2],
1089                 'owner_id': key[3],
1090                 'location_id': key[4],
1091                 'location_dest_id': key[5],
1092                 'product_uom_id': self.pool.get("product.product").browse(cr, uid, key[0], context=context).uom_id.id,
1093             })
1094         return vals
1095
1096     @api.cr_uid_ids_context
1097     def open_barcode_interface(self, cr, uid, picking_ids, context=None):
1098         final_url="/barcode/web/#action=stock.ui&picking_id="+str(picking_ids[0])
1099         return {'type': 'ir.actions.act_url', 'url':final_url, 'target': 'self',}
1100
1101     @api.cr_uid_ids_context
1102     def do_partial_open_barcode(self, cr, uid, picking_ids, context=None):
1103         self.do_prepare_partial(cr, uid, picking_ids, context=context)
1104         return self.open_barcode_interface(cr, uid, picking_ids, context=context)
1105
1106     @api.cr_uid_ids_context
1107     def do_prepare_partial(self, cr, uid, picking_ids, context=None):
1108         context = context or {}
1109         pack_operation_obj = self.pool.get('stock.pack.operation')
1110         #used to avoid recomputing the remaining quantities at each new pack operation created
1111         ctx = context.copy()
1112         ctx['no_recompute'] = True
1113
1114         #get list of existing operations and delete them
1115         existing_package_ids = pack_operation_obj.search(cr, uid, [('picking_id', 'in', picking_ids)], context=context)
1116         if existing_package_ids:
1117             pack_operation_obj.unlink(cr, uid, existing_package_ids, context)
1118         for picking in self.browse(cr, uid, picking_ids, context=context):
1119             forced_qties = {}  # Quantity remaining after calculating reserved quants
1120             picking_quants = []
1121             #Calculate packages, reserved quants, qtys of this picking's moves
1122             for move in picking.move_lines:
1123                 if move.state not in ('assigned', 'confirmed'):
1124                     continue
1125                 move_quants = move.reserved_quant_ids
1126                 picking_quants += move_quants
1127                 forced_qty = (move.state == 'assigned') and move.product_qty - sum([x.qty for x in move_quants]) or 0
1128                 #if we used force_assign() on the move, or if the move is incoming, forced_qty > 0
1129                 if float_compare(forced_qty, 0, precision_rounding=move.product_id.uom_id.rounding) > 0:
1130                     if forced_qties.get(move.product_id):
1131                         forced_qties[move.product_id] += forced_qty
1132                     else:
1133                         forced_qties[move.product_id] = forced_qty
1134             for vals in self._prepare_pack_ops(cr, uid, picking, picking_quants, forced_qties, context=context):
1135                 pack_operation_obj.create(cr, uid, vals, context=ctx)
1136         #recompute the remaining quantities all at once
1137         self.do_recompute_remaining_quantities(cr, uid, picking_ids, context=context)
1138         self.write(cr, uid, picking_ids, {'recompute_pack_op': False}, context=context)
1139
1140     @api.cr_uid_ids_context
1141     def do_unreserve(self, cr, uid, picking_ids, context=None):
1142         """
1143           Will remove all quants for picking in picking_ids
1144         """
1145         moves_to_unreserve = []
1146         pack_line_to_unreserve = []
1147         for picking in self.browse(cr, uid, picking_ids, context=context):
1148             moves_to_unreserve += [m.id for m in picking.move_lines if m.state not in ('done', 'cancel')]
1149             pack_line_to_unreserve += [p.id for p in picking.pack_operation_ids]
1150         if moves_to_unreserve:
1151             if pack_line_to_unreserve:
1152                 self.pool.get('stock.pack.operation').unlink(cr, uid, pack_line_to_unreserve, context=context)
1153             self.pool.get('stock.move').do_unreserve(cr, uid, moves_to_unreserve, context=context)
1154
1155     def recompute_remaining_qty(self, cr, uid, picking, context=None):
1156         def _create_link_for_index(operation_id, index, product_id, qty_to_assign, quant_id=False):
1157             move_dict = prod2move_ids[product_id][index]
1158             qty_on_link = min(move_dict['remaining_qty'], qty_to_assign)
1159             self.pool.get('stock.move.operation.link').create(cr, uid, {'move_id': move_dict['move'].id, 'operation_id': operation_id, 'qty': qty_on_link, 'reserved_quant_id': quant_id}, context=context)
1160             if move_dict['remaining_qty'] == qty_on_link:
1161                 prod2move_ids[product_id].pop(index)
1162             else:
1163                 move_dict['remaining_qty'] -= qty_on_link
1164             return qty_on_link
1165
1166         def _create_link_for_quant(operation_id, quant, qty):
1167             """create a link for given operation and reserved move of given quant, for the max quantity possible, and returns this quantity"""
1168             if not quant.reservation_id.id:
1169                 return _create_link_for_product(operation_id, quant.product_id.id, qty)
1170             qty_on_link = 0
1171             for i in range(0, len(prod2move_ids[quant.product_id.id])):
1172                 if prod2move_ids[quant.product_id.id][i]['move'].id != quant.reservation_id.id:
1173                     continue
1174                 qty_on_link = _create_link_for_index(operation_id, i, quant.product_id.id, qty, quant_id=quant.id)
1175                 break
1176             return qty_on_link
1177
1178         def _create_link_for_product(operation_id, product_id, qty):
1179             '''method that creates the link between a given operation and move(s) of given product, for the given quantity.
1180             Returns True if it was possible to create links for the requested quantity (False if there was not enough quantity on stock moves)'''
1181             qty_to_assign = qty
1182             prod_obj = self.pool.get("product.product")
1183             product = prod_obj.browse(cr, uid, product_id)
1184             rounding = product.uom_id.rounding
1185             qtyassign_cmp = float_compare(qty_to_assign, 0.0, precision_rounding=rounding)
1186             if prod2move_ids.get(product_id):
1187                 while prod2move_ids[product_id] and qtyassign_cmp > 0:
1188                     qty_on_link = _create_link_for_index(operation_id, 0, product_id, qty_to_assign, quant_id=False)
1189                     qty_to_assign -= qty_on_link
1190                     qtyassign_cmp = float_compare(qty_to_assign, 0.0, precision_rounding=rounding)
1191             return qtyassign_cmp == 0
1192
1193         uom_obj = self.pool.get('product.uom')
1194         package_obj = self.pool.get('stock.quant.package')
1195         quant_obj = self.pool.get('stock.quant')
1196         quants_in_package_done = set()
1197         prod2move_ids = {}
1198         still_to_do = []
1199         #make a dictionary giving for each product, the moves and related quantity that can be used in operation links
1200         for move in picking.move_lines:
1201             if not prod2move_ids.get(move.product_id.id):
1202                 prod2move_ids[move.product_id.id] = [{'move': move, 'remaining_qty': move.product_qty}]
1203             else:
1204                 prod2move_ids[move.product_id.id].append({'move': move, 'remaining_qty': move.product_qty})
1205
1206         need_rereserve = False
1207         #sort the operations in order to give higher priority to those with a package, then a serial number
1208         operations = picking.pack_operation_ids
1209         operations = sorted(operations, key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
1210         #delete existing operations to start again from scratch
1211         cr.execute("DELETE FROM stock_move_operation_link WHERE operation_id in %s", (tuple([x.id for x in operations]),))
1212         #1) first, try to create links when quants can be identified without any doubt
1213         for ops in operations:
1214             #for each operation, create the links with the stock move by seeking on the matching reserved quants,
1215             #and deffer the operation if there is some ambiguity on the move to select
1216             if ops.package_id and not ops.product_id:
1217                 #entire package
1218                 quant_ids = package_obj.get_content(cr, uid, [ops.package_id.id], context=context)
1219                 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1220                     remaining_qty_on_quant = quant.qty
1221                     if quant.reservation_id:
1222                         #avoid quants being counted twice
1223                         quants_in_package_done.add(quant.id)
1224                         qty_on_link = _create_link_for_quant(ops.id, quant, quant.qty)
1225                         remaining_qty_on_quant -= qty_on_link
1226                     if remaining_qty_on_quant:
1227                         still_to_do.append((ops, quant.product_id.id, remaining_qty_on_quant))
1228                         need_rereserve = True
1229             elif ops.product_id.id:
1230                 #Check moves with same product
1231                 qty_to_assign = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, round=False, context=context)
1232                 for move_dict in prod2move_ids.get(ops.product_id.id, []):
1233                     move = move_dict['move']
1234                     for quant in move.reserved_quant_ids:
1235                         if not qty_to_assign > 0:
1236                             break
1237                         if quant.id in quants_in_package_done:
1238                             continue
1239
1240                         #check if the quant is matching the operation details
1241                         if ops.package_id:
1242                             flag = quant.package_id and bool(package_obj.search(cr, uid, [('id', 'child_of', [ops.package_id.id])], context=context)) or False
1243                         else:
1244                             flag = not quant.package_id.id
1245                         flag = flag and ((ops.lot_id and ops.lot_id.id == quant.lot_id.id) or not ops.lot_id)
1246                         flag = flag and (ops.owner_id.id == quant.owner_id.id)
1247                         if flag:
1248                             max_qty_on_link = min(quant.qty, qty_to_assign)
1249                             qty_on_link = _create_link_for_quant(ops.id, quant, max_qty_on_link)
1250                             qty_to_assign -= qty_on_link
1251                 qty_assign_cmp = float_compare(qty_to_assign, 0, precision_rounding=ops.product_id.uom_id.rounding)
1252                 if qty_assign_cmp > 0:
1253                     #qty reserved is less than qty put in operations. We need to create a link but it's deferred after we processed
1254                     #all the quants (because they leave no choice on their related move and needs to be processed with higher priority)
1255                     still_to_do += [(ops, ops.product_id.id, qty_to_assign)]
1256                     need_rereserve = True
1257
1258         #2) then, process the remaining part
1259         all_op_processed = True
1260         for ops, product_id, remaining_qty in still_to_do:
1261             all_op_processed = all_op_processed and _create_link_for_product(ops.id, product_id, remaining_qty)
1262         return (need_rereserve, all_op_processed)
1263
1264     def picking_recompute_remaining_quantities(self, cr, uid, picking, context=None):
1265         need_rereserve = False
1266         all_op_processed = True
1267         if picking.pack_operation_ids:
1268             need_rereserve, all_op_processed = self.recompute_remaining_qty(cr, uid, picking, context=context)
1269         return need_rereserve, all_op_processed
1270
1271     @api.cr_uid_ids_context
1272     def do_recompute_remaining_quantities(self, cr, uid, picking_ids, context=None):
1273         for picking in self.browse(cr, uid, picking_ids, context=context):
1274             if picking.pack_operation_ids:
1275                 self.recompute_remaining_qty(cr, uid, picking, context=context)
1276
1277     def _prepare_values_extra_move(self, cr, uid, op, product, remaining_qty, context=None):
1278         """
1279         Creates an extra move when there is no corresponding original move to be copied
1280         """
1281         picking = op.picking_id
1282         res = {
1283             'picking_id': picking.id,
1284             'location_id': picking.location_id.id,
1285             'location_dest_id': picking.location_dest_id.id,
1286             'product_id': product.id,
1287             'product_uom': product.uom_id.id,
1288             'product_uom_qty': remaining_qty,
1289             'name': _('Extra Move: ') + product.name,
1290             'state': 'draft',
1291             }
1292         return res
1293
1294     def _create_extra_moves(self, cr, uid, picking, context=None):
1295         '''This function creates move lines on a picking, at the time of do_transfer, based on
1296         unexpected product transfers (or exceeding quantities) found in the pack operations.
1297         '''
1298         move_obj = self.pool.get('stock.move')
1299         operation_obj = self.pool.get('stock.pack.operation')
1300         moves = []
1301         for op in picking.pack_operation_ids:
1302             for product_id, remaining_qty in operation_obj._get_remaining_prod_quantities(cr, uid, op, context=context).items():
1303                 if remaining_qty > 0:
1304                     product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
1305                     vals = self._prepare_values_extra_move(cr, uid, op, product, remaining_qty, context=context)
1306                     moves.append(move_obj.create(cr, uid, vals, context=context))
1307         if moves:
1308             move_obj.action_confirm(cr, uid, moves, context=context)
1309         return moves
1310
1311     def rereserve_pick(self, cr, uid, ids, context=None):
1312         """
1313         This can be used to provide a button that rereserves taking into account the existing pack operations
1314         """
1315         for pick in self.browse(cr, uid, ids, context=context):
1316             self.rereserve_quants(cr, uid, pick, move_ids = [x.id for x in pick.move_lines], context=context)
1317
1318     def rereserve_quants(self, cr, uid, picking, move_ids=[], context=None):
1319         """ Unreserve quants then try to reassign quants."""
1320         stock_move_obj = self.pool.get('stock.move')
1321         if not move_ids:
1322             self.do_unreserve(cr, uid, [picking.id], context=context)
1323             self.action_assign(cr, uid, [picking.id], context=context)
1324         else:
1325             stock_move_obj.do_unreserve(cr, uid, move_ids, context=context)
1326             stock_move_obj.action_assign(cr, uid, move_ids, context=context)
1327
1328     @api.cr_uid_ids_context
1329     def do_enter_transfer_details(self, cr, uid, picking, context=None):
1330         if not context:
1331             context = {}
1332
1333         context.update({
1334             'active_model': self._name,
1335             'active_ids': picking,
1336             'active_id': len(picking) and picking[0] or False
1337         })
1338
1339         created_id = self.pool['stock.transfer_details'].create(cr, uid, {'picking_id': len(picking) and picking[0] or False}, context)
1340         return self.pool['stock.transfer_details'].wizard_view(cr, uid, created_id, context)
1341
1342
1343     @api.cr_uid_ids_context
1344     def do_transfer(self, cr, uid, picking_ids, context=None):
1345         """
1346             If no pack operation, we do simple action_done of the picking
1347             Otherwise, do the pack operations
1348         """
1349         if not context:
1350             context = {}
1351         stock_move_obj = self.pool.get('stock.move')
1352         for picking in self.browse(cr, uid, picking_ids, context=context):
1353             if not picking.pack_operation_ids:
1354                 self.action_done(cr, uid, [picking.id], context=context)
1355                 continue
1356             else:
1357                 need_rereserve, all_op_processed = self.picking_recompute_remaining_quantities(cr, uid, picking, context=context)
1358                 #create extra moves in the picking (unexpected product moves coming from pack operations)
1359                 todo_move_ids = []
1360                 if not all_op_processed:
1361                     todo_move_ids += self._create_extra_moves(cr, uid, picking, context=context)
1362
1363                 picking.refresh()
1364                 #split move lines eventually
1365
1366                 toassign_move_ids = []
1367                 for move in picking.move_lines:
1368                     remaining_qty = move.remaining_qty
1369                     if move.state in ('done', 'cancel'):
1370                         #ignore stock moves cancelled or already done
1371                         continue
1372                     elif move.state == 'draft':
1373                         toassign_move_ids.append(move.id)
1374                     if float_compare(remaining_qty, 0,  precision_rounding = move.product_id.uom_id.rounding) == 0:
1375                         if move.state in ('draft', 'assigned', 'confirmed'):
1376                             todo_move_ids.append(move.id)
1377                     elif float_compare(remaining_qty,0, precision_rounding = move.product_id.uom_id.rounding) > 0 and \
1378                                 float_compare(remaining_qty, move.product_qty, precision_rounding = move.product_id.uom_id.rounding) < 0:
1379                         new_move = stock_move_obj.split(cr, uid, move, remaining_qty, context=context)
1380                         todo_move_ids.append(move.id)
1381                         #Assign move as it was assigned before
1382                         toassign_move_ids.append(new_move)
1383                 if need_rereserve or not all_op_processed: 
1384                     if not picking.location_id.usage in ("supplier", "production", "inventory"):
1385                         self.rereserve_quants(cr, uid, picking, move_ids=todo_move_ids, context=context)
1386                     self.do_recompute_remaining_quantities(cr, uid, [picking.id], context=context)
1387                 if todo_move_ids and not context.get('do_only_split'):
1388                     self.pool.get('stock.move').action_done(cr, uid, todo_move_ids, context=context)
1389                 elif context.get('do_only_split'):
1390                     context = dict(context, split=todo_move_ids)
1391             picking.refresh()
1392             self._create_backorder(cr, uid, picking, context=context)
1393             if toassign_move_ids:
1394                 stock_move_obj.action_assign(cr, uid, toassign_move_ids, context=context)
1395         return True
1396
1397     @api.cr_uid_ids_context
1398     def do_split(self, cr, uid, picking_ids, context=None):
1399         """ just split the picking (create a backorder) without making it 'done' """
1400         if context is None:
1401             context = {}
1402         ctx = context.copy()
1403         ctx['do_only_split'] = True
1404         return self.do_transfer(cr, uid, picking_ids, context=ctx)
1405
1406     def get_next_picking_for_ui(self, cr, uid, context=None):
1407         """ returns the next pickings to process. Used in the barcode scanner UI"""
1408         if context is None:
1409             context = {}
1410         domain = [('state', 'in', ('assigned', 'partially_available'))]
1411         if context.get('default_picking_type_id'):
1412             domain.append(('picking_type_id', '=', context['default_picking_type_id']))
1413         return self.search(cr, uid, domain, context=context)
1414
1415     def action_done_from_ui(self, cr, uid, picking_id, context=None):
1416         """ called when button 'done' is pushed in the barcode scanner UI """
1417         #write qty_done into field product_qty for every package_operation before doing the transfer
1418         pack_op_obj = self.pool.get('stock.pack.operation')
1419         for operation in self.browse(cr, uid, picking_id, context=context).pack_operation_ids:
1420             pack_op_obj.write(cr, uid, operation.id, {'product_qty': operation.qty_done}, context=context)
1421         self.do_transfer(cr, uid, [picking_id], context=context)
1422         #return id of next picking to work on
1423         return self.get_next_picking_for_ui(cr, uid, context=context)
1424
1425     @api.cr_uid_ids_context
1426     def action_pack(self, cr, uid, picking_ids, operation_filter_ids=None, context=None):
1427         """ Create a package with the current pack_operation_ids of the picking that aren't yet in a pack.
1428         Used in the barcode scanner UI and the normal interface as well. 
1429         operation_filter_ids is used by barcode scanner interface to specify a subset of operation to pack"""
1430         if operation_filter_ids == None:
1431             operation_filter_ids = []
1432         stock_operation_obj = self.pool.get('stock.pack.operation')
1433         package_obj = self.pool.get('stock.quant.package')
1434         stock_move_obj = self.pool.get('stock.move')
1435         for picking_id in picking_ids:
1436             operation_search_domain = [('picking_id', '=', picking_id), ('result_package_id', '=', False)]
1437             if operation_filter_ids != []:
1438                 operation_search_domain.append(('id', 'in', operation_filter_ids))
1439             operation_ids = stock_operation_obj.search(cr, uid, operation_search_domain, context=context)
1440             pack_operation_ids = []
1441             if operation_ids:
1442                 for operation in stock_operation_obj.browse(cr, uid, operation_ids, context=context):
1443                     #If we haven't done all qty in operation, we have to split into 2 operation
1444                     op = operation
1445                     if (operation.qty_done < operation.product_qty):
1446                         new_operation = stock_operation_obj.copy(cr, uid, operation.id, {'product_qty': operation.qty_done,'qty_done': operation.qty_done}, context=context)
1447                         stock_operation_obj.write(cr, uid, operation.id, {'product_qty': operation.product_qty - operation.qty_done,'qty_done': 0, 'lot_id': False}, context=context)
1448                         op = stock_operation_obj.browse(cr, uid, new_operation, context=context)
1449                     pack_operation_ids.append(op.id)
1450                     if op.product_id and op.location_id and op.location_dest_id:
1451                         stock_move_obj.check_tracking_product(cr, uid, op.product_id, op.lot_id.id, op.location_id, op.location_dest_id, context=context)
1452                 package_id = package_obj.create(cr, uid, {}, context=context)
1453                 stock_operation_obj.write(cr, uid, pack_operation_ids, {'result_package_id': package_id}, context=context)
1454         return True
1455
1456     def process_product_id_from_ui(self, cr, uid, picking_id, product_id, op_id, increment=True, context=None):
1457         return self.pool.get('stock.pack.operation')._search_and_increment(cr, uid, picking_id, [('product_id', '=', product_id),('id', '=', op_id)], increment=increment, context=context)
1458
1459     def process_barcode_from_ui(self, cr, uid, picking_id, barcode_str, visible_op_ids, context=None):
1460         '''This function is called each time there barcode scanner reads an input'''
1461         lot_obj = self.pool.get('stock.production.lot')
1462         package_obj = self.pool.get('stock.quant.package')
1463         product_obj = self.pool.get('product.product')
1464         stock_operation_obj = self.pool.get('stock.pack.operation')
1465         stock_location_obj = self.pool.get('stock.location')
1466         answer = {'filter_loc': False, 'operation_id': False}
1467         #check if the barcode correspond to a location
1468         matching_location_ids = stock_location_obj.search(cr, uid, [('loc_barcode', '=', barcode_str)], context=context)
1469         if matching_location_ids:
1470             #if we have a location, return immediatly with the location name
1471             location = stock_location_obj.browse(cr, uid, matching_location_ids[0], context=None)
1472             answer['filter_loc'] = stock_location_obj._name_get(cr, uid, location, context=None)
1473             answer['filter_loc_id'] = matching_location_ids[0]
1474             return answer
1475         #check if the barcode correspond to a product
1476         matching_product_ids = product_obj.search(cr, uid, ['|', ('ean13', '=', barcode_str), ('default_code', '=', barcode_str)], context=context)
1477         if matching_product_ids:
1478             op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', matching_product_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1479             answer['operation_id'] = op_id
1480             return answer
1481         #check if the barcode correspond to a lot
1482         matching_lot_ids = lot_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1483         if matching_lot_ids:
1484             lot = lot_obj.browse(cr, uid, matching_lot_ids[0], context=context)
1485             op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('product_id', '=', lot.product_id.id), ('lot_id', '=', lot.id)], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1486             answer['operation_id'] = op_id
1487             return answer
1488         #check if the barcode correspond to a package
1489         matching_package_ids = package_obj.search(cr, uid, [('name', '=', barcode_str)], context=context)
1490         if matching_package_ids:
1491             op_id = stock_operation_obj._search_and_increment(cr, uid, picking_id, [('package_id', '=', matching_package_ids[0])], filter_visible=True, visible_op_ids=visible_op_ids, increment=True, context=context)
1492             answer['operation_id'] = op_id
1493             return answer
1494         return answer
1495
1496
1497 class stock_production_lot(osv.osv):
1498     _name = 'stock.production.lot'
1499     _inherit = ['mail.thread']
1500     _description = 'Lot/Serial'
1501     _columns = {
1502         'name': fields.char('Serial Number', required=True, help="Unique Serial Number"),
1503         'ref': fields.char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's serial number"),
1504         'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1505         'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
1506         'create_date': fields.datetime('Creation Date'),
1507     }
1508     _defaults = {
1509         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1510         'product_id': lambda x, y, z, c: c.get('product_id', False),
1511     }
1512     _sql_constraints = [
1513         ('name_ref_uniq', 'unique (name, ref, product_id)', 'The combination of serial number, internal reference and product must be unique !'),
1514     ]
1515
1516     def action_traceability(self, cr, uid, ids, context=None):
1517         """ It traces the information of lots
1518         @param self: The object pointer.
1519         @param cr: A database cursor
1520         @param uid: ID of the user currently logged in
1521         @param ids: List of IDs selected
1522         @param context: A standard dictionary
1523         @return: A dictionary of values
1524         """
1525         quant_obj = self.pool.get("stock.quant")
1526         quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
1527         moves = set()
1528         for quant in quant_obj.browse(cr, uid, quants, context=context):
1529             moves |= {move.id for move in quant.history_ids}
1530         if moves:
1531             return {
1532                 'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
1533                 'name': _('Traceability'),
1534                 'view_mode': 'tree,form',
1535                 'view_type': 'form',
1536                 'context': {'tree_view_ref': 'stock.view_move_tree'},
1537                 'res_model': 'stock.move',
1538                 'type': 'ir.actions.act_window',
1539                     }
1540         return False
1541
1542
1543 # ----------------------------------------------------
1544 # Move
1545 # ----------------------------------------------------
1546
1547 class stock_move(osv.osv):
1548     _name = "stock.move"
1549     _description = "Stock Move"
1550     _order = 'date_expected desc, id'
1551     _log_create = False
1552
1553     def get_price_unit(self, cr, uid, move, context=None):
1554         """ Returns the unit price to store on the quant """
1555         return move.price_unit or move.product_id.standard_price
1556
1557     def name_get(self, cr, uid, ids, context=None):
1558         res = []
1559         for line in self.browse(cr, uid, ids, context=context):
1560             name = line.location_id.name + ' > ' + line.location_dest_id.name
1561             if line.product_id.code:
1562                 name = line.product_id.code + ': ' + name
1563             if line.picking_id.origin:
1564                 name = line.picking_id.origin + '/ ' + name
1565             res.append((line.id, name))
1566         return res
1567
1568     def _quantity_normalize(self, cr, uid, ids, name, args, context=None):
1569         uom_obj = self.pool.get('product.uom')
1570         res = {}
1571         for m in self.browse(cr, uid, ids, context=context):
1572             res[m.id] = uom_obj._compute_qty_obj(cr, uid, m.product_uom, m.product_uom_qty, m.product_id.uom_id, round=False, context=context)
1573         return res
1574
1575     def _get_remaining_qty(self, cr, uid, ids, field_name, args, context=None):
1576         uom_obj = self.pool.get('product.uom')
1577         res = {}
1578         for move in self.browse(cr, uid, ids, context=context):
1579             qty = move.product_qty
1580             for record in move.linked_move_operation_ids:
1581                 qty -= record.qty
1582             #converting the remaining quantity in the move UoM
1583             res[move.id] = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom, round=False, context=context)
1584         return res
1585
1586     def _get_lot_ids(self, cr, uid, ids, field_name, args, context=None):
1587         res = dict.fromkeys(ids, False)
1588         for move in self.browse(cr, uid, ids, context=context):
1589             if move.state == 'done':
1590                 res[move.id] = [q.lot_id.id for q in move.quant_ids if q.lot_id]
1591             else:
1592                 res[move.id] = [q.lot_id.id for q in move.reserved_quant_ids if q.lot_id]
1593         return res
1594
1595     def _get_product_availability(self, cr, uid, ids, field_name, args, context=None):
1596         quant_obj = self.pool.get('stock.quant')
1597         res = dict.fromkeys(ids, False)
1598         for move in self.browse(cr, uid, ids, context=context):
1599             if move.state == 'done':
1600                 res[move.id] = move.product_qty
1601             else:
1602                 sublocation_ids = self.pool.get('stock.location').search(cr, uid, [('id', 'child_of', [move.location_id.id])], context=context)
1603                 quant_ids = quant_obj.search(cr, uid, [('location_id', 'in', sublocation_ids), ('product_id', '=', move.product_id.id), ('reservation_id', '=', False)], context=context)
1604                 availability = 0
1605                 for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
1606                     availability += quant.qty
1607                 res[move.id] = min(move.product_qty, availability)
1608         return res
1609
1610     def _get_string_qty_information(self, cr, uid, ids, field_name, args, context=None):
1611         settings_obj = self.pool.get('stock.config.settings')
1612         uom_obj = self.pool.get('product.uom')
1613         res = dict.fromkeys(ids, '')
1614         for move in self.browse(cr, uid, ids, context=context):
1615             if move.state in ('draft', 'done', 'cancel') or move.location_id.usage != 'internal':
1616                 res[move.id] = ''  # 'not applicable' or 'n/a' could work too
1617                 continue
1618             total_available = min(move.product_qty, move.reserved_availability + move.availability)
1619             total_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, total_available, move.product_uom, context=context)
1620             info = str(total_available)
1621             #look in the settings if we need to display the UoM name or not
1622             config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
1623             if config_ids:
1624                 stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
1625                 if stock_settings.group_uom:
1626                     info += ' ' + move.product_uom.name
1627             if move.reserved_availability:
1628                 if move.reserved_availability != total_available:
1629                     #some of the available quantity is assigned and some are available but not reserved
1630                     reserved_available = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, move.reserved_availability, move.product_uom, context=context)
1631                     info += _(' (%s reserved)') % str(reserved_available)
1632                 else:
1633                     #all available quantity is assigned
1634                     info += _(' (reserved)')
1635             res[move.id] = info
1636         return res
1637
1638     def _get_reserved_availability(self, cr, uid, ids, field_name, args, context=None):
1639         res = dict.fromkeys(ids, 0)
1640         for move in self.browse(cr, uid, ids, context=context):
1641             res[move.id] = sum([quant.qty for quant in move.reserved_quant_ids])
1642         return res
1643
1644     def _get_move(self, cr, uid, ids, context=None):
1645         res = set()
1646         for quant in self.browse(cr, uid, ids, context=context):
1647             if quant.reservation_id:
1648                 res.add(quant.reservation_id.id)
1649         return list(res)
1650
1651     def _get_move_ids(self, cr, uid, ids, context=None):
1652         res = []
1653         for picking in self.browse(cr, uid, ids, context=context):
1654             res += [x.id for x in picking.move_lines]
1655         return res
1656
1657     def _get_moves_from_prod(self, cr, uid, ids, context=None):
1658         if ids:
1659             return self.pool.get('stock.move').search(cr, uid, [('product_id', 'in', ids)], context=context)
1660         return []
1661
1662     def _set_product_qty(self, cr, uid, id, field, value, arg, context=None):
1663         """ The meaning of product_qty field changed lately and is now a functional field computing the quantity
1664             in the default product UoM. This code has been added to raise an error if a write is made given a value
1665             for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
1666             detect errors.
1667         """
1668         raise osv.except_osv(_('Programming Error!'), _('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.'))
1669
1670     _columns = {
1671         'name': fields.char('Description', required=True, select=True),
1672         'priority': fields.selection(procurement.PROCUREMENT_PRIORITIES, 'Priority'),
1673         'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1674         '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)]}),
1675         'date_expected': fields.datetime('Expected Date', states={'done': [('readonly', True)]}, required=True, select=True, help="Scheduled date for the processing of this move"),
1676         'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type', '<>', 'service')], states={'done': [('readonly', True)]}),
1677         'product_qty': fields.function(_quantity_normalize, fnct_inv=_set_product_qty, type='float', digits=0, store={
1678                 'stock.move': (lambda self, cr, uid, ids, ctx: ids, ['product_id', 'product_uom_qty', 'product_uom'], 20),
1679                 'product.product': (_get_moves_from_prod, ['uom_id'], 20),
1680             }, string='Quantity',
1681             help='Quantity in the default UoM of the product'),
1682         'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1683             required=True, states={'done': [('readonly', True)]},
1684             help="This is the quantity of products from an inventory "
1685                 "point of view. For moves in the state 'done', this is the "
1686                 "quantity of products that were actually moved. For other "
1687                 "moves, this is the quantity of product that is planned to "
1688                 "be moved. Lowering this quantity does not generate a "
1689                 "backorder. Changing this quantity on assigned moves affects "
1690                 "the product reservation, and should be done with care."
1691         ),
1692         'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, states={'done': [('readonly', True)]}),
1693         'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1694         'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1695
1696         'product_packaging': fields.many2one('product.packaging', 'Prefered Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1697
1698         '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."),
1699         '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."),
1700
1701         '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"),
1702
1703
1704         'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True, copy=False),
1705         'move_orig_ids': fields.one2many('stock.move', 'move_dest_id', 'Original Move', help="Optional: previous stock move when chaining them", select=True),
1706
1707         'picking_id': fields.many2one('stock.picking', 'Reference', select=True, states={'done': [('readonly', True)]}),
1708         'note': fields.text('Notes'),
1709         'state': fields.selection([('draft', 'New'),
1710                                    ('cancel', 'Cancelled'),
1711                                    ('waiting', 'Waiting Another Move'),
1712                                    ('confirmed', 'Waiting Availability'),
1713                                    ('assigned', 'Available'),
1714                                    ('done', 'Done'),
1715                                    ], 'Status', readonly=True, select=True, copy=False,
1716                  help= "* New: When the stock move is created and not yet confirmed.\n"\
1717                        "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1718                        "* 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"\
1719                        "* Available: When products are reserved, it is set to \'Available\'.\n"\
1720                        "* Done: When the shipment is processed, the state is \'Done\'."),
1721         'partially_available': fields.boolean('Partially Available', readonly=True, help="Checks if the move has some stock reserved", copy=False),
1722         '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
1723
1724         'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1725         'split_from': fields.many2one('stock.move', string="Move Split From", help="Technical field used to track the origin of a split move, which can be useful in case of debug", copy=False),
1726         'backorder_id': fields.related('picking_id', 'backorder_id', type='many2one', relation="stock.picking", string="Back Order of", select=True),
1727         'origin': fields.char("Source"),
1728         'procure_method': fields.selection([('make_to_stock', 'Default: Take From Stock'), ('make_to_order', 'Advanced: Apply Procurement Rules')], 'Supply Method', required=True, 
1729                                            help="""By default, the system will take from the stock in the source location and passively wait for availability. The other possibility allows you to directly create a procurement on the source location (and thus ignore its current stock) to gather products. If we want to chain moves and have this one to wait for the previous, this second option should be chosen."""),
1730
1731         # used for colors in tree views:
1732         'scrapped': fields.related('location_dest_id', 'scrap_location', type='boolean', relation='stock.location', string='Scrapped', readonly=True),
1733
1734         'quant_ids': fields.many2many('stock.quant', 'stock_quant_move_rel', 'move_id', 'quant_id', 'Moved Quants'),
1735         'reserved_quant_ids': fields.one2many('stock.quant', 'reservation_id', 'Reserved quants'),
1736         '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'),
1737         'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Quantity',
1738                                          digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]},),
1739         'procurement_id': fields.many2one('procurement.order', 'Procurement'),
1740         'group_id': fields.many2one('procurement.group', 'Procurement Group'),
1741         'rule_id': fields.many2one('procurement.rule', 'Procurement Rule', help='The pull rule that created this stock move'),
1742         'push_rule_id': fields.many2one('stock.location.path', 'Push Rule', help='The push rule that created this stock move'),
1743         'propagate': fields.boolean('Propagate cancel and split', help='If checked, when this move is cancelled, cancel the linked move too'),
1744         'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
1745         'inventory_id': fields.many2one('stock.inventory', 'Inventory'),
1746         'lot_ids': fields.function(_get_lot_ids, type='many2many', relation='stock.production.lot', string='Lots'),
1747         'origin_returned_move_id': fields.many2one('stock.move', 'Origin return move', help='move that created the return move', copy=False),
1748         'returned_move_ids': fields.one2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move'),
1749         'reserved_availability': fields.function(_get_reserved_availability, type='float', string='Quantity Reserved', readonly=True, help='Quantity that has already been reserved for this move'),
1750         'availability': fields.function(_get_product_availability, type='float', string='Quantity Available', readonly=True, help='Quantity in stock that can still be reserved for this move'),
1751         'string_availability_info': fields.function(_get_string_qty_information, type='text', string='Availability', readonly=True, help='Show various information on stock availability for this move'),
1752         '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'"),
1753         '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'"),
1754         '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"),
1755         '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)."),
1756     }
1757
1758     def _default_location_destination(self, cr, uid, context=None):
1759         context = context or {}
1760         if context.get('default_picking_type_id', False):
1761             pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1762             return pick_type.default_location_dest_id and pick_type.default_location_dest_id.id or False
1763         return False
1764
1765     def _default_location_source(self, cr, uid, context=None):
1766         context = context or {}
1767         if context.get('default_picking_type_id', False):
1768             pick_type = self.pool.get('stock.picking.type').browse(cr, uid, context['default_picking_type_id'], context=context)
1769             return pick_type.default_location_src_id and pick_type.default_location_src_id.id or False
1770         return False
1771
1772     def _default_destination_address(self, cr, uid, context=None):
1773         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1774         return user.company_id.partner_id.id
1775
1776     _defaults = {
1777         'location_id': _default_location_source,
1778         'location_dest_id': _default_location_destination,
1779         'partner_id': _default_destination_address,
1780         'state': 'draft',
1781         'priority': '1',
1782         'product_uom_qty': 1.0,
1783         'scrapped': False,
1784         'date': fields.datetime.now,
1785         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1786         'date_expected': fields.datetime.now,
1787         'procure_method': 'make_to_stock',
1788         'propagate': True,
1789         'partially_available': False,
1790     }
1791
1792     def _check_uom(self, cr, uid, ids, context=None):
1793         for move in self.browse(cr, uid, ids, context=context):
1794             if move.product_id.uom_id.category_id.id != move.product_uom.category_id.id:
1795                 return False
1796         return True
1797
1798     _constraints = [
1799         (_check_uom,
1800             '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.',
1801             ['product_uom']),
1802     ]
1803
1804     @api.cr_uid_ids_context
1805     def do_unreserve(self, cr, uid, move_ids, context=None):
1806         quant_obj = self.pool.get("stock.quant")
1807         for move in self.browse(cr, uid, move_ids, context=context):
1808             if move.state in ('done', 'cancel'):
1809                 raise osv.except_osv(_('Operation Forbidden!'), _('Cannot unreserve a done move'))
1810             quant_obj.quants_unreserve(cr, uid, move, context=context)
1811             if self.find_move_ancestors(cr, uid, move, context=context):
1812                 self.write(cr, uid, [move.id], {'state': 'waiting'}, context=context)
1813             else:
1814                 self.write(cr, uid, [move.id], {'state': 'confirmed'}, context=context)
1815
1816     def _prepare_procurement_from_move(self, cr, uid, move, context=None):
1817         origin = (move.group_id and (move.group_id.name + ":") or "") + (move.rule_id and move.rule_id.name or move.origin or "/")
1818         group_id = move.group_id and move.group_id.id or False
1819         if move.rule_id:
1820             if move.rule_id.group_propagation_option == 'fixed' and move.rule_id.group_id:
1821                 group_id = move.rule_id.group_id.id
1822             elif move.rule_id.group_propagation_option == 'none':
1823                 group_id = False
1824         return {
1825             'name': move.rule_id and move.rule_id.name or "/",
1826             'origin': origin,
1827             'company_id': move.company_id and move.company_id.id or False,
1828             'date_planned': move.date,
1829             'product_id': move.product_id.id,
1830             'product_qty': move.product_qty,
1831             'product_uom': move.product_uom.id,
1832             'product_uos_qty': (move.product_uos and move.product_uos_qty) or move.product_qty,
1833             'product_uos': (move.product_uos and move.product_uos.id) or move.product_uom.id,
1834             'location_id': move.location_id.id,
1835             'move_dest_id': move.id,
1836             'group_id': group_id,
1837             'route_ids': [(4, x.id) for x in move.route_ids],
1838             'warehouse_id': move.warehouse_id.id or (move.picking_type_id and move.picking_type_id.warehouse_id.id or False),
1839             'priority': move.priority,
1840         }
1841
1842     def _push_apply(self, cr, uid, moves, context=None):
1843         push_obj = self.pool.get("stock.location.path")
1844         for move in moves:
1845             #1) if the move is already chained, there is no need to check push rules
1846             #2) if the move is a returned move, we don't want to check push rules, as returning a returned move is the only decent way
1847             #   to receive goods without triggering the push rules again (which would duplicate chained operations)
1848             if not move.move_dest_id and not move.origin_returned_move_id:
1849                 domain = [('location_from_id', '=', move.location_dest_id.id)]
1850                 #priority goes to the route defined on the product and product category
1851                 route_ids = [x.id for x in move.product_id.route_ids + move.product_id.categ_id.total_route_ids]
1852                 rules = push_obj.search(cr, uid, domain + [('route_id', 'in', route_ids)], order='route_sequence, sequence', context=context)
1853                 if not rules:
1854                     #then we search on the warehouse if a rule can apply
1855                     wh_route_ids = []
1856                     if move.warehouse_id:
1857                         wh_route_ids = [x.id for x in move.warehouse_id.route_ids]
1858                     elif move.picking_type_id and move.picking_type_id.warehouse_id:
1859                         wh_route_ids = [x.id for x in move.picking_type_id.warehouse_id.route_ids]
1860                     if wh_route_ids:
1861                         rules = push_obj.search(cr, uid, domain + [('route_id', 'in', wh_route_ids)], order='route_sequence, sequence', context=context)
1862                     if not rules:
1863                         #if no specialized push rule has been found yet, we try to find a general one (without route)
1864                         rules = push_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)
1865                 if rules:
1866                     rule = push_obj.browse(cr, uid, rules[0], context=context)
1867                     push_obj._apply(cr, uid, rule, move, context=context)
1868         return True
1869
1870     def _create_procurement(self, cr, uid, move, context=None):
1871         """ This will create a procurement order """
1872         return self.pool.get("procurement.order").create(cr, uid, self._prepare_procurement_from_move(cr, uid, move, context=context))
1873
1874     def write(self, cr, uid, ids, vals, context=None):
1875         if context is None:
1876             context = {}
1877         if isinstance(ids, (int, long)):
1878             ids = [ids]
1879         # Check that we do not modify a stock.move which is done
1880         frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1881         for move in self.browse(cr, uid, ids, context=context):
1882             if move.state == 'done':
1883                 if frozen_fields.intersection(vals):
1884                     raise osv.except_osv(_('Operation Forbidden!'),
1885                         _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1886         propagated_changes_dict = {}
1887         #propagation of quantity change
1888         if vals.get('product_uom_qty'):
1889             propagated_changes_dict['product_uom_qty'] = vals['product_uom_qty']
1890         if vals.get('product_uom_id'):
1891             propagated_changes_dict['product_uom_id'] = vals['product_uom_id']
1892         #propagation of expected date:
1893         propagated_date_field = False
1894         if vals.get('date_expected'):
1895             #propagate any manual change of the expected date
1896             propagated_date_field = 'date_expected'
1897         elif (vals.get('state', '') == 'done' and vals.get('date')):
1898             #propagate also any delta observed when setting the move as done
1899             propagated_date_field = 'date'
1900
1901         if not context.get('do_not_propagate', False) and (propagated_date_field or propagated_changes_dict):
1902             #any propagation is (maybe) needed
1903             for move in self.browse(cr, uid, ids, context=context):
1904                 if move.move_dest_id and move.propagate:
1905                     if 'date_expected' in propagated_changes_dict:
1906                         propagated_changes_dict.pop('date_expected')
1907                     if propagated_date_field:
1908                         current_date = datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1909                         new_date = datetime.strptime(vals.get(propagated_date_field), DEFAULT_SERVER_DATETIME_FORMAT)
1910                         delta = new_date - current_date
1911                         if abs(delta.days) >= move.company_id.propagation_minimum_delta:
1912                             old_move_date = datetime.strptime(move.move_dest_id.date_expected, DEFAULT_SERVER_DATETIME_FORMAT)
1913                             new_move_date = (old_move_date + relativedelta.relativedelta(days=delta.days or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
1914                             propagated_changes_dict['date_expected'] = new_move_date
1915                     #For pushed moves as well as for pulled moves, propagate by recursive call of write().
1916                     #Note that, for pulled moves we intentionally don't propagate on the procurement.
1917                     if propagated_changes_dict:
1918                         self.write(cr, uid, [move.move_dest_id.id], propagated_changes_dict, context=context)
1919         return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1920
1921     def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1922         """ On change of product quantity finds UoM and UoS quantities
1923         @param product_id: Product id
1924         @param product_qty: Changed Quantity of product
1925         @param product_uom: Unit of measure of product
1926         @param product_uos: Unit of sale of product
1927         @return: Dictionary of values
1928         """
1929         result = {
1930             'product_uos_qty': 0.00
1931         }
1932         warning = {}
1933
1934         if (not product_id) or (product_qty <= 0.0):
1935             result['product_qty'] = 0.0
1936             return {'value': result}
1937
1938         product_obj = self.pool.get('product.product')
1939         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1940
1941         # Warn if the quantity was decreased
1942         if ids:
1943             for move in self.read(cr, uid, ids, ['product_qty']):
1944                 if product_qty < move['product_qty']:
1945                     warning.update({
1946                         'title': _('Information'),
1947                         'message': _("By changing this quantity here, you accept the "
1948                                 "new quantity as complete: Odoo will not "
1949                                 "automatically generate a back order.")})
1950                 break
1951
1952         if product_uos and product_uom and (product_uom != product_uos):
1953             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1954         else:
1955             result['product_uos_qty'] = product_qty
1956
1957         return {'value': result, 'warning': warning}
1958
1959     def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1960                           product_uos, product_uom):
1961         """ On change of product quantity finds UoM and UoS quantities
1962         @param product_id: Product id
1963         @param product_uos_qty: Changed UoS Quantity of product
1964         @param product_uom: Unit of measure of product
1965         @param product_uos: Unit of sale of product
1966         @return: Dictionary of values
1967         """
1968         result = {
1969             'product_uom_qty': 0.00
1970         }
1971
1972         if (not product_id) or (product_uos_qty <= 0.0):
1973             result['product_uos_qty'] = 0.0
1974             return {'value': result}
1975
1976         product_obj = self.pool.get('product.product')
1977         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1978
1979         # No warning if the quantity was decreased to avoid double warnings:
1980         # The clients should call onchange_quantity too anyway
1981
1982         if product_uos and product_uom and (product_uom != product_uos):
1983             result['product_uom_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1984         else:
1985             result['product_uom_qty'] = product_uos_qty
1986         return {'value': result}
1987
1988     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, partner_id=False):
1989         """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1990         @param prod_id: Changed Product id
1991         @param loc_id: Source location id
1992         @param loc_dest_id: Destination location id
1993         @param partner_id: Address id of partner
1994         @return: Dictionary of values
1995         """
1996         if not prod_id:
1997             return {}
1998         user = self.pool.get('res.users').browse(cr, uid, uid)
1999         lang = user and user.lang or False
2000         if partner_id:
2001             addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
2002             if addr_rec:
2003                 lang = addr_rec and addr_rec.lang or False
2004         ctx = {'lang': lang}
2005
2006         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
2007         uos_id = product.uos_id and product.uos_id.id or False
2008         result = {
2009             'name': product.partner_ref,
2010             'product_uom': product.uom_id.id,
2011             'product_uos': uos_id,
2012             'product_uom_qty': 1.00,
2013             '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'],
2014         }
2015         if loc_id:
2016             result['location_id'] = loc_id
2017         if loc_dest_id:
2018             result['location_dest_id'] = loc_dest_id
2019         return {'value': result}
2020
2021     @api.cr_uid_ids_context
2022     def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):
2023         """Assign a picking on the given move_ids, which is a list of move supposed to share the same procurement_group, location_from and location_to
2024         (and company). Those attributes are also given as parameters.
2025         """
2026         pick_obj = self.pool.get("stock.picking")
2027         picks = pick_obj.search(cr, uid, [
2028                 ('group_id', '=', procurement_group),
2029                 ('location_id', '=', location_from),
2030                 ('location_dest_id', '=', location_to),
2031                 ('state', 'in', ['draft', 'confirmed', 'waiting'])], context=context)
2032         if picks:
2033             pick = picks[0]
2034         else:
2035             move = self.browse(cr, uid, move_ids, context=context)[0]
2036             values = {
2037                 'origin': move.origin,
2038                 'company_id': move.company_id and move.company_id.id or False,
2039                 'move_type': move.group_id and move.group_id.move_type or 'direct',
2040                 'partner_id': move.partner_id.id or False,
2041                 'picking_type_id': move.picking_type_id and move.picking_type_id.id or False,
2042             }
2043             pick = pick_obj.create(cr, uid, values, context=context)
2044         return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)
2045
2046     def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
2047         """ On change of Scheduled Date gives a Move date.
2048         @param date_expected: Scheduled Date
2049         @param date: Move Date
2050         @return: Move Date
2051         """
2052         if not date_expected:
2053             date_expected = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
2054         return {'value': {'date': date_expected}}
2055
2056     def attribute_price(self, cr, uid, move, context=None):
2057         """
2058             Attribute price to move, important in inter-company moves or receipts with only one partner
2059         """
2060         if not move.price_unit:
2061             price = move.product_id.standard_price
2062             self.write(cr, uid, [move.id], {'price_unit': price})
2063
2064     def action_confirm(self, cr, uid, ids, context=None):
2065         """ Confirms stock move or put it in waiting if it's linked to another move.
2066         @return: List of ids.
2067         """
2068         if isinstance(ids, (int, long)):
2069             ids = [ids]
2070         states = {
2071             'confirmed': [],
2072             'waiting': []
2073         }
2074         to_assign = {}
2075         for move in self.browse(cr, uid, ids, context=context):
2076             self.attribute_price(cr, uid, move, context=context)
2077             state = 'confirmed'
2078             #if the move is preceeded, then it's waiting (if preceeding move is done, then action_assign has been called already and its state is already available)
2079             if move.move_orig_ids:
2080                 state = 'waiting'
2081             #if the move is split and some of the ancestor was preceeded, then it's waiting as well
2082             elif move.split_from:
2083                 move2 = move.split_from
2084                 while move2 and state != 'waiting':
2085                     if move2.move_orig_ids:
2086                         state = 'waiting'
2087                     move2 = move2.split_from
2088             states[state].append(move.id)
2089
2090             if not move.picking_id and move.picking_type_id:
2091                 key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
2092                 if key not in to_assign:
2093                     to_assign[key] = []
2094                 to_assign[key].append(move.id)
2095
2096         for move in self.browse(cr, uid, states['confirmed'], context=context):
2097             if move.procure_method == 'make_to_order':
2098                 self._create_procurement(cr, uid, move, context=context)
2099                 states['waiting'].append(move.id)
2100                 states['confirmed'].remove(move.id)
2101
2102         for state, write_ids in states.items():
2103             if len(write_ids):
2104                 self.write(cr, uid, write_ids, {'state': state})
2105         #assign picking in batch for all confirmed move that share the same details
2106         for key, move_ids in to_assign.items():
2107             procurement_group, location_from, location_to = key
2108             self._picking_assign(cr, uid, move_ids, procurement_group, location_from, location_to, context=context)
2109         moves = self.browse(cr, uid, ids, context=context)
2110         self._push_apply(cr, uid, moves, context=context)
2111         return ids
2112
2113     def force_assign(self, cr, uid, ids, context=None):
2114         """ Changes the state to assigned.
2115         @return: True
2116         """
2117         return self.write(cr, uid, ids, {'state': 'assigned'}, context=context)
2118
2119     def check_tracking_product(self, cr, uid, product, lot_id, location, location_dest, context=None):
2120         check = False
2121         if product.track_all and not location_dest.usage == 'inventory':
2122             check = True
2123         elif product.track_incoming and location.usage in ('supplier', 'transit', 'inventory') and location_dest.usage == 'internal':
2124             check = True
2125         elif product.track_outgoing and location_dest.usage in ('customer', 'transit') and location.usage == 'internal':
2126             check = True
2127         if check and not lot_id:
2128             raise osv.except_osv(_('Warning!'), _('You must assign a serial number for the product %s') % (product.name))
2129
2130
2131     def check_tracking(self, cr, uid, move, lot_id, context=None):
2132         """ Checks if serial number is assigned to stock move or not and raise an error if it had to.
2133         """
2134         self.check_tracking_product(cr, uid, move.product_id, lot_id, move.location_id, move.location_dest_id, context=context)
2135         
2136
2137     def action_assign(self, cr, uid, ids, context=None):
2138         """ Checks the product type and accordingly writes the state.
2139         """
2140         context = context or {}
2141         quant_obj = self.pool.get("stock.quant")
2142         to_assign_moves = []
2143         main_domain = {}
2144         todo_moves = []
2145         operations = set()
2146         for move in self.browse(cr, uid, ids, context=context):
2147             if move.state not in ('confirmed', 'waiting', 'assigned'):
2148                 continue
2149             if move.location_id.usage in ('supplier', 'inventory', 'production'):
2150                 to_assign_moves.append(move.id)
2151                 #in case the move is returned, we want to try to find quants before forcing the assignment
2152                 if not move.origin_returned_move_id:
2153                     continue
2154             if move.product_id.type == 'consu':
2155                 to_assign_moves.append(move.id)
2156                 continue
2157             else:
2158                 todo_moves.append(move)
2159
2160                 #we always keep the quants already assigned and try to find the remaining quantity on quants not assigned only
2161                 main_domain[move.id] = [('reservation_id', '=', False), ('qty', '>', 0)]
2162
2163                 #if the move is preceeded, restrict the choice of quants in the ones moved previously in original move
2164                 ancestors = self.find_move_ancestors(cr, uid, move, context=context)
2165                 if move.state == 'waiting' and not ancestors:
2166                     #if the waiting move hasn't yet any ancestor (PO/MO not confirmed yet), don't find any quant available in stock
2167                     main_domain[move.id] += [('id', '=', False)]
2168                 elif ancestors:
2169                     main_domain[move.id] += [('history_ids', 'in', ancestors)]
2170
2171                 #if the move is returned from another, restrict the choice of quants to the ones that follow the returned move
2172                 if move.origin_returned_move_id:
2173                     main_domain[move.id] += [('history_ids', 'in', move.origin_returned_move_id.id)]
2174                 for link in move.linked_move_operation_ids:
2175                     operations.add(link.operation_id)
2176         # Check all ops and sort them: we want to process first the packages, then operations with lot then the rest
2177         operations = list(operations)
2178         operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
2179         for ops in operations:
2180             #first try to find quants based on specific domains given by linked operations
2181             for record in ops.linked_move_operation_ids:
2182                 move = record.move_id
2183                 if move.id in main_domain:
2184                     domain = main_domain[move.id] + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2185                     qty = record.qty
2186                     if qty:
2187                         quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, qty, domain=domain, prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2188                         quant_obj.quants_reserve(cr, uid, quants, move, record, context=context)
2189         for move in todo_moves:
2190             if move.linked_move_operation_ids:
2191                 continue
2192             move.refresh()
2193             #then if the move isn't totally assigned, try to find quants without any specific domain
2194             if move.state != 'assigned':
2195                 qty_already_assigned = move.reserved_availability
2196                 qty = move.product_qty - qty_already_assigned
2197                 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain[move.id], prefered_domain_list=[], restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2198                 quant_obj.quants_reserve(cr, uid, quants, move, context=context)
2199
2200         #force assignation of consumable products and incoming from supplier/inventory/production
2201         if to_assign_moves:
2202             self.force_assign(cr, uid, to_assign_moves, context=context)
2203
2204     def action_cancel(self, cr, uid, ids, context=None):
2205         """ Cancels the moves and if all moves are cancelled it cancels the picking.
2206         @return: True
2207         """
2208         procurement_obj = self.pool.get('procurement.order')
2209         context = context or {}
2210         procs_to_check = []
2211         for move in self.browse(cr, uid, ids, context=context):
2212             if move.state == 'done':
2213                 raise osv.except_osv(_('Operation Forbidden!'),
2214                         _('You cannot cancel a stock move that has been set to \'Done\'.'))
2215             if move.reserved_quant_ids:
2216                 self.pool.get("stock.quant").quants_unreserve(cr, uid, move, context=context)
2217             if context.get('cancel_procurement'):
2218                 if move.propagate:
2219                     procurement_ids = procurement_obj.search(cr, uid, [('move_dest_id', '=', move.id)], context=context)
2220                     procurement_obj.cancel(cr, uid, procurement_ids, context=context)
2221             else:
2222                 if move.move_dest_id:
2223                     if move.propagate:
2224                         self.action_cancel(cr, uid, [move.move_dest_id.id], context=context)
2225                     elif move.move_dest_id.state == 'waiting':
2226                         #If waiting, the chain will be broken and we are not sure if we can still wait for it (=> could take from stock instead)
2227                         self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2228                 if move.procurement_id:
2229                     # Does the same as procurement check, only eliminating a refresh
2230                     procs_to_check.append(move.procurement_id.id)
2231                     
2232         res = self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2233         if procs_to_check:
2234             procurement_obj.check(cr, uid, procs_to_check, context=context)
2235         return res
2236
2237     def _check_package_from_moves(self, cr, uid, ids, context=None):
2238         pack_obj = self.pool.get("stock.quant.package")
2239         packs = set()
2240         for move in self.browse(cr, uid, ids, context=context):
2241             packs |= set([q.package_id for q in move.quant_ids if q.package_id and q.qty > 0])
2242         return pack_obj._check_location_constraint(cr, uid, list(packs), context=context)
2243
2244     def find_move_ancestors(self, cr, uid, move, context=None):
2245         '''Find the first level ancestors of given move '''
2246         ancestors = []
2247         move2 = move
2248         while move2:
2249             ancestors += [x.id for x in move2.move_orig_ids]
2250             #loop on the split_from to find the ancestor of split moves only if the move has not direct ancestor (priority goes to them)
2251             move2 = not move2.move_orig_ids and move2.split_from or False
2252         return ancestors
2253
2254     @api.cr_uid_ids_context
2255     def recalculate_move_state(self, cr, uid, move_ids, context=None):
2256         '''Recompute the state of moves given because their reserved quants were used to fulfill another operation'''
2257         for move in self.browse(cr, uid, move_ids, context=context):
2258             vals = {}
2259             reserved_quant_ids = move.reserved_quant_ids
2260             if len(reserved_quant_ids) > 0 and not move.partially_available:
2261                 vals['partially_available'] = True
2262             if len(reserved_quant_ids) == 0 and move.partially_available:
2263                 vals['partially_available'] = False
2264             if move.state == 'assigned':
2265                 if self.find_move_ancestors(cr, uid, move, context=context):
2266                     vals['state'] = 'waiting'
2267                 else:
2268                     vals['state'] = 'confirmed'
2269             if vals:
2270                 self.write(cr, uid, [move.id], vals, context=context)
2271
2272     def action_done(self, cr, uid, ids, context=None):
2273         """ Process completely the moves given as ids and if all moves are done, it will finish the picking.
2274         """
2275         context = context or {}
2276         picking_obj = self.pool.get("stock.picking")
2277         quant_obj = self.pool.get("stock.quant")
2278         todo = [move.id for move in self.browse(cr, uid, ids, context=context) if move.state == "draft"]
2279         if todo:
2280             ids = self.action_confirm(cr, uid, todo, context=context)
2281         pickings = set()
2282         procurement_ids = []
2283         #Search operations that are linked to the moves
2284         operations = set()
2285         move_qty = {}
2286         for move in self.browse(cr, uid, ids, context=context):
2287             move_qty[move.id] = move.product_qty
2288             for link in move.linked_move_operation_ids:
2289                 operations.add(link.operation_id)
2290
2291         #Sort operations according to entire packages first, then package + lot, package only, lot only
2292         operations = list(operations)
2293         operations.sort(key=lambda x: ((x.package_id and not x.product_id) and -4 or 0) + (x.package_id and -2 or 0) + (x.lot_id and -1 or 0))
2294
2295         for ops in operations:
2296             if ops.picking_id:
2297                 pickings.add(ops.picking_id.id)
2298             main_domain = [('qty', '>', 0)]
2299             for record in ops.linked_move_operation_ids:
2300                 move = record.move_id
2301                 self.check_tracking(cr, uid, move, not ops.product_id and ops.package_id.id or ops.lot_id.id, context=context)
2302                 prefered_domain = [('reservation_id', '=', move.id)]
2303                 fallback_domain = [('reservation_id', '=', False)]
2304                 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2305                 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2306                 dom = main_domain + self.pool.get('stock.move.operation.link').get_specific_domain(cr, uid, record, context=context)
2307                 quants = quant_obj.quants_get_prefered_domain(cr, uid, ops.location_id, move.product_id, record.qty, domain=dom, prefered_domain_list=prefered_domain_list,
2308                                                           restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2309                 if ops.result_package_id.id:
2310                     #if a result package is given, all quants go there
2311                     quant_dest_package_id = ops.result_package_id.id
2312                 elif ops.product_id and ops.package_id:
2313                     #if a package and a product is given, we will remove quants from the pack.
2314                     quant_dest_package_id = False
2315                 else:
2316                     #otherwise we keep the current pack of the quant, which may mean None
2317                     quant_dest_package_id = ops.package_id.id
2318                 quant_obj.quants_move(cr, uid, quants, move, ops.location_dest_id, location_from=ops.location_id, lot_id=ops.lot_id.id, owner_id=ops.owner_id.id, src_package_id=ops.package_id.id, dest_package_id=quant_dest_package_id, context=context)
2319                 # Handle pack in pack
2320                 if not ops.product_id and ops.package_id and ops.result_package_id.id != ops.package_id.parent_id.id:
2321                     self.pool.get('stock.quant.package').write(cr, SUPERUSER_ID, [ops.package_id.id], {'parent_id': ops.result_package_id.id}, context=context)
2322                 move_qty[move.id] -= record.qty
2323         #Check for remaining qtys and unreserve/check move_dest_id in
2324         move_dest_ids = set()
2325         for move in self.browse(cr, uid, ids, context=context):
2326             if move_qty[move.id] > 0:  # (=In case no pack operations in picking)
2327                 main_domain = [('qty', '>', 0)]
2328                 prefered_domain = [('reservation_id', '=', move.id)]
2329                 fallback_domain = [('reservation_id', '=', False)]
2330                 fallback_domain2 = ['&', ('reservation_id', '!=', move.id), ('reservation_id', '!=', False)]
2331                 prefered_domain_list = [prefered_domain] + [fallback_domain] + [fallback_domain2]
2332                 self.check_tracking(cr, uid, move, move.restrict_lot_id.id, context=context)
2333                 qty = move_qty[move.id]
2334                 quants = quant_obj.quants_get_prefered_domain(cr, uid, move.location_id, move.product_id, qty, domain=main_domain, prefered_domain_list=prefered_domain_list, restrict_lot_id=move.restrict_lot_id.id, restrict_partner_id=move.restrict_partner_id.id, context=context)
2335                 quant_obj.quants_move(cr, uid, quants, move, move.location_dest_id, lot_id=move.restrict_lot_id.id, owner_id=move.restrict_partner_id.id, context=context)
2336
2337             # If the move has a destination, add it to the list to reserve
2338             if move.move_dest_id and move.move_dest_id.state in ('waiting', 'confirmed'):
2339                 move_dest_ids.add(move.move_dest_id.id)
2340
2341             if move.procurement_id:
2342                 procurement_ids.append(move.procurement_id.id)
2343
2344             #unreserve the quants and make them available for other operations/moves
2345             quant_obj.quants_unreserve(cr, uid, move, context=context)
2346         # Check the packages have been placed in the correct locations
2347         self._check_package_from_moves(cr, uid, ids, context=context)
2348         #set the move as done
2349         self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2350         self.pool.get('procurement.order').check(cr, uid, procurement_ids, context=context)
2351         #assign destination moves
2352         if move_dest_ids:
2353             self.action_assign(cr, uid, list(move_dest_ids), context=context)
2354         #check picking state to set the date_done is needed
2355         done_picking = []
2356         for picking in picking_obj.browse(cr, uid, list(pickings), context=context):
2357             if picking.state == 'done' and not picking.date_done:
2358                 done_picking.append(picking.id)
2359         if done_picking:
2360             picking_obj.write(cr, uid, done_picking, {'date_done': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)
2361         return True
2362
2363     def unlink(self, cr, uid, ids, context=None):
2364         context = context or {}
2365         for move in self.browse(cr, uid, ids, context=context):
2366             if move.state not in ('draft', 'cancel'):
2367                 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2368         return super(stock_move, self).unlink(cr, uid, ids, context=context)
2369
2370     def action_scrap(self, cr, uid, ids, quantity, location_id, restrict_lot_id=False, restrict_partner_id=False, context=None):
2371         """ Move the scrap/damaged product into scrap location
2372         @param cr: the database cursor
2373         @param uid: the user id
2374         @param ids: ids of stock move object to be scrapped
2375         @param quantity : specify scrap qty
2376         @param location_id : specify scrap location
2377         @param context: context arguments
2378         @return: Scraped lines
2379         """
2380         #quantity should be given in MOVE UOM
2381         if quantity <= 0:
2382             raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2383         res = []
2384         for move in self.browse(cr, uid, ids, context=context):
2385             source_location = move.location_id
2386             if move.state == 'done':
2387                 source_location = move.location_dest_id
2388             #Previously used to prevent scraping from virtual location but not necessary anymore
2389             #if source_location.usage != 'internal':
2390                 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2391                 #raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2392             move_qty = move.product_qty
2393             uos_qty = quantity / move_qty * move.product_uos_qty
2394             default_val = {
2395                 'location_id': source_location.id,
2396                 'product_uom_qty': quantity,
2397                 'product_uos_qty': uos_qty,
2398                 'state': move.state,
2399                 'scrapped': True,
2400                 'location_dest_id': location_id,
2401                 'restrict_lot_id': restrict_lot_id,
2402                 'restrict_partner_id': restrict_partner_id,
2403             }
2404             new_move = self.copy(cr, uid, move.id, default_val)
2405
2406             res += [new_move]
2407             product_obj = self.pool.get('product.product')
2408             for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2409                 if move.picking_id:
2410                     uom = product.uom_id.name if product.uom_id else ''
2411                     message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2412                     move.picking_id.message_post(body=message)
2413
2414         self.action_done(cr, uid, res, context=context)
2415         return res
2416
2417     def split(self, cr, uid, move, qty, restrict_lot_id=False, restrict_partner_id=False, context=None):
2418         """ Splits qty from move move into a new move
2419         :param move: browse record
2420         :param qty: float. quantity to split (given in product UoM)
2421         :param restrict_lot_id: optional production lot that can be given in order to force the new move to restrict its choice of quants to this lot.
2422         :param restrict_partner_id: optional partner that can be given in order to force the new move to restrict its choice of quants to the ones belonging to this partner.
2423         :param context: dictionay. can contains the special key 'source_location_id' in order to force the source location when copying the move
2424
2425         returns the ID of the backorder move created
2426         """
2427         if move.state in ('done', 'cancel'):
2428             raise osv.except_osv(_('Error'), _('You cannot split a move done'))
2429         if move.state == 'draft':
2430             #we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
2431             #case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
2432             raise osv.except_osv(_('Error'), _('You cannot split a draft move. It needs to be confirmed first.'))
2433
2434         if move.product_qty <= qty or qty == 0:
2435             return move.id
2436
2437         uom_obj = self.pool.get('product.uom')
2438         context = context or {}
2439
2440         uom_qty = uom_obj._compute_qty_obj(cr, uid, move.product_id.uom_id, qty, move.product_uom)
2441         uos_qty = uom_qty * move.product_uos_qty / move.product_uom_qty
2442
2443         defaults = {
2444             'product_uom_qty': uom_qty,
2445             'product_uos_qty': uos_qty,
2446             'procure_method': 'make_to_stock',
2447             'restrict_lot_id': restrict_lot_id,
2448             'restrict_partner_id': restrict_partner_id,
2449             'split_from': move.id,
2450             'procurement_id': move.procurement_id.id,
2451             'move_dest_id': move.move_dest_id.id,
2452         }
2453         if context.get('source_location_id'):
2454             defaults['location_id'] = context['source_location_id']
2455         new_move = self.copy(cr, uid, move.id, defaults)
2456
2457         ctx = context.copy()
2458         ctx['do_not_propagate'] = True
2459         self.write(cr, uid, [move.id], {
2460             'product_uom_qty': move.product_uom_qty - uom_qty,
2461             'product_uos_qty': move.product_uos_qty - uos_qty,
2462         }, context=ctx)
2463
2464         if move.move_dest_id and move.propagate and move.move_dest_id.state not in ('done', 'cancel'):
2465             new_move_prop = self.split(cr, uid, move.move_dest_id, qty, context=context)
2466             self.write(cr, uid, [new_move], {'move_dest_id': new_move_prop}, context=context)
2467         #returning the first element of list returned by action_confirm is ok because we checked it wouldn't be exploded (and
2468         #thus the result of action_confirm should always be a list of 1 element length)
2469         return self.action_confirm(cr, uid, [new_move], context=context)[0]
2470
2471
2472     def get_code_from_locs(self, cr, uid, move, location_id=False, location_dest_id=False, context=None):
2473         """
2474         Returns the code the picking type should have.  This can easily be used
2475         to check if a move is internal or not
2476         move, location_id and location_dest_id are browse records
2477         """
2478         code = 'internal'
2479         src_loc = location_id or move.location_id
2480         dest_loc = location_dest_id or move.location_dest_id
2481         if src_loc.usage == 'internal' and dest_loc.usage != 'internal':
2482             code = 'outgoing'
2483         if src_loc.usage != 'internal' and dest_loc.usage == 'internal':
2484             code = 'incoming'
2485         return code
2486
2487
2488 class stock_inventory(osv.osv):
2489     _name = "stock.inventory"
2490     _description = "Inventory"
2491
2492     def _get_move_ids_exist(self, cr, uid, ids, field_name, arg, context=None):
2493         res = {}
2494         for inv in self.browse(cr, uid, ids, context=context):
2495             res[inv.id] = False
2496             if inv.move_ids:
2497                 res[inv.id] = True
2498         return res
2499
2500     def _get_available_filters(self, cr, uid, context=None):
2501         """
2502            This function will return the list of filter allowed according to the options checked
2503            in 'Settings\Warehouse'.
2504
2505            :rtype: list of tuple
2506         """
2507         #default available choices
2508         res_filter = [('none', _('All products')), ('product', _('One product only'))]
2509         settings_obj = self.pool.get('stock.config.settings')
2510         config_ids = settings_obj.search(cr, uid, [], limit=1, order='id DESC', context=context)
2511         #If we don't have updated config until now, all fields are by default false and so should be not dipslayed
2512         if not config_ids:
2513             return res_filter
2514
2515         stock_settings = settings_obj.browse(cr, uid, config_ids[0], context=context)
2516         if stock_settings.group_stock_tracking_owner:
2517             res_filter.append(('owner', _('One owner only')))
2518             res_filter.append(('product_owner', _('One product for a specific owner')))
2519         if stock_settings.group_stock_tracking_lot:
2520             res_filter.append(('lot', _('One Lot/Serial Number')))
2521         if stock_settings.group_stock_packaging:
2522             res_filter.append(('pack', _('A Pack')))
2523         return res_filter
2524
2525     def _get_total_qty(self, cr, uid, ids, field_name, args, context=None):
2526         res = {}
2527         for inv in self.browse(cr, uid, ids, context=context):
2528             res[inv.id] = sum([x.product_qty for x in inv.line_ids])
2529         return res
2530
2531     INVENTORY_STATE_SELECTION = [
2532         ('draft', 'Draft'),
2533         ('cancel', 'Cancelled'),
2534         ('confirm', 'In Progress'),
2535         ('done', 'Validated'),
2536     ]
2537
2538     _columns = {
2539         'name': fields.char('Inventory Reference', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Inventory Name."),
2540         'date': fields.datetime('Inventory Date', required=True, readonly=True, help="The date that will be used for the stock level check of the products and the validation of the stock move related to this inventory."),
2541         'line_ids': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=False, states={'done': [('readonly', True)]}, help="Inventory Lines.", copy=True),
2542         'move_ids': fields.one2many('stock.move', 'inventory_id', 'Created Moves', help="Inventory Moves.", states={'done': [('readonly', True)]}),
2543         'state': fields.selection(INVENTORY_STATE_SELECTION, 'Status', readonly=True, select=True, copy=False),
2544         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft': [('readonly', False)]}),
2545         'location_id': fields.many2one('stock.location', 'Inventoried Location', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2546         'product_id': fields.many2one('product.product', 'Inventoried Product', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Product to focus your inventory on a particular Product."),
2547         'package_id': fields.many2one('stock.quant.package', 'Inventoried Pack', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Pack to focus your inventory on a particular Pack."),
2548         'partner_id': fields.many2one('res.partner', 'Inventoried Owner', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Owner to focus your inventory on a particular Owner."),
2549         'lot_id': fields.many2one('stock.production.lot', 'Inventoried Lot/Serial Number', readonly=True, states={'draft': [('readonly', False)]}, help="Specify Lot/Serial Number to focus your inventory on a particular Lot/Serial Number.", copy=False),
2550         'move_ids_exist': fields.function(_get_move_ids_exist, type='boolean', string=' Stock Move Exists?', help='technical field for attrs in view'),
2551         'filter': fields.selection(_get_available_filters, 'Selection Filter', required=True),
2552         'total_qty': fields.function(_get_total_qty, type="float"),
2553     }
2554
2555     def _default_stock_location(self, cr, uid, context=None):
2556         try:
2557             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0')
2558             return warehouse.lot_stock_id.id
2559         except:
2560             return False
2561
2562     _defaults = {
2563         'date': fields.datetime.now,
2564         'state': 'draft',
2565         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2566         'location_id': _default_stock_location,
2567         'filter': 'none',
2568     }
2569
2570     def reset_real_qty(self, cr, uid, ids, context=None):
2571         inventory = self.browse(cr, uid, ids[0], context=context)
2572         line_ids = [line.id for line in inventory.line_ids]
2573         self.pool.get('stock.inventory.line').write(cr, uid, line_ids, {'product_qty': 0})
2574         return True
2575
2576     def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2577         """ Creates a stock move from an inventory line
2578         @param inventory_line:
2579         @param move_vals:
2580         @return:
2581         """
2582         return self.pool.get('stock.move').create(cr, uid, move_vals)
2583
2584     def action_done(self, cr, uid, ids, context=None):
2585         """ Finish the inventory
2586         @return: True
2587         """
2588         for inv in self.browse(cr, uid, ids, context=context):
2589             for inventory_line in inv.line_ids:
2590                 if inventory_line.product_qty < 0 and inventory_line.product_qty != inventory_line.theoretical_qty:
2591                     raise osv.except_osv(_('Warning'), _('You cannot set a negative product quantity in an inventory line:\n\t%s - qty: %s' % (inventory_line.product_id.name, inventory_line.product_qty)))
2592             self.action_check(cr, uid, [inv.id], context=context)
2593             inv.refresh()
2594             self.write(cr, uid, [inv.id], {'state': 'done'}, context=context)
2595             self.post_inventory(cr, uid, inv, context=context)
2596         return True
2597
2598     def post_inventory(self, cr, uid, inv, context=None):
2599         #The inventory is posted as a single step which means quants cannot be moved from an internal location to another using an inventory
2600         #as they will be moved to inventory loss, and other quants will be created to the encoded quant location. This is a normal behavior
2601         #as quants cannot be reuse from inventory location (users can still manually move the products before/after the inventory if they want).
2602         move_obj = self.pool.get('stock.move')
2603         move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2604
2605     def _create_stock_move(self, cr, uid, inventory, todo_line, context=None):
2606         stock_move_obj = self.pool.get('stock.move')
2607         product_obj = self.pool.get('product.product')
2608         inventory_location_id = product_obj.browse(cr, uid, todo_line['product_id'], context=context).property_stock_inventory.id
2609         vals = {
2610             'name': _('INV:') + (inventory.name or ''),
2611             'product_id': todo_line['product_id'],
2612             'product_uom': todo_line['product_uom_id'],
2613             'date': inventory.date,
2614             'company_id': inventory.company_id.id,
2615             'inventory_id': inventory.id,
2616             'state': 'assigned',
2617             'restrict_lot_id': todo_line.get('prod_lot_id'),
2618             'restrict_partner_id': todo_line.get('partner_id'),
2619          }
2620
2621         if todo_line['product_qty'] < 0:
2622             #found more than expected
2623             vals['location_id'] = inventory_location_id
2624             vals['location_dest_id'] = todo_line['location_id']
2625             vals['product_uom_qty'] = -todo_line['product_qty']
2626         else:
2627             #found less than expected
2628             vals['location_id'] = todo_line['location_id']
2629             vals['location_dest_id'] = inventory_location_id
2630             vals['product_uom_qty'] = todo_line['product_qty']
2631         return stock_move_obj.create(cr, uid, vals, context=context)
2632
2633     def action_check(self, cr, uid, ids, context=None):
2634         """ Checks the inventory and computes the stock move to do
2635         @return: True
2636         """
2637         inventory_line_obj = self.pool.get('stock.inventory.line')
2638         stock_move_obj = self.pool.get('stock.move')
2639         for inventory in self.browse(cr, uid, ids, context=context):
2640             #first remove the existing stock moves linked to this inventory
2641             move_ids = [move.id for move in inventory.move_ids]
2642             stock_move_obj.unlink(cr, uid, move_ids, context=context)
2643             for line in inventory.line_ids:
2644                 #compare the checked quantities on inventory lines to the theorical one
2645                 inventory_line_obj._resolve_inventory_line(cr, uid, line, context=context)
2646
2647     def action_cancel_draft(self, cr, uid, ids, context=None):
2648         """ Cancels the stock move and change inventory state to draft.
2649         @return: True
2650         """
2651         for inv in self.browse(cr, uid, ids, context=context):
2652             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2653             self.write(cr, uid, [inv.id], {'state': 'draft'}, context=context)
2654         return True
2655
2656     def action_cancel_inventory(self, cr, uid, ids, context=None):
2657         self.action_cancel_draft(cr, uid, ids, context=context)
2658
2659     def prepare_inventory(self, cr, uid, ids, context=None):
2660         inventory_line_obj = self.pool.get('stock.inventory.line')
2661         for inventory in self.browse(cr, uid, ids, context=context):
2662             # If there are inventory lines already (e.g. from import), respect those and set their theoretical qty
2663             line_ids = [line.id for line in inventory.line_ids]
2664             if not line_ids:
2665                 #compute the inventory lines and create them
2666                 vals = self._get_inventory_lines(cr, uid, inventory, context=context)
2667                 for product_line in vals:
2668                     inventory_line_obj.create(cr, uid, product_line, context=context)
2669             else:
2670                 # On import calculate theoretical quantity
2671                 quant_obj = self.pool.get("stock.quant")
2672                 for line in inventory.line_ids:
2673                     dom = [('company_id', '=', line.company_id.id), ('location_id', 'child_of', line.location_id.id), ('lot_id', '=', line.prod_lot_id.id),
2674                         ('product_id','=', line.product_id.id), ('owner_id', '=', line.partner_id.id)]
2675                     if line.package_id:
2676                         dom += [('package_id', '=', line.package_id.id)]
2677                     quants = quant_obj.search(cr, uid, dom, context=context)
2678                     tot_qty = 0
2679                     for quant in quant_obj.browse(cr, uid, quants, context=context):
2680                         tot_qty += quant.qty
2681                     inventory_line_obj.write(cr, uid, [line.id], {'theoretical_qty': tot_qty}, context=context)
2682
2683         return self.write(cr, uid, ids, {'state': 'confirm', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
2684
2685     def _get_inventory_lines(self, cr, uid, inventory, context=None):
2686         location_obj = self.pool.get('stock.location')
2687         product_obj = self.pool.get('product.product')
2688         location_ids = location_obj.search(cr, uid, [('id', 'child_of', [inventory.location_id.id])], context=context)
2689         domain = ' location_id in %s'
2690         args = (tuple(location_ids),)
2691         if inventory.partner_id:
2692             domain += ' and owner_id = %s'
2693             args += (inventory.partner_id.id,)
2694         if inventory.lot_id:
2695             domain += ' and lot_id = %s'
2696             args += (inventory.lot_id.id,)
2697         if inventory.product_id:
2698             domain += ' and product_id = %s'
2699             args += (inventory.product_id.id,)
2700         if inventory.package_id:
2701             domain += ' and package_id = %s'
2702             args += (inventory.package_id.id,)
2703
2704         cr.execute('''
2705            SELECT product_id, sum(qty) as product_qty, location_id, lot_id as prod_lot_id, package_id, owner_id as partner_id
2706            FROM stock_quant WHERE''' + domain + '''
2707            GROUP BY product_id, location_id, lot_id, package_id, partner_id
2708         ''', args)
2709         vals = []
2710         for product_line in cr.dictfetchall():
2711             #replace the None the dictionary by False, because falsy values are tested later on
2712             for key, value in product_line.items():
2713                 if not value:
2714                     product_line[key] = False
2715             product_line['inventory_id'] = inventory.id
2716             product_line['theoretical_qty'] = product_line['product_qty']
2717             if product_line['product_id']:
2718                 product = product_obj.browse(cr, uid, product_line['product_id'], context=context)
2719                 product_line['product_uom_id'] = product.uom_id.id
2720             vals.append(product_line)
2721         return vals
2722
2723
2724 class stock_inventory_line(osv.osv):
2725     _name = "stock.inventory.line"
2726     _description = "Inventory Line"
2727     _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2728
2729     def _get_product_name_change(self, cr, uid, ids, context=None):
2730         return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2731
2732     def _get_location_change(self, cr, uid, ids, context=None):
2733         return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2734
2735     def _get_prodlot_change(self, cr, uid, ids, context=None):
2736         return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2737
2738     _columns = {
2739         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2740         'location_id': fields.many2one('stock.location', 'Location', required=True, select=True),
2741         'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2742         'package_id': fields.many2one('stock.quant.package', 'Pack', select=True),
2743         'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2744         'product_qty': fields.float('Checked Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2745         'company_id': fields.related('inventory_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, select=True, readonly=True),
2746         'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2747         'state': fields.related('inventory_id', 'state', type='char', string='Status', readonly=True),
2748         'theoretical_qty': fields.float('Theoretical Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), readonly=True),
2749         'partner_id': fields.many2one('res.partner', 'Owner'),
2750         'product_name': fields.related('product_id', 'name', type='char', string='Product Name', store={
2751                                                                                             'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2752                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2753         'product_code': fields.related('product_id', 'default_code', type='char', string='Product Code', store={
2754                                                                                             'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2755                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2756         'location_name': fields.related('location_id', 'complete_name', type='char', string='Location Name', store={
2757                                                                                             'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2758                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
2759         'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number Name', store={
2760                                                                                             'stock.production.lot': (_get_prodlot_change, ['name'], 20),
2761                                                                                             'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
2762     }
2763
2764     _defaults = {
2765         'product_qty': 1,
2766     }
2767
2768     def _resolve_inventory_line(self, cr, uid, inventory_line, context=None):
2769         stock_move_obj = self.pool.get('stock.move')
2770         diff = inventory_line.theoretical_qty - inventory_line.product_qty
2771         if not diff:
2772             return
2773         #each theorical_lines where difference between theoretical and checked quantities is not 0 is a line for which we need to create a stock move
2774         vals = {
2775             'name': _('INV:') + (inventory_line.inventory_id.name or ''),
2776             'product_id': inventory_line.product_id.id,
2777             'product_uom': inventory_line.product_uom_id.id,
2778             'date': inventory_line.inventory_id.date,
2779             'company_id': inventory_line.inventory_id.company_id.id,
2780             'inventory_id': inventory_line.inventory_id.id,
2781             'state': 'confirmed',
2782             'restrict_lot_id': inventory_line.prod_lot_id.id,
2783             'restrict_partner_id': inventory_line.partner_id.id,
2784          }
2785         inventory_location_id = inventory_line.product_id.property_stock_inventory.id
2786         if diff < 0:
2787             #found more than expected
2788             vals['location_id'] = inventory_location_id
2789             vals['location_dest_id'] = inventory_line.location_id.id
2790             vals['product_uom_qty'] = -diff
2791         else:
2792             #found less than expected
2793             vals['location_id'] = inventory_line.location_id.id
2794             vals['location_dest_id'] = inventory_location_id
2795             vals['product_uom_qty'] = diff
2796         return stock_move_obj.create(cr, uid, vals, context=context)
2797
2798     def restrict_change(self, cr, uid, ids, theoretical_qty, context=None):
2799         if ids and theoretical_qty:
2800             #if the user try to modify a line prepared by openerp, reject the change and display an error message explaining how he should do
2801             old_value = self.browse(cr, uid, ids[0], context=context)
2802             return {
2803                 'value': {
2804                     'product_id': old_value.product_id.id,
2805                     'product_uom_id': old_value.product_uom_id.id,
2806                     'location_id': old_value.location_id.id,
2807                     'prod_lot_id': old_value.prod_lot_id.id,
2808                     'package_id': old_value.package_id.id,
2809                     'partner_id': old_value.partner_id.id,
2810                     },
2811                 'warning': {
2812                     'title': _('Error'),
2813                     'message': _('You can only change the checked quantity of an existing inventory line. If you want modify a data, please set the checked quantity to 0 and create a new inventory line.')
2814                 }
2815             }
2816         return {}
2817
2818     def on_change_product_id(self, cr, uid, ids, product, uom, theoretical_qty, context=None):
2819         """ Changes UoM
2820         @param location_id: Location id
2821         @param product: Changed product_id
2822         @param uom: UoM product
2823         @return:  Dictionary of changed values
2824         """
2825         if ids and theoretical_qty:
2826             return self.restrict_change(cr, uid, ids, theoretical_qty, context=context)
2827         if not product:
2828             return {'value': {'product_uom_id': False}}
2829         obj_product = self.pool.get('product.product').browse(cr, uid, product, context=context)
2830         return {'value': {'product_uom_id': uom or obj_product.uom_id.id}}
2831
2832
2833 #----------------------------------------------------------
2834 # Stock Warehouse
2835 #----------------------------------------------------------
2836 class stock_warehouse(osv.osv):
2837     _name = "stock.warehouse"
2838     _description = "Warehouse"
2839
2840     _columns = {
2841         'name': fields.char('Warehouse Name', required=True, select=True),
2842         'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, select=True),
2843         'partner_id': fields.many2one('res.partner', 'Address'),
2844         'view_location_id': fields.many2one('stock.location', 'View Location', required=True, domain=[('usage', '=', 'view')]),
2845         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', domain=[('usage', '=', 'internal')], required=True),
2846         'code': fields.char('Short Name', size=5, required=True, help="Short name used to identify your warehouse"),
2847         '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'),
2848         'reception_steps': fields.selection([
2849             ('one_step', 'Receive goods directly in stock (1 step)'),
2850             ('two_steps', 'Unload in input location then go to stock (2 steps)'),
2851             ('three_steps', 'Unload in input location, go through a quality control before being admitted in stock (3 steps)')], 'Incoming Shipments', 
2852                                             help="Default incoming route to follow", required=True),
2853         'delivery_steps': fields.selection([
2854             ('ship_only', 'Ship directly from stock (Ship only)'),
2855             ('pick_ship', 'Bring goods to output location before shipping (Pick + Ship)'),
2856             ('pick_pack_ship', 'Make packages into a dedicated location, then bring them to the output location for shipping (Pick + Pack + Ship)')], 'Outgoing Shippings', 
2857                                            help="Default outgoing route to follow", required=True),
2858         'wh_input_stock_loc_id': fields.many2one('stock.location', 'Input Location'),
2859         'wh_qc_stock_loc_id': fields.many2one('stock.location', 'Quality Control Location'),
2860         'wh_output_stock_loc_id': fields.many2one('stock.location', 'Output Location'),
2861         'wh_pack_stock_loc_id': fields.many2one('stock.location', 'Packing Location'),
2862         'mto_pull_id': fields.many2one('procurement.rule', 'MTO rule'),
2863         'pick_type_id': fields.many2one('stock.picking.type', 'Pick Type'),
2864         'pack_type_id': fields.many2one('stock.picking.type', 'Pack Type'),
2865         'out_type_id': fields.many2one('stock.picking.type', 'Out Type'),
2866         'in_type_id': fields.many2one('stock.picking.type', 'In Type'),
2867         'int_type_id': fields.many2one('stock.picking.type', 'Internal Type'),
2868         'crossdock_route_id': fields.many2one('stock.location.route', 'Crossdock Route'),
2869         'reception_route_id': fields.many2one('stock.location.route', 'Receipt Route'),
2870         'delivery_route_id': fields.many2one('stock.location.route', 'Delivery Route'),
2871         'resupply_from_wh': fields.boolean('Resupply From Other Warehouses'),
2872         'resupply_wh_ids': fields.many2many('stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id', 'Resupply Warehouses'),
2873         'resupply_route_ids': fields.one2many('stock.location.route', 'supplied_wh_id', 'Resupply Routes', 
2874                                               help="Routes will be created for these resupply warehouses and you can select them on products and product categories"),
2875         'default_resupply_wh_id': fields.many2one('stock.warehouse', 'Default Resupply Warehouse', help="Goods will always be resupplied from this warehouse"),
2876     }
2877
2878     def onchange_filter_default_resupply_wh_id(self, cr, uid, ids, default_resupply_wh_id, resupply_wh_ids, context=None):
2879         resupply_wh_ids = set([x['id'] for x in (self.resolve_2many_commands(cr, uid, 'resupply_wh_ids', resupply_wh_ids, ['id']))])
2880         if default_resupply_wh_id: #If we are removing the default resupply, we don't have default_resupply_wh_id 
2881             resupply_wh_ids.add(default_resupply_wh_id)
2882         resupply_wh_ids = list(resupply_wh_ids)        
2883         return {'value': {'resupply_wh_ids': resupply_wh_ids}}
2884
2885     def _get_external_transit_location(self, cr, uid, warehouse, context=None):
2886         ''' returns browse record of inter company transit location, if found'''
2887         data_obj = self.pool.get('ir.model.data')
2888         location_obj = self.pool.get('stock.location')
2889         try:
2890             inter_wh_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]
2891         except:
2892             return False
2893         return location_obj.browse(cr, uid, inter_wh_loc, context=context)
2894
2895     def _get_inter_wh_route(self, cr, uid, warehouse, wh, context=None):
2896         return {
2897             'name': _('%s: Supply Product from %s') % (warehouse.name, wh.name),
2898             'warehouse_selectable': False,
2899             'product_selectable': True,
2900             'product_categ_selectable': True,
2901             'supplied_wh_id': warehouse.id,
2902             'supplier_wh_id': wh.id,
2903         }
2904
2905     def _create_resupply_routes(self, cr, uid, warehouse, supplier_warehouses, default_resupply_wh, context=None):
2906         route_obj = self.pool.get('stock.location.route')
2907         pull_obj = self.pool.get('procurement.rule')
2908         #create route selectable on the product to resupply the warehouse from another one
2909         external_transit_location = self._get_external_transit_location(cr, uid, warehouse, context=context)
2910         internal_transit_location = warehouse.company_id.internal_transit_location_id
2911         input_loc = warehouse.wh_input_stock_loc_id
2912         if warehouse.reception_steps == 'one_step':
2913             input_loc = warehouse.lot_stock_id
2914         for wh in supplier_warehouses:
2915             transit_location = wh.company_id.id == warehouse.company_id.id and internal_transit_location or external_transit_location
2916             if transit_location:
2917                 output_loc = wh.wh_output_stock_loc_id
2918                 if wh.delivery_steps == 'ship_only':
2919                     output_loc = wh.lot_stock_id
2920                     # Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
2921                     mto_pull_vals = self._get_mto_pull_rule(cr, uid, wh, [(output_loc, transit_location, wh.out_type_id.id)], context=context)[0]
2922                     pull_obj.create(cr, uid, mto_pull_vals, context=context)
2923                 inter_wh_route_vals = self._get_inter_wh_route(cr, uid, warehouse, wh, context=context)
2924                 inter_wh_route_id = route_obj.create(cr, uid, vals=inter_wh_route_vals, context=context)
2925                 values = [(output_loc, transit_location, wh.out_type_id.id, wh), (transit_location, input_loc, warehouse.in_type_id.id, warehouse)]
2926                 pull_rules_list = self._get_supply_pull_rules(cr, uid, warehouse, values, inter_wh_route_id, context=context)
2927                 for pull_rule in pull_rules_list:
2928                     pull_obj.create(cr, uid, vals=pull_rule, context=context)
2929                 #if the warehouse is also set as default resupply method, assign this route automatically to the warehouse
2930                 if default_resupply_wh and default_resupply_wh.id == wh.id:
2931                     self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]}, context=context)
2932
2933     _defaults = {
2934         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2935         'reception_steps': 'one_step',
2936         'delivery_steps': 'ship_only',
2937     }
2938     _sql_constraints = [
2939         ('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
2940         ('warehouse_code_uniq', 'unique(code, company_id)', 'The code of the warehouse must be unique per company!'),
2941     ]
2942
2943     def _get_partner_locations(self, cr, uid, ids, context=None):
2944         ''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
2945         data_obj = self.pool.get('ir.model.data')
2946         location_obj = self.pool.get('stock.location')
2947         try:
2948             customer_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]
2949             supplier_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]
2950         except:
2951             customer_loc = location_obj.search(cr, uid, [('usage', '=', 'customer')], context=context)
2952             customer_loc = customer_loc and customer_loc[0] or False
2953             supplier_loc = location_obj.search(cr, uid, [('usage', '=', 'supplier')], context=context)
2954             supplier_loc = supplier_loc and supplier_loc[0] or False
2955         if not (customer_loc and supplier_loc):
2956             raise osv.except_osv(_('Error!'), _('Can\'t find any customer or supplier location.'))
2957         return location_obj.browse(cr, uid, [customer_loc, supplier_loc], context=context)
2958
2959     def switch_location(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
2960         location_obj = self.pool.get('stock.location')
2961
2962         new_reception_step = new_reception_step or warehouse.reception_steps
2963         new_delivery_step = new_delivery_step or warehouse.delivery_steps
2964         if warehouse.reception_steps != new_reception_step:
2965             location_obj.write(cr, uid, [warehouse.wh_input_stock_loc_id.id, warehouse.wh_qc_stock_loc_id.id], {'active': False}, context=context)
2966             if new_reception_step != 'one_step':
2967                 location_obj.write(cr, uid, warehouse.wh_input_stock_loc_id.id, {'active': True}, context=context)
2968             if new_reception_step == 'three_steps':
2969                 location_obj.write(cr, uid, warehouse.wh_qc_stock_loc_id.id, {'active': True}, context=context)
2970
2971         if warehouse.delivery_steps != new_delivery_step:
2972             location_obj.write(cr, uid, [warehouse.wh_output_stock_loc_id.id, warehouse.wh_pack_stock_loc_id.id], {'active': False}, context=context)
2973             if new_delivery_step != 'ship_only':
2974                 location_obj.write(cr, uid, warehouse.wh_output_stock_loc_id.id, {'active': True}, context=context)
2975             if new_delivery_step == 'pick_pack_ship':
2976                 location_obj.write(cr, uid, warehouse.wh_pack_stock_loc_id.id, {'active': True}, context=context)
2977         return True
2978
2979     def _get_reception_delivery_route(self, cr, uid, warehouse, route_name, context=None):
2980         return {
2981             'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
2982             'product_categ_selectable': True,
2983             'product_selectable': False,
2984             'sequence': 10,
2985         }
2986
2987     def _get_supply_pull_rules(self, cr, uid, supplied_warehouse, values, new_route_id, context=None):
2988         pull_rules_list = []
2989         for from_loc, dest_loc, pick_type_id, warehouse in values:
2990             pull_rules_list.append({
2991                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
2992                 'location_src_id': from_loc.id,
2993                 'location_id': dest_loc.id,
2994                 'route_id': new_route_id,
2995                 'action': 'move',
2996                 'picking_type_id': pick_type_id,
2997                 'procure_method': warehouse.lot_stock_id.id != from_loc.id and 'make_to_order' or 'make_to_stock', # first part of the resuply route is MTS
2998                 'warehouse_id': supplied_warehouse.id,
2999                 'propagate_warehouse_id': warehouse.id,
3000             })
3001         return pull_rules_list
3002
3003     def _get_push_pull_rules(self, cr, uid, warehouse, active, values, new_route_id, context=None):
3004         first_rule = True
3005         push_rules_list = []
3006         pull_rules_list = []
3007         for from_loc, dest_loc, pick_type_id in values:
3008             push_rules_list.append({
3009                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
3010                 'location_from_id': from_loc.id,
3011                 'location_dest_id': dest_loc.id,
3012                 'route_id': new_route_id,
3013                 'auto': 'manual',
3014                 'picking_type_id': pick_type_id,
3015                 'active': active,
3016                 'warehouse_id': warehouse.id,
3017             })
3018             pull_rules_list.append({
3019                 'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context),
3020                 'location_src_id': from_loc.id,
3021                 'location_id': dest_loc.id,
3022                 'route_id': new_route_id,
3023                 'action': 'move',
3024                 'picking_type_id': pick_type_id,
3025                 'procure_method': first_rule is True and 'make_to_stock' or 'make_to_order',
3026                 'active': active,
3027                 'warehouse_id': warehouse.id,
3028             })
3029             first_rule = False
3030         return push_rules_list, pull_rules_list
3031
3032     def _get_mto_route(self, cr, uid, context=None):
3033         route_obj = self.pool.get('stock.location.route')
3034         data_obj = self.pool.get('ir.model.data')
3035         try:
3036             mto_route_id = data_obj.get_object_reference(cr, uid, 'stock', 'route_warehouse0_mto')[1]
3037         except:
3038             mto_route_id = route_obj.search(cr, uid, [('name', 'like', _('Make To Order'))], context=context)
3039             mto_route_id = mto_route_id and mto_route_id[0] or False
3040         if not mto_route_id:
3041             raise osv.except_osv(_('Error!'), _('Can\'t find any generic Make To Order route.'))
3042         return mto_route_id
3043
3044     def _check_remove_mto_resupply_rules(self, cr, uid, warehouse, context=None):
3045         """ Checks that the moves from the different """
3046         pull_obj = self.pool.get('procurement.rule')
3047         mto_route_id = self._get_mto_route(cr, uid, context=context)
3048         rules = pull_obj.search(cr, uid, ['&', ('location_src_id', '=', warehouse.lot_stock_id.id), ('location_id.usage', '=', 'transit')], context=context)
3049         pull_obj.unlink(cr, uid, rules, context=context)
3050
3051     def _get_mto_pull_rule(self, cr, uid, warehouse, values, context=None):
3052         mto_route_id = self._get_mto_route(cr, uid, context=context)
3053         res = []
3054         for value in values:
3055             from_loc, dest_loc, pick_type_id = value
3056             res += [{
3057             'name': self._format_rulename(cr, uid, warehouse, from_loc, dest_loc, context=context) + _(' MTO'),
3058             'location_src_id': from_loc.id,
3059             'location_id': dest_loc.id,
3060             'route_id': mto_route_id,
3061             'action': 'move',
3062             'picking_type_id': pick_type_id,
3063             'procure_method': 'make_to_order',
3064             'active': True,
3065             'warehouse_id': warehouse.id,
3066             }]
3067         return res
3068
3069     def _get_crossdock_route(self, cr, uid, warehouse, route_name, context=None):
3070         return {
3071             'name': self._format_routename(cr, uid, warehouse, route_name, context=context),
3072             'warehouse_selectable': False,
3073             'product_selectable': True,
3074             'product_categ_selectable': True,
3075             'active': warehouse.delivery_steps != 'ship_only' and warehouse.reception_steps != 'one_step',
3076             'sequence': 20,
3077         }
3078
3079     def create_routes(self, cr, uid, ids, warehouse, context=None):
3080         wh_route_ids = []
3081         route_obj = self.pool.get('stock.location.route')
3082         pull_obj = self.pool.get('procurement.rule')
3083         push_obj = self.pool.get('stock.location.path')
3084         routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3085         #create reception route and rules
3086         route_name, values = routes_dict[warehouse.reception_steps]
3087         route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3088         reception_route_id = route_obj.create(cr, uid, route_vals, context=context)
3089         wh_route_ids.append((4, reception_route_id))
3090         push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, reception_route_id, context=context)
3091         #create the push/pull rules
3092         for push_rule in push_rules_list:
3093             push_obj.create(cr, uid, vals=push_rule, context=context)
3094         for pull_rule in pull_rules_list:
3095             #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
3096             pull_rule['procure_method'] = 'make_to_order'
3097             pull_obj.create(cr, uid, vals=pull_rule, context=context)
3098
3099         #create MTS route and pull rules for delivery and a specific route MTO to be set on the product
3100         route_name, values = routes_dict[warehouse.delivery_steps]
3101         route_vals = self._get_reception_delivery_route(cr, uid, warehouse, route_name, context=context)
3102         #create the route and its pull rules
3103         delivery_route_id = route_obj.create(cr, uid, route_vals, context=context)
3104         wh_route_ids.append((4, delivery_route_id))
3105         dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, delivery_route_id, context=context)
3106         for pull_rule in pull_rules_list:
3107             pull_obj.create(cr, uid, vals=pull_rule, context=context)
3108         #create MTO pull rule and link it to the generic MTO route
3109         mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3110         mto_pull_id = pull_obj.create(cr, uid, mto_pull_vals, context=context)
3111
3112         #create a route for cross dock operations, that can be set on products and product categories
3113         route_name, values = routes_dict['crossdock']
3114         crossdock_route_vals = self._get_crossdock_route(cr, uid, warehouse, route_name, context=context)
3115         crossdock_route_id = route_obj.create(cr, uid, vals=crossdock_route_vals, context=context)
3116         wh_route_ids.append((4, crossdock_route_id))
3117         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)
3118         for pull_rule in pull_rules_list:
3119             # Fixed cross-dock is logically mto
3120             pull_rule['procure_method'] = 'make_to_order'
3121             pull_obj.create(cr, uid, vals=pull_rule, context=context)
3122
3123         #create route selectable on the product to resupply the warehouse from another one
3124         self._create_resupply_routes(cr, uid, warehouse, warehouse.resupply_wh_ids, warehouse.default_resupply_wh_id, context=context)
3125
3126         #return routes and mto pull rule to store on the warehouse
3127         return {
3128             'route_ids': wh_route_ids,
3129             'mto_pull_id': mto_pull_id,
3130             'reception_route_id': reception_route_id,
3131             'delivery_route_id': delivery_route_id,
3132             'crossdock_route_id': crossdock_route_id,
3133         }
3134
3135     def change_route(self, cr, uid, ids, warehouse, new_reception_step=False, new_delivery_step=False, context=None):
3136         picking_type_obj = self.pool.get('stock.picking.type')
3137         pull_obj = self.pool.get('procurement.rule')
3138         push_obj = self.pool.get('stock.location.path')
3139         route_obj = self.pool.get('stock.location.route')
3140         new_reception_step = new_reception_step or warehouse.reception_steps
3141         new_delivery_step = new_delivery_step or warehouse.delivery_steps
3142
3143         #change the default source and destination location and (de)activate picking types
3144         input_loc = warehouse.wh_input_stock_loc_id
3145         if new_reception_step == 'one_step':
3146             input_loc = warehouse.lot_stock_id
3147         output_loc = warehouse.wh_output_stock_loc_id
3148         if new_delivery_step == 'ship_only':
3149             output_loc = warehouse.lot_stock_id
3150         picking_type_obj.write(cr, uid, warehouse.in_type_id.id, {'default_location_dest_id': input_loc.id}, context=context)
3151         picking_type_obj.write(cr, uid, warehouse.out_type_id.id, {'default_location_src_id': output_loc.id}, context=context)
3152         picking_type_obj.write(cr, uid, warehouse.pick_type_id.id, {'active': new_delivery_step != 'ship_only'}, context=context)
3153         picking_type_obj.write(cr, uid, warehouse.pack_type_id.id, {'active': new_delivery_step == 'pick_pack_ship'}, context=context)
3154
3155         routes_dict = self.get_routes_dict(cr, uid, ids, warehouse, context=context)
3156         #update delivery route and rules: unlink the existing rules of the warehouse delivery route and recreate it
3157         pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.delivery_route_id.pull_ids], context=context)
3158         route_name, values = routes_dict[new_delivery_step]
3159         route_obj.write(cr, uid, warehouse.delivery_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3160         dummy, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.delivery_route_id.id, context=context)
3161         #create the pull rules
3162         for pull_rule in pull_rules_list:
3163             pull_obj.create(cr, uid, vals=pull_rule, context=context)
3164
3165         #update receipt route and rules: unlink the existing rules of the warehouse receipt route and recreate it
3166         pull_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.pull_ids], context=context)
3167         push_obj.unlink(cr, uid, [pu.id for pu in warehouse.reception_route_id.push_ids], context=context)
3168         route_name, values = routes_dict[new_reception_step]
3169         route_obj.write(cr, uid, warehouse.reception_route_id.id, {'name': self._format_routename(cr, uid, warehouse, route_name, context=context)}, context=context)
3170         push_rules_list, pull_rules_list = self._get_push_pull_rules(cr, uid, warehouse, True, values, warehouse.reception_route_id.id, context=context)
3171         #create the push/pull rules
3172         for push_rule in push_rules_list:
3173             push_obj.create(cr, uid, vals=push_rule, context=context)
3174         for pull_rule in pull_rules_list:
3175             #all pull rules in receipt route are mto, because we don't want to wait for the scheduler to trigger an orderpoint on input location
3176             pull_rule['procure_method'] = 'make_to_order'
3177             pull_obj.create(cr, uid, vals=pull_rule, context=context)
3178
3179         route_obj.write(cr, uid, warehouse.crossdock_route_id.id, {'active': new_reception_step != 'one_step' and new_delivery_step != 'ship_only'}, context=context)
3180
3181         #change MTO rule
3182         dummy, values = routes_dict[new_delivery_step]
3183         mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, values, context=context)[0]
3184         pull_obj.write(cr, uid, warehouse.mto_pull_id.id, mto_pull_vals, context=context)
3185         return True
3186
3187     def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):
3188         seq_obj = self.pool.get('ir.sequence')
3189         picking_type_obj = self.pool.get('stock.picking.type')
3190         #create new sequences
3191         in_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence in'), 'prefix': warehouse.code + '/IN/', 'padding': 5}, context=context)
3192         out_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence out'), 'prefix': warehouse.code + '/OUT/', 'padding': 5}, context=context)
3193         pack_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': warehouse.code + '/PACK/', 'padding': 5}, context=context)
3194         pick_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': warehouse.code + '/PICK/', 'padding': 5}, context=context)
3195         int_seq_id = seq_obj.create(cr, SUPERUSER_ID, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': warehouse.code + '/INT/', 'padding': 5}, context=context)
3196
3197         wh_stock_loc = warehouse.lot_stock_id
3198         wh_input_stock_loc = warehouse.wh_input_stock_loc_id
3199         wh_output_stock_loc = warehouse.wh_output_stock_loc_id
3200         wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id
3201
3202         #fetch customer and supplier locations, for references
3203         customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)
3204
3205         #create in, out, internal picking types for warehouse
3206         input_loc = wh_input_stock_loc
3207         if warehouse.reception_steps == 'one_step':
3208             input_loc = wh_stock_loc
3209         output_loc = wh_output_stock_loc
3210         if warehouse.delivery_steps == 'ship_only':
3211             output_loc = wh_stock_loc
3212
3213         #choose the next available color for the picking types of this warehouse
3214         color = 0
3215         available_colors = [c%9 for c in range(3, 12)]  # put flashy colors first
3216         all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')
3217         #don't use sets to preserve the list order
3218         for x in all_used_colors:
3219             if x['color'] in available_colors:
3220                 available_colors.remove(x['color'])
3221         if available_colors:
3222             color = available_colors[0]
3223
3224         #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship. 
3225         max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')
3226         max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
3227
3228         in_type_id = picking_type_obj.create(cr, uid, vals={
3229             'name': _('Receipts'),
3230             'warehouse_id': warehouse.id,
3231             'code': 'incoming',
3232             'sequence_id': in_seq_id,
3233             'default_location_src_id': supplier_loc.id,
3234             'default_location_dest_id': input_loc.id,
3235             'sequence': max_sequence + 1,
3236             'color': color}, context=context)
3237         out_type_id = picking_type_obj.create(cr, uid, vals={
3238             'name': _('Delivery Orders'),
3239             'warehouse_id': warehouse.id,
3240             'code': 'outgoing',
3241             'sequence_id': out_seq_id,
3242             'return_picking_type_id': in_type_id,
3243             'default_location_src_id': output_loc.id,
3244             'default_location_dest_id': customer_loc.id,
3245             'sequence': max_sequence + 4,
3246             'color': color}, context=context)
3247         picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)
3248         int_type_id = picking_type_obj.create(cr, uid, vals={
3249             'name': _('Internal Transfers'),
3250             'warehouse_id': warehouse.id,
3251             'code': 'internal',
3252             'sequence_id': int_seq_id,
3253             'default_location_src_id': wh_stock_loc.id,
3254             'default_location_dest_id': wh_stock_loc.id,
3255             'active': True,
3256             'sequence': max_sequence + 2,
3257             'color': color}, context=context)
3258         pack_type_id = picking_type_obj.create(cr, uid, vals={
3259             'name': _('Pack'),
3260             'warehouse_id': warehouse.id,
3261             'code': 'internal',
3262             'sequence_id': pack_seq_id,
3263             'default_location_src_id': wh_pack_stock_loc.id,
3264             'default_location_dest_id': output_loc.id,
3265             'active': warehouse.delivery_steps == 'pick_pack_ship',
3266             'sequence': max_sequence + 3,
3267             'color': color}, context=context)
3268         pick_type_id = picking_type_obj.create(cr, uid, vals={
3269             'name': _('Pick'),
3270             'warehouse_id': warehouse.id,
3271             'code': 'internal',
3272             'sequence_id': pick_seq_id,
3273             'default_location_src_id': wh_stock_loc.id,
3274             'default_location_dest_id': wh_pack_stock_loc.id,
3275             'active': warehouse.delivery_steps != 'ship_only',
3276             'sequence': max_sequence + 2,
3277             'color': color}, context=context)
3278
3279         #write picking types on WH
3280         vals = {
3281             'in_type_id': in_type_id,
3282             'out_type_id': out_type_id,
3283             'pack_type_id': pack_type_id,
3284             'pick_type_id': pick_type_id,
3285             'int_type_id': int_type_id,
3286         }
3287         super(stock_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)
3288
3289
3290     def create(self, cr, uid, vals, context=None):
3291         if context is None:
3292             context = {}
3293         if vals is None:
3294             vals = {}
3295         data_obj = self.pool.get('ir.model.data')
3296         seq_obj = self.pool.get('ir.sequence')
3297         picking_type_obj = self.pool.get('stock.picking.type')
3298         location_obj = self.pool.get('stock.location')
3299
3300         #create view location for warehouse
3301         loc_vals = {
3302                 'name': _(vals.get('code')),
3303                 'usage': 'view',
3304                 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1],
3305         }
3306         if vals.get('company_id'):
3307             loc_vals['company_id'] = vals.get('company_id')
3308         wh_loc_id = location_obj.create(cr, uid, loc_vals, context=context)
3309         vals['view_location_id'] = wh_loc_id
3310         #create all location
3311         def_values = self.default_get(cr, uid, {'reception_steps', 'delivery_steps'})
3312         reception_steps = vals.get('reception_steps',  def_values['reception_steps'])
3313         delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
3314         context_with_inactive = context.copy()
3315         context_with_inactive['active_test'] = False
3316         sub_locations = [
3317             {'name': _('Stock'), 'active': True, 'field': 'lot_stock_id'},
3318             {'name': _('Input'), 'active': reception_steps != 'one_step', 'field': 'wh_input_stock_loc_id'},
3319             {'name': _('Quality Control'), 'active': reception_steps == 'three_steps', 'field': 'wh_qc_stock_loc_id'},
3320             {'name': _('Output'), 'active': delivery_steps != 'ship_only', 'field': 'wh_output_stock_loc_id'},
3321             {'name': _('Packing Zone'), 'active': delivery_steps == 'pick_pack_ship', 'field': 'wh_pack_stock_loc_id'},
3322         ]
3323         for values in sub_locations:
3324             loc_vals = {
3325                 'name': values['name'],
3326                 'usage': 'internal',
3327                 'location_id': wh_loc_id,
3328                 'active': values['active'],
3329             }
3330             if vals.get('company_id'):
3331                 loc_vals['company_id'] = vals.get('company_id')
3332             location_id = location_obj.create(cr, uid, loc_vals, context=context_with_inactive)
3333             vals[values['field']] = location_id
3334
3335         #create WH
3336         new_id = super(stock_warehouse, self).create(cr, uid, vals=vals, context=context)
3337         warehouse = self.browse(cr, uid, new_id, context=context)
3338         self.create_sequences_and_picking_types(cr, uid, warehouse, context=context)
3339         warehouse.refresh()
3340
3341         #create routes and push/pull rules
3342         new_objects_dict = self.create_routes(cr, uid, new_id, warehouse, context=context)
3343         self.write(cr, uid, warehouse.id, new_objects_dict, context=context)
3344         return new_id
3345
3346     def _format_rulename(self, cr, uid, obj, from_loc, dest_loc, context=None):
3347         return obj.code + ': ' + from_loc.name + ' -> ' + dest_loc.name
3348
3349     def _format_routename(self, cr, uid, obj, name, context=None):
3350         return obj.name + ': ' + name
3351
3352     def get_routes_dict(self, cr, uid, ids, warehouse, context=None):
3353         #fetch customer and supplier locations, for references
3354         customer_loc, supplier_loc = self._get_partner_locations(cr, uid, ids, context=context)
3355
3356         return {
3357             'one_step': (_('Receipt in 1 step'), []),
3358             'two_steps': (_('Receipt in 2 steps'), [(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id.id)]),
3359             'three_steps': (_('Receipt 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)]),
3360             '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)]),
3361             'ship_only': (_('Ship Only'), [(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id.id)]),
3362             '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)]),
3363             '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)]),
3364         }
3365
3366     def _handle_renaming(self, cr, uid, warehouse, name, code, context=None):
3367         location_obj = self.pool.get('stock.location')
3368         route_obj = self.pool.get('stock.location.route')
3369         pull_obj = self.pool.get('procurement.rule')
3370         push_obj = self.pool.get('stock.location.path')
3371         #rename location
3372         location_id = warehouse.lot_stock_id.location_id.id
3373         location_obj.write(cr, uid, location_id, {'name': code}, context=context)
3374         #rename route and push-pull rules
3375         for route in warehouse.route_ids:
3376             route_obj.write(cr, uid, route.id, {'name': route.name.replace(warehouse.name, name, 1)}, context=context)
3377             for pull in route.pull_ids:
3378                 pull_obj.write(cr, uid, pull.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3379             for push in route.push_ids:
3380                 push_obj.write(cr, uid, push.id, {'name': pull.name.replace(warehouse.name, name, 1)}, context=context)
3381         #change the mto pull rule name
3382         if warehouse.mto_pull_id.id:
3383             pull_obj.write(cr, uid, warehouse.mto_pull_id.id, {'name': warehouse.mto_pull_id.name.replace(warehouse.name, name, 1)}, context=context)
3384
3385     def _check_delivery_resupply(self, cr, uid, warehouse, new_location, change_to_multiple, context=None):
3386         """ Will check if the resupply routes from this warehouse follow the changes of number of delivery steps """
3387         #Check routes that are being delivered by this warehouse and change the rule going to transit location
3388         route_obj = self.pool.get("stock.location.route")
3389         pull_obj = self.pool.get("procurement.rule")
3390         routes = route_obj.search(cr, uid, [('supplier_wh_id','=', warehouse.id)], context=context)
3391         pulls = pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_id.usage', '=', 'transit')], context=context)
3392         if pulls:
3393             pull_obj.write(cr, uid, pulls, {'location_src_id': new_location, 'procure_method': change_to_multiple and "make_to_order" or "make_to_stock"}, context=context)
3394         # Create or clean MTO rules
3395         mto_route_id = self._get_mto_route(cr, uid, context=context)
3396         if not change_to_multiple:
3397             # If single delivery we should create the necessary MTO rules for the resupply 
3398             # pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
3399             pull_recs = pull_obj.browse(cr, uid, pulls, context=context)
3400             transfer_locs = list(set([x.location_id for x in pull_recs]))
3401             vals = [(warehouse.lot_stock_id , x, warehouse.out_type_id.id) for x in transfer_locs]
3402             mto_pull_vals = self._get_mto_pull_rule(cr, uid, warehouse, vals, context=context)
3403             for mto_pull_val in mto_pull_vals:
3404                 pull_obj.create(cr, uid, mto_pull_val, context=context)
3405         else:
3406             # We need to delete all the MTO pull rules, otherwise they risk to be used in the system
3407             pulls = pull_obj.search(cr, uid, ['&', ('route_id', '=', mto_route_id), ('location_id.usage', '=', 'transit'), ('location_src_id', '=', warehouse.lot_stock_id.id)], context=context)
3408             if pulls:
3409                 pull_obj.unlink(cr, uid, pulls, context=context)
3410
3411     def _check_reception_resupply(self, cr, uid, warehouse, new_location, context=None):
3412         """
3413             Will check if the resupply routes to this warehouse follow the changes of number of receipt steps
3414         """
3415         #Check routes that are being delivered by this warehouse and change the rule coming from transit location
3416         route_obj = self.pool.get("stock.location.route")
3417         pull_obj = self.pool.get("procurement.rule")
3418         routes = route_obj.search(cr, uid, [('supplied_wh_id','=', warehouse.id)], context=context)
3419         pulls= pull_obj.search(cr, uid, ['&', ('route_id', 'in', routes), ('location_src_id.usage', '=', 'transit')])
3420         if pulls:
3421             pull_obj.write(cr, uid, pulls, {'location_id': new_location}, context=context)
3422
3423     def _check_resupply(self, cr, uid, warehouse, reception_new, delivery_new, context=None):
3424         if reception_new:
3425             old_val = warehouse.reception_steps
3426             new_val = reception_new
3427             change_to_one = (old_val != 'one_step' and new_val == 'one_step')
3428             change_to_multiple = (old_val == 'one_step' and new_val != 'one_step')
3429             if change_to_one or change_to_multiple:
3430                 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_input_stock_loc_id.id
3431                 self._check_reception_resupply(cr, uid, warehouse, new_location, context=context)
3432         if delivery_new:
3433             old_val = warehouse.delivery_steps
3434             new_val = delivery_new
3435             change_to_one = (old_val != 'ship_only' and new_val == 'ship_only')
3436             change_to_multiple = (old_val == 'ship_only' and new_val != 'ship_only')
3437             if change_to_one or change_to_multiple:
3438                 new_location = change_to_one and warehouse.lot_stock_id.id or warehouse.wh_output_stock_loc_id.id 
3439                 self._check_delivery_resupply(cr, uid, warehouse, new_location, change_to_multiple, context=context)
3440
3441     def write(self, cr, uid, ids, vals, context=None):
3442         if context is None:
3443             context = {}
3444         if isinstance(ids, (int, long)):
3445             ids = [ids]
3446         seq_obj = self.pool.get('ir.sequence')
3447         route_obj = self.pool.get('stock.location.route')
3448         context_with_inactive = context.copy()
3449         context_with_inactive['active_test'] = False
3450         for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):
3451             #first of all, check if we need to delete and recreate route
3452             if vals.get('reception_steps') or vals.get('delivery_steps'):
3453                 #activate and deactivate location according to reception and delivery option
3454                 self.switch_location(cr, uid, warehouse.id, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context)
3455                 # switch between route
3456                 self.change_route(cr, uid, ids, warehouse, vals.get('reception_steps', False), vals.get('delivery_steps', False), context=context_with_inactive)
3457                 # Check if we need to change something to resupply warehouses and associated MTO rules
3458                 self._check_resupply(cr, uid, warehouse, vals.get('reception_steps'), vals.get('delivery_steps'), context=context)
3459                 warehouse.refresh()
3460             if vals.get('code') or vals.get('name'):
3461                 name = warehouse.name
3462                 #rename sequence
3463                 if vals.get('name'):
3464                     name = vals.get('name', warehouse.name)
3465                 self._handle_renaming(cr, uid, warehouse, name, vals.get('code', warehouse.code), context=context_with_inactive)
3466                 if warehouse.in_type_id:
3467                     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)
3468                     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)
3469                     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)
3470                     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)
3471                     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)
3472         if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
3473             for cmd in vals.get('resupply_wh_ids'):
3474                 if cmd[0] == 6:
3475                     new_ids = set(cmd[2])
3476                     old_ids = set([wh.id for wh in warehouse.resupply_wh_ids])
3477                     to_add_wh_ids = new_ids - old_ids
3478                     if to_add_wh_ids:
3479                         supplier_warehouses = self.browse(cr, uid, list(to_add_wh_ids), context=context)
3480                         self._create_resupply_routes(cr, uid, warehouse, supplier_warehouses, warehouse.default_resupply_wh_id, context=context)
3481                     to_remove_wh_ids = old_ids - new_ids
3482                     if to_remove_wh_ids:
3483                         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)
3484                         if to_remove_route_ids:
3485                             route_obj.unlink(cr, uid, to_remove_route_ids, context=context)
3486                 else:
3487                     #not implemented
3488                     pass
3489         if 'default_resupply_wh_id' in vals:
3490             if vals.get('default_resupply_wh_id') == warehouse.id:
3491                 raise osv.except_osv(_('Warning'),_('The default resupply warehouse should be different than the warehouse itself!'))
3492             if warehouse.default_resupply_wh_id:
3493                 #remove the existing resupplying route on the warehouse
3494                 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)
3495                 for inter_wh_route_id in to_remove_route_ids:
3496                     self.write(cr, uid, [warehouse.id], {'route_ids': [(3, inter_wh_route_id)]})
3497             if vals.get('default_resupply_wh_id'):
3498                 #assign the new resupplying route on all products
3499                 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)
3500                 for inter_wh_route_id in to_assign_route_ids:
3501                     self.write(cr, uid, [warehouse.id], {'route_ids': [(4, inter_wh_route_id)]})
3502
3503         return super(stock_warehouse, self).write(cr, uid, ids, vals=vals, context=context)
3504
3505     def get_all_routes_for_wh(self, cr, uid, warehouse, context=None):
3506         route_obj = self.pool.get("stock.location.route")
3507         all_routes = [route.id for route in warehouse.route_ids]
3508         all_routes += route_obj.search(cr, uid, [('supplied_wh_id', '=', warehouse.id)], context=context)
3509         all_routes += [warehouse.mto_pull_id.route_id.id]
3510         return all_routes
3511
3512     def view_all_routes_for_wh(self, cr, uid, ids, context=None):
3513         all_routes = []
3514         for wh in self.browse(cr, uid, ids, context=context):
3515             all_routes += self.get_all_routes_for_wh(cr, uid, wh, context=context)
3516
3517         domain = [('id', 'in', all_routes)]
3518         return {
3519             'name': _('Warehouse\'s Routes'),
3520             'domain': domain,
3521             'res_model': 'stock.location.route',
3522             'type': 'ir.actions.act_window',
3523             'view_id': False,
3524             'view_mode': 'tree,form',
3525             'view_type': 'form',
3526             'limit': 20
3527         }
3528
3529
3530 class stock_location_path(osv.osv):
3531     _name = "stock.location.path"
3532     _description = "Pushed Flows"
3533     _order = "name"
3534
3535     def _get_rules(self, cr, uid, ids, context=None):
3536         res = []
3537         for route in self.browse(cr, uid, ids, context=context):
3538             res += [x.id for x in route.push_ids]
3539         return res
3540
3541     _columns = {
3542         'name': fields.char('Operation Name', required=True),
3543         'company_id': fields.many2one('res.company', 'Company'),
3544         'route_id': fields.many2one('stock.location.route', 'Route'),
3545         'location_from_id': fields.many2one('stock.location', 'Source Location', ondelete='cascade', select=1, required=True),
3546         'location_dest_id': fields.many2one('stock.location', 'Destination Location', ondelete='cascade', select=1, required=True),
3547         'delay': fields.integer('Delay (days)', help="Number of days to do this transition"),
3548         '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"), 
3549         'auto': fields.selection(
3550             [('auto','Automatic Move'), ('manual','Manual Operation'),('transparent','Automatic No Step Added')],
3551             'Automatic Move',
3552             required=True, select=1,
3553             help="This is used to define paths the product has to follow within the location tree.\n" \
3554                 "The 'Automatic Move' value will create a stock move after the current one that will be "\
3555                 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
3556                 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
3557             ),
3558         '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'),
3559         'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the rule without removing it."),
3560         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
3561         'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',
3562             store={
3563                 'stock.location.route': (_get_rules, ['sequence'], 10),
3564                 'stock.location.path': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),
3565         }),
3566         'sequence': fields.integer('Sequence'),
3567     }
3568     _defaults = {
3569         'auto': 'auto',
3570         'delay': 0,
3571         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c),
3572         'propagate': True,
3573         'active': True,
3574     }
3575
3576     def _prepare_push_apply(self, cr, uid, rule, move, context=None):
3577         newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3578         return {
3579                 'location_id': move.location_dest_id.id,
3580                 'location_dest_id': rule.location_dest_id.id,
3581                 'date': newdate,
3582                 'company_id': rule.company_id and rule.company_id.id or False,
3583                 'date_expected': newdate,
3584                 'picking_id': False,
3585                 'picking_type_id': rule.picking_type_id and rule.picking_type_id.id or False,
3586                 'propagate': rule.propagate,
3587                 'push_rule_id': rule.id,
3588                 'warehouse_id': rule.warehouse_id and rule.warehouse_id.id or False,
3589             }
3590
3591     def _apply(self, cr, uid, rule, move, context=None):
3592         move_obj = self.pool.get('stock.move')
3593         newdate = (datetime.strptime(move.date_expected, DEFAULT_SERVER_DATETIME_FORMAT) + relativedelta.relativedelta(days=rule.delay or 0)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
3594         if rule.auto == 'transparent':
3595             old_dest_location = move.location_dest_id.id
3596             move_obj.write(cr, uid, [move.id], {
3597                 'date': newdate,
3598                 'date_expected': newdate,
3599                 'location_dest_id': rule.location_dest_id.id
3600             })
3601             move.refresh()
3602             #avoid looping if a push rule is not well configured
3603             if rule.location_dest_id.id != old_dest_location:
3604                 #call again push_apply to see if a next step is defined
3605                 move_obj._push_apply(cr, uid, [move], context=context)
3606         else:
3607             vals = self._prepare_push_apply(cr, uid, rule, move, context=context)
3608             move_id = move_obj.copy(cr, uid, move.id, vals, context=context)
3609             move_obj.write(cr, uid, [move.id], {
3610                 'move_dest_id': move_id,
3611             })
3612             move_obj.action_confirm(cr, uid, [move_id], context=None)
3613
3614
3615 # -------------------------
3616 # Packaging related stuff
3617 # -------------------------
3618
3619 from openerp.report import report_sxw
3620
3621 class stock_package(osv.osv):
3622     """
3623     These are the packages, containing quants and/or other packages
3624     """
3625     _name = "stock.quant.package"
3626     _description = "Physical Packages"
3627     _parent_name = "parent_id"
3628     _parent_store = True
3629     _parent_order = 'name'
3630     _order = 'parent_left'
3631
3632     def name_get(self, cr, uid, ids, context=None):
3633         res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
3634         return res.items()
3635
3636     def _complete_name(self, cr, uid, ids, name, args, context=None):
3637         """ Forms complete name of location from parent location to child location.
3638         @return: Dictionary of values
3639         """
3640         res = {}
3641         for m in self.browse(cr, uid, ids, context=context):
3642             res[m.id] = m.name
3643             parent = m.parent_id
3644             while parent:
3645                 res[m.id] = parent.name + ' / ' + res[m.id]
3646                 parent = parent.parent_id
3647         return res
3648
3649     def _get_packages(self, cr, uid, ids, context=None):
3650         """Returns packages from quants for store"""
3651         res = set()
3652         for quant in self.browse(cr, uid, ids, context=context):
3653             if quant.package_id:
3654                 res.add(quant.package_id.id)
3655         return list(res)
3656
3657     def _get_packages_to_relocate(self, cr, uid, ids, context=None):
3658         res = set()
3659         for pack in self.browse(cr, uid, ids, context=context):
3660             res.add(pack.id)
3661             if pack.parent_id:
3662                 res.add(pack.parent_id.id)
3663         return list(res)
3664
3665     def _get_package_info(self, cr, uid, ids, name, args, context=None):
3666         default_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
3667         res = dict((res_id, {'location_id': False, 'company_id': default_company_id, 'owner_id': False}) for res_id in ids)
3668         for pack in self.browse(cr, uid, ids, context=context):
3669             if pack.quant_ids:
3670                 res[pack.id]['location_id'] = pack.quant_ids[0].location_id.id
3671                 res[pack.id]['owner_id'] = pack.quant_ids[0].owner_id and pack.quant_ids[0].owner_id.id or False
3672                 res[pack.id]['company_id'] = pack.quant_ids[0].company_id.id
3673             elif pack.children_ids:
3674                 res[pack.id]['location_id'] = pack.children_ids[0].location_id and pack.children_ids[0].location_id.id or False
3675                 res[pack.id]['owner_id'] = pack.children_ids[0].owner_id and pack.children_ids[0].owner_id.id or False
3676                 res[pack.id]['company_id'] = pack.children_ids[0].company_id and pack.children_ids[0].company_id.id or False
3677         return res
3678
3679     _columns = {
3680         'name': fields.char('Package Reference', select=True, copy=False),
3681         'complete_name': fields.function(_complete_name, type='char', string="Package Name",),
3682         'parent_left': fields.integer('Left Parent', select=1),
3683         'parent_right': fields.integer('Right Parent', select=1),
3684         'packaging_id': fields.many2one('product.packaging', 'Packaging', help="This field should be completed only if everything inside the package share the same product, otherwise it doesn't really makes sense.", select=True),
3685         'ul_id': fields.many2one('product.ul', 'Logistic Unit'),
3686         'location_id': fields.function(_get_package_info, type='many2one', relation='stock.location', string='Location', multi="package",
3687                                     store={
3688                                        'stock.quant': (_get_packages, ['location_id'], 10),
3689                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3690                                     }, readonly=True, select=True),
3691         'quant_ids': fields.one2many('stock.quant', 'package_id', 'Bulk Content', readonly=True),
3692         'parent_id': fields.many2one('stock.quant.package', 'Parent Package', help="The package containing this item", ondelete='restrict', readonly=True),
3693         'children_ids': fields.one2many('stock.quant.package', 'parent_id', 'Contained Packages', readonly=True),
3694         'company_id': fields.function(_get_package_info, type="many2one", relation='res.company', string='Company', multi="package", 
3695                                     store={
3696                                        'stock.quant': (_get_packages, ['company_id'], 10),
3697                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3698                                     }, readonly=True, select=True),
3699         'owner_id': fields.function(_get_package_info, type='many2one', relation='res.partner', string='Owner', multi="package",
3700                                 store={
3701                                        'stock.quant': (_get_packages, ['owner_id'], 10),
3702                                        'stock.quant.package': (_get_packages_to_relocate, ['quant_ids', 'children_ids', 'parent_id'], 10),
3703                                     }, readonly=True, select=True),
3704     }
3705     _defaults = {
3706         'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.quant.package') or _('Unknown Pack')
3707     }
3708
3709     def _check_location_constraint(self, cr, uid, packs, context=None):
3710         '''checks that all quants in a package are stored in the same location. This function cannot be used
3711            as a constraint because it needs to be checked on pack operations (they may not call write on the
3712            package)
3713         '''
3714         quant_obj = self.pool.get('stock.quant')
3715         for pack in packs:
3716             parent = pack
3717             while parent.parent_id:
3718                 parent = parent.parent_id
3719             quant_ids = self.get_content(cr, uid, [parent.id], context=context)
3720             quants = [x for x in quant_obj.browse(cr, uid, quant_ids, context=context) if x.qty > 0]
3721             location_id = quants and quants[0].location_id.id or False
3722             if not [quant.location_id.id == location_id for quant in quants]:
3723                 raise osv.except_osv(_('Error'), _('Everything inside a package should be in the same location'))
3724         return True
3725
3726     def action_print(self, cr, uid, ids, context=None):
3727         context = dict(context or {}, active_ids=ids)
3728         return self.pool.get("report").get_action(cr, uid, ids, 'stock.report_package_barcode_small', context=context)
3729     
3730     
3731     def unpack(self, cr, uid, ids, context=None):
3732         quant_obj = self.pool.get('stock.quant')
3733         for package in self.browse(cr, uid, ids, context=context):
3734             quant_ids = [quant.id for quant in package.quant_ids]
3735             quant_obj.write(cr, uid, quant_ids, {'package_id': package.parent_id.id or False}, context=context)
3736             children_package_ids = [child_package.id for child_package in package.children_ids]
3737             self.write(cr, uid, children_package_ids, {'parent_id': package.parent_id.id or False}, context=context)
3738         #delete current package since it contains nothing anymore
3739         self.unlink(cr, uid, ids, context=context)
3740         return self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'action_package_view', context=context)
3741
3742     def get_content(self, cr, uid, ids, context=None):
3743         child_package_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context)
3744         return self.pool.get('stock.quant').search(cr, uid, [('package_id', 'in', child_package_ids)], context=context)
3745
3746     def get_content_package(self, cr, uid, ids, context=None):
3747         quants_ids = self.get_content(cr, uid, ids, context=context)
3748         res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'stock', 'quantsact', context=context)
3749         res['domain'] = [('id', 'in', quants_ids)]
3750         return res
3751
3752     def _get_product_total_qty(self, cr, uid, package_record, product_id, context=None):
3753         ''' find the total of given product 'product_id' inside the given package 'package_id'''
3754         quant_obj = self.pool.get('stock.quant')
3755         all_quant_ids = self.get_content(cr, uid, [package_record.id], context=context)
3756         total = 0
3757         for quant in quant_obj.browse(cr, uid, all_quant_ids, context=context):
3758             if quant.product_id.id == product_id:
3759                 total += quant.qty
3760         return total
3761
3762     def _get_all_products_quantities(self, cr, uid, package_id, context=None):
3763         '''This function computes the different product quantities for the given package
3764         '''
3765         quant_obj = self.pool.get('stock.quant')
3766         res = {}
3767         for quant in quant_obj.browse(cr, uid, self.get_content(cr, uid, package_id, context=context)):
3768             if quant.product_id.id not in res:
3769                 res[quant.product_id.id] = 0
3770             res[quant.product_id.id] += quant.qty
3771         return res
3772
3773     def copy_pack(self, cr, uid, id, default_pack_values=None, default=None, context=None):
3774         stock_pack_operation_obj = self.pool.get('stock.pack.operation')
3775         if default is None:
3776             default = {}
3777         new_package_id = self.copy(cr, uid, id, default_pack_values, context=context)
3778         default['result_package_id'] = new_package_id
3779         op_ids = stock_pack_operation_obj.search(cr, uid, [('result_package_id', '=', id)], context=context)
3780         for op_id in op_ids:
3781             stock_pack_operation_obj.copy(cr, uid, op_id, default, context=context)
3782
3783
3784 class stock_pack_operation(osv.osv):
3785     _name = "stock.pack.operation"
3786     _description = "Packing Operation"
3787
3788     def _get_remaining_prod_quantities(self, cr, uid, operation, context=None):
3789         '''Get the remaining quantities per product on an operation with a package. This function returns a dictionary'''
3790         #if the operation doesn't concern a package, it's not relevant to call this function
3791         if not operation.package_id or operation.product_id:
3792             return {operation.product_id.id: operation.remaining_qty}
3793         #get the total of products the package contains
3794         res = self.pool.get('stock.quant.package')._get_all_products_quantities(cr, uid, operation.package_id.id, context=context)
3795         #reduce by the quantities linked to a move
3796         for record in operation.linked_move_operation_ids:
3797             if record.move_id.product_id.id not in res:
3798                 res[record.move_id.product_id.id] = 0
3799             res[record.move_id.product_id.id] -= record.qty
3800         return res
3801
3802     def _get_remaining_qty(self, cr, uid, ids, name, args, context=None):
3803         uom_obj = self.pool.get('product.uom')
3804         res = {}
3805         for ops in self.browse(cr, uid, ids, context=context):
3806             res[ops.id] = 0
3807             if ops.package_id and not ops.product_id:
3808                 #dont try to compute the remaining quantity for packages because it's not relevant (a package could include different products).
3809                 #should use _get_remaining_prod_quantities instead
3810                 continue
3811             else:
3812                 qty = ops.product_qty
3813                 if ops.product_uom_id:
3814                     qty = uom_obj._compute_qty_obj(cr, uid, ops.product_uom_id, ops.product_qty, ops.product_id.uom_id, context=context)
3815                 for record in ops.linked_move_operation_ids:
3816                     qty -= record.qty
3817                 #converting the remaining quantity in the pack operation UoM
3818                 if ops.product_uom_id:
3819                     qty = uom_obj._compute_qty_obj(cr, uid, ops.product_id.uom_id, qty, ops.product_uom_id, context=context)
3820                 res[ops.id] = qty
3821         return res
3822
3823     def product_id_change(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3824         res = self.on_change_tests(cr, uid, ids, product_id, product_uom_id, product_qty, context=context)
3825         if product_id and not product_uom_id:
3826             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3827             res['value']['product_uom_id'] = product.uom_id.id
3828         return res
3829
3830     def on_change_tests(self, cr, uid, ids, product_id, product_uom_id, product_qty, context=None):
3831         res = {'value': {}}
3832         uom_obj = self.pool.get('product.uom')
3833         if product_id:
3834             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
3835             product_uom_id = product_uom_id or product.uom_id.id
3836             selected_uom = uom_obj.browse(cr, uid, product_uom_id, context=context)
3837             if selected_uom.category_id.id != product.uom_id.category_id.id:
3838                 res['warning'] = {
3839                     'title': _('Warning: wrong UoM!'),
3840                     '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)
3841                 }
3842             if product_qty and 'warning' not in res:
3843                 rounded_qty = uom_obj._compute_qty(cr, uid, product_uom_id, product_qty, product_uom_id, round=True)
3844                 if rounded_qty != product_qty:
3845                     res['warning'] = {
3846                         'title': _('Warning: wrong quantity!'),
3847                         'message': _('The chosen quantity for product %s is not compatible with the UoM rounding. It will be automatically converted at confirmation') % (product.name)
3848                     }
3849         return res
3850
3851     _columns = {
3852         'picking_id': fields.many2one('stock.picking', 'Stock Picking', help='The stock operation where the packing has been made', required=True),
3853         'product_id': fields.many2one('product.product', 'Product', ondelete="CASCADE"),  # 1
3854         'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
3855         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
3856         'qty_done': fields.float('Quantity Processed', digits_compute=dp.get_precision('Product Unit of Measure')),
3857         'package_id': fields.many2one('stock.quant.package', 'Source Package'),  # 2
3858         'lot_id': fields.many2one('stock.production.lot', 'Lot/Serial Number'),
3859         'result_package_id': fields.many2one('stock.quant.package', 'Destination Package', help="If set, the operations are packed into this package", required=False, ondelete='cascade'),
3860         'date': fields.datetime('Date', required=True),
3861         'owner_id': fields.many2one('res.partner', 'Owner', help="Owner of the quants"),
3862         #'update_cost': fields.boolean('Need cost update'),
3863         'cost': fields.float("Cost", help="Unit Cost for this product line"),
3864         'currency': fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
3865         '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'),
3866         'remaining_qty': fields.function(_get_remaining_qty, type='float', string='Remaining Qty'),
3867         'location_id': fields.many2one('stock.location', 'Source Location', required=True),
3868         'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True),
3869         'processed': fields.selection([('true','Yes'), ('false','No')],'Has been processed?', required=True),
3870     }
3871
3872     _defaults = {
3873         'date': fields.date.context_today,
3874         'qty_done': 0,
3875         'processed': lambda *a: 'false',
3876     }
3877
3878     def write(self, cr, uid, ids, vals, context=None):
3879         context = context or {}
3880         res = super(stock_pack_operation, self).write(cr, uid, ids, vals, context=context)
3881         if isinstance(ids, (int, long)):
3882             ids = [ids]
3883         if not context.get("no_recompute"):
3884             pickings = vals.get('picking_id') and [vals['picking_id']] or list(set([x.picking_id.id for x in self.browse(cr, uid, ids, context=context)]))
3885             self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, pickings, context=context)
3886         return res
3887
3888     def create(self, cr, uid, vals, context=None):
3889         context = context or {}
3890         res_id = super(stock_pack_operation, self).create(cr, uid, vals, context=context)
3891         if vals.get("picking_id") and not context.get("no_recompute"):
3892             self.pool.get("stock.picking").do_recompute_remaining_quantities(cr, uid, [vals['picking_id']], context=context)
3893         return res_id
3894
3895     def action_drop_down(self, cr, uid, ids, context=None):
3896         ''' Used by barcode interface to say that pack_operation has been moved from src location 
3897             to destination location, if qty_done is less than product_qty than we have to split the
3898             operation in two to process the one with the qty moved
3899         '''
3900         processed_ids = []
3901         move_obj = self.pool.get("stock.move")
3902         for pack_op in self.browse(cr, uid, ids, context=None):
3903             if pack_op.product_id and pack_op.location_id and pack_op.location_dest_id:
3904                 move_obj.check_tracking_product(cr, uid, pack_op.product_id, pack_op.lot_id.id, pack_op.location_id, pack_op.location_dest_id, context=context)
3905             op = pack_op.id
3906             if pack_op.qty_done < pack_op.product_qty:
3907                 # we split the operation in two
3908                 op = self.copy(cr, uid, pack_op.id, {'product_qty': pack_op.qty_done, 'qty_done': pack_op.qty_done}, context=context)
3909                 self.write(cr, uid, [pack_op.id], {'product_qty': pack_op.product_qty - pack_op.qty_done, 'qty_done': 0, 'lot_id': False}, context=context)
3910             processed_ids.append(op)
3911         self.write(cr, uid, processed_ids, {'processed': 'true'}, context=context)
3912
3913     def create_and_assign_lot(self, cr, uid, id, name, context=None):
3914         ''' Used by barcode interface to create a new lot and assign it to the operation
3915         '''
3916         obj = self.browse(cr,uid,id,context)
3917         product_id = obj.product_id.id
3918         val = {'product_id': product_id}
3919         new_lot_id = False
3920         if name:
3921             lots = self.pool.get('stock.production.lot').search(cr, uid, ['&', ('name', '=', name), ('product_id', '=', product_id)], context=context)
3922             if lots:
3923                 new_lot_id = lots[0]
3924             val.update({'name': name})
3925
3926         if not new_lot_id:
3927             new_lot_id = self.pool.get('stock.production.lot').create(cr, uid, val, context=context)
3928         self.write(cr, uid, id, {'lot_id': new_lot_id}, context=context)
3929
3930     def _search_and_increment(self, cr, uid, picking_id, domain, filter_visible=False, visible_op_ids=False, increment=True, context=None):
3931         '''Search for an operation with given 'domain' in a picking, if it exists increment the qty (+1) otherwise create it
3932
3933         :param domain: list of tuple directly reusable as a domain
3934         context can receive a key 'current_package_id' with the package to consider for this operation
3935         returns True
3936         '''
3937         if context is None:
3938             context = {}
3939
3940         #if current_package_id is given in the context, we increase the number of items in this package
3941         package_clause = [('result_package_id', '=', context.get('current_package_id', False))]
3942         existing_operation_ids = self.search(cr, uid, [('picking_id', '=', picking_id)] + domain + package_clause, context=context)
3943         todo_operation_ids = []
3944         if existing_operation_ids:
3945             if filter_visible:
3946                 todo_operation_ids = [val for val in existing_operation_ids if val in visible_op_ids]
3947             else:
3948                 todo_operation_ids = existing_operation_ids
3949         if todo_operation_ids:
3950             #existing operation found for the given domain and picking => increment its quantity
3951             operation_id = todo_operation_ids[0]
3952             op_obj = self.browse(cr, uid, operation_id, context=context)
3953             qty = op_obj.qty_done
3954             if increment:
3955                 qty += 1
3956             else:
3957                 qty -= 1 if qty >= 1 else 0
3958                 if qty == 0 and op_obj.product_qty == 0:
3959                     #we have a line with 0 qty set, so delete it
3960                     self.unlink(cr, uid, [operation_id], context=context)
3961                     return False
3962             self.write(cr, uid, [operation_id], {'qty_done': qty}, context=context)
3963         else:
3964             #no existing operation found for the given domain and picking => create a new one
3965             picking_obj = self.pool.get("stock.picking")
3966             picking = picking_obj.browse(cr, uid, picking_id, context=context)
3967             values = {
3968                 'picking_id': picking_id,
3969                 'product_qty': 0,
3970                 'location_id': picking.location_id.id, 
3971                 'location_dest_id': picking.location_dest_id.id,
3972                 'qty_done': 1,
3973                 }
3974             for key in domain:
3975                 var_name, dummy, value = key
3976                 uom_id = False
3977                 if var_name == 'product_id':
3978                     uom_id = self.pool.get('product.product').browse(cr, uid, value, context=context).uom_id.id
3979                 update_dict = {var_name: value}
3980                 if uom_id:
3981                     update_dict['product_uom_id'] = uom_id
3982                 values.update(update_dict)
3983             operation_id = self.create(cr, uid, values, context=context)
3984         return operation_id
3985
3986
3987 class stock_move_operation_link(osv.osv):
3988     """
3989     Table making the link between stock.moves and stock.pack.operations to compute the remaining quantities on each of these objects
3990     """
3991     _name = "stock.move.operation.link"
3992     _description = "Link between stock moves and pack operations"
3993
3994     _columns = {
3995         '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."),
3996         'operation_id': fields.many2one('stock.pack.operation', 'Operation', required=True, ondelete="cascade"),
3997         'move_id': fields.many2one('stock.move', 'Move', required=True, ondelete="cascade"),
3998         'reserved_quant_id': fields.many2one('stock.quant', 'Reserved Quant', help="Technical field containing the quant that created this link between an operation and a stock move. Used at the stock_move_obj.action_done() time to avoid seeking a matching quant again"),
3999     }
4000
4001     def get_specific_domain(self, cr, uid, record, context=None):
4002         '''Returns the specific domain to consider for quant selection in action_assign() or action_done() of stock.move,
4003         having the record given as parameter making the link between the stock move and a pack operation'''
4004
4005         op = record.operation_id
4006         domain = []
4007         if op.package_id and op.product_id:
4008             #if removing a product from a box, we restrict the choice of quants to this box
4009             domain.append(('package_id', '=', op.package_id.id))
4010         elif op.package_id:
4011             #if moving a box, we allow to take everything from inside boxes as well
4012             domain.append(('package_id', 'child_of', [op.package_id.id]))
4013         else:
4014             #if not given any information about package, we don't open boxes
4015             domain.append(('package_id', '=', False))
4016         #if lot info is given, we restrict choice to this lot otherwise we can take any
4017         if op.lot_id:
4018             domain.append(('lot_id', '=', op.lot_id.id))
4019         #if owner info is given, we restrict to this owner otherwise we restrict to no owner
4020         if op.owner_id:
4021             domain.append(('owner_id', '=', op.owner_id.id))
4022         else:
4023             domain.append(('owner_id', '=', False))
4024         return domain
4025
4026 class stock_warehouse_orderpoint(osv.osv):
4027     """
4028     Defines Minimum stock rules.
4029     """
4030     _name = "stock.warehouse.orderpoint"
4031     _description = "Minimum Inventory Rule"
4032
4033     def subtract_procurements(self, cr, uid, orderpoint, context=None):
4034         '''This function returns quantity of product that needs to be deducted from the orderpoint computed quantity because there's already a procurement created with aim to fulfill it.
4035         '''
4036         qty = 0
4037         uom_obj = self.pool.get("product.uom")
4038         for procurement in orderpoint.procurement_ids:
4039             if procurement.state in ('cancel', 'done'):
4040                 continue
4041             procurement_qty = uom_obj._compute_qty_obj(cr, uid, procurement.product_uom, procurement.product_qty, procurement.product_id.uom_id, context=context)
4042             for move in procurement.move_ids:
4043                 #need to add the moves in draft as they aren't in the virtual quantity + moves that have not been created yet
4044                 if move.state not in ('draft'):
4045                     #if move is already confirmed, assigned or done, the virtual stock is already taking this into account so it shouldn't be deducted
4046                     procurement_qty -= move.product_qty
4047             qty += procurement_qty
4048         return qty
4049
4050     def _check_product_uom(self, cr, uid, ids, context=None):
4051         '''
4052         Check if the UoM has the same category as the product standard UoM
4053         '''
4054         if not context:
4055             context = {}
4056
4057         for rule in self.browse(cr, uid, ids, context=context):
4058             if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
4059                 return False
4060         return True
4061
4062     def action_view_proc_to_process(self, cr, uid, ids, context=None):
4063         act_obj = self.pool.get('ir.actions.act_window')
4064         mod_obj = self.pool.get('ir.model.data')
4065         proc_ids = self.pool.get('procurement.order').search(cr, uid, [('orderpoint_id', 'in', ids), ('state', 'not in', ('done', 'cancel'))], context=context)
4066         result = mod_obj.get_object_reference(cr, uid, 'procurement', 'do_view_procurements')
4067         if not result:
4068             return False
4069
4070         result = act_obj.read(cr, uid, [result[1]], context=context)[0]
4071         result['domain'] = "[('id', 'in', [" + ','.join(map(str, proc_ids)) + "])]"
4072         return result
4073
4074     _columns = {
4075         'name': fields.char('Name', required=True, copy=False),
4076         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
4077         'logic': fields.selection([('max', 'Order to Max'), ('price', 'Best price (not yet active!)')], 'Reordering Mode', required=True),
4078         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
4079         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
4080         'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type', '=', 'product')]),
4081         'product_uom': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Product Unit of Measure', readonly=True, required=True),
4082         'product_min_qty': fields.float('Minimum Quantity', required=True,
4083             digits_compute=dp.get_precision('Product Unit of Measure'),
4084             help="When the virtual stock goes below the Min Quantity specified for this field, Odoo generates "\
4085             "a procurement to bring the forecasted quantity to the Max Quantity."),
4086         'product_max_qty': fields.float('Maximum Quantity', required=True,
4087             digits_compute=dp.get_precision('Product Unit of Measure'),
4088             help="When the virtual stock goes below the Min Quantity, Odoo generates "\
4089             "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
4090         'qty_multiple': fields.float('Qty Multiple', required=True,
4091             digits_compute=dp.get_precision('Product Unit of Measure'),
4092             help="The procurement quantity will be rounded up to this multiple.  If it is 0, the exact quantity will be used.  "),
4093         'procurement_ids': fields.one2many('procurement.order', 'orderpoint_id', 'Created Procurements'),
4094         'group_id': fields.many2one('procurement.group', 'Procurement Group', help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by procurement rules will be grouped into one big picking.", copy=False),
4095         'company_id': fields.many2one('res.company', 'Company', required=True),
4096     }
4097     _defaults = {
4098         'active': lambda *a: 1,
4099         'logic': lambda *a: 'max',
4100         'qty_multiple': lambda *a: 1,
4101         'name': lambda self, cr, uid, context: self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
4102         'product_uom': lambda self, cr, uid, context: context.get('product_uom', False),
4103         'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=context)
4104     }
4105     _sql_constraints = [
4106         ('qty_multiple_check', 'CHECK( qty_multiple >= 0 )', 'Qty Multiple must be greater than or equal to zero.'),
4107     ]
4108     _constraints = [
4109         (_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']),
4110     ]
4111
4112     def default_get(self, cr, uid, fields, context=None):
4113         warehouse_obj = self.pool.get('stock.warehouse')
4114         res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
4115         # default 'warehouse_id' and 'location_id'
4116         if 'warehouse_id' not in res:
4117             warehouse_ids = res.get('company_id') and warehouse_obj.search(cr, uid, [('company_id', '=', res['company_id'])], limit=1, context=context) or []
4118             res['warehouse_id'] = warehouse_ids and warehouse_ids[0] or False
4119         if 'location_id' not in res:
4120             res['location_id'] = res.get('warehouse_id') and warehouse_obj.browse(cr, uid, res['warehouse_id'], context).lot_stock_id.id or False
4121         return res
4122
4123     def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
4124         """ Finds location id for changed warehouse.
4125         @param warehouse_id: Changed id of warehouse.
4126         @return: Dictionary of values.
4127         """
4128         if warehouse_id:
4129             w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
4130             v = {'location_id': w.lot_stock_id.id}
4131             return {'value': v}
4132         return {}
4133
4134     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
4135         """ Finds UoM for changed product.
4136         @param product_id: Changed id of product.
4137         @return: Dictionary of values.
4138         """
4139         if product_id:
4140             prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
4141             d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
4142             v = {'product_uom': prod.uom_id.id}
4143             return {'value': v, 'domain': d}
4144         return {'domain': {'product_uom': []}}
4145
4146 class stock_picking_type(osv.osv):
4147     _name = "stock.picking.type"
4148     _description = "The picking type determines the picking view"
4149     _order = 'sequence'
4150
4151     def open_barcode_interface(self, cr, uid, ids, context=None):
4152         final_url = "/barcode/web/#action=stock.ui&picking_type_id=" + str(ids[0]) if len(ids) else '0'
4153         return {'type': 'ir.actions.act_url', 'url': final_url, 'target': 'self'}
4154
4155     def _get_tristate_values(self, cr, uid, ids, field_name, arg, context=None):
4156         picking_obj = self.pool.get('stock.picking')
4157         res = {}
4158         for picking_type_id in ids:
4159             #get last 10 pickings of this type
4160             picking_ids = picking_obj.search(cr, uid, [('picking_type_id', '=', picking_type_id), ('state', '=', 'done')], order='date_done desc', limit=10, context=context)
4161             tristates = []
4162             for picking in picking_obj.browse(cr, uid, picking_ids, context=context):
4163                 if picking.date_done > picking.date:
4164                     tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Late'), 'value': -1})
4165                 elif picking.backorder_id:
4166                     tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('Backorder exists'), 'value': 0})
4167                 else:
4168                     tristates.insert(0, {'tooltip': picking.name or '' + ": " + _('OK'), 'value': 1})
4169             res[picking_type_id] = json.dumps(tristates)
4170         return res
4171
4172     def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):
4173         obj = self.pool.get('stock.picking')
4174         domains = {
4175             'count_picking_draft': [('state', '=', 'draft')],
4176             'count_picking_waiting': [('state', '=', 'confirmed')],
4177             'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],
4178             'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4179             'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],
4180             'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],
4181         }
4182         result = {}
4183         for field in domains:
4184             data = obj.read_group(cr, uid, domains[field] +
4185                 [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],
4186                 ['picking_type_id'], ['picking_type_id'], context=context)
4187             count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))
4188             for tid in ids:
4189                 result.setdefault(tid, {})[field] = count.get(tid, 0)
4190         for tid in ids:
4191             if result[tid]['count_picking']:
4192                 result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']
4193                 result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']
4194             else:
4195                 result[tid]['rate_picking_late'] = 0
4196                 result[tid]['rate_picking_backorders'] = 0
4197         return result
4198
4199     def onchange_picking_code(self, cr, uid, ids, picking_code=False):
4200         if not picking_code:
4201             return False
4202         
4203         obj_data = self.pool.get('ir.model.data')
4204         stock_loc = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_stock')
4205         
4206         result = {
4207             'default_location_src_id': stock_loc,
4208             'default_location_dest_id': stock_loc,
4209         }
4210         if picking_code == 'incoming':
4211             result['default_location_src_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_suppliers')
4212         elif picking_code == 'outgoing':
4213             result['default_location_dest_id'] = obj_data.xmlid_to_res_id(cr, uid, 'stock.stock_location_customers')
4214         return {'value': result}
4215
4216     def _get_name(self, cr, uid, ids, field_names, arg, context=None):
4217         return dict(self.name_get(cr, uid, ids, context=context))
4218
4219     def name_get(self, cr, uid, ids, context=None):
4220         """Overides orm name_get method to display 'Warehouse_name: PickingType_name' """
4221         if context is None:
4222             context = {}
4223         if not isinstance(ids, list):
4224             ids = [ids]
4225         res = []
4226         if not ids:
4227             return res
4228         for record in self.browse(cr, uid, ids, context=context):
4229             name = record.name
4230             if record.warehouse_id:
4231                 name = record.warehouse_id.name + ': ' +name
4232             if context.get('special_shortened_wh_name'):
4233                 if record.warehouse_id:
4234                     name = record.warehouse_id.name
4235                 else:
4236                     name = _('Customer') + ' (' + record.name + ')'
4237             res.append((record.id, name))
4238         return res
4239
4240     def _default_warehouse(self, cr, uid, context=None):
4241         user = self.pool.get('res.users').browse(cr, uid, uid, context)
4242         res = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
4243         return res and res[0] or False
4244
4245     _columns = {
4246         'name': fields.char('Picking Type Name', translate=True, required=True),
4247         'complete_name': fields.function(_get_name, type='char', string='Name'),
4248         'color': fields.integer('Color'),
4249         'sequence': fields.integer('Sequence', help="Used to order the 'All Operations' kanban view"),
4250         'sequence_id': fields.many2one('ir.sequence', 'Reference Sequence', required=True),
4251         'default_location_src_id': fields.many2one('stock.location', 'Default Source Location'),
4252         'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location'),
4253         'code': fields.selection([('incoming', 'Suppliers'), ('outgoing', 'Customers'), ('internal', 'Internal')], 'Type of Operation', required=True),
4254         'return_picking_type_id': fields.many2one('stock.picking.type', 'Picking Type for Returns'),
4255         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),
4256         'active': fields.boolean('Active'),
4257
4258         # Statistics for the kanban view
4259         'last_done_picking': fields.function(_get_tristate_values,
4260             type='char',
4261             string='Last 10 Done Pickings'),
4262
4263         'count_picking_draft': fields.function(_get_picking_count,
4264             type='integer', multi='_get_picking_count'),
4265         'count_picking_ready': fields.function(_get_picking_count,
4266             type='integer', multi='_get_picking_count'),
4267         'count_picking': fields.function(_get_picking_count,
4268             type='integer', multi='_get_picking_count'),
4269         'count_picking_waiting': fields.function(_get_picking_count,
4270             type='integer', multi='_get_picking_count'),
4271         'count_picking_late': fields.function(_get_picking_count,
4272             type='integer', multi='_get_picking_count'),
4273         'count_picking_backorders': fields.function(_get_picking_count,
4274             type='integer', multi='_get_picking_count'),
4275
4276         'rate_picking_late': fields.function(_get_picking_count,
4277             type='integer', multi='_get_picking_count'),
4278         'rate_picking_backorders': fields.function(_get_picking_count,
4279             type='integer', multi='_get_picking_count'),
4280
4281     }
4282     _defaults = {
4283         'warehouse_id': _default_warehouse,
4284         'active': True,
4285     }
4286
4287 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: