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