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