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