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