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