[FORWARD] Forward port of addons 7.0 until revision 9008
[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 datetime
23 from dateutil.relativedelta import relativedelta
24 import time
25 from operator import itemgetter
26 from itertools import groupby
27
28 from openerp.osv import fields, osv
29 from openerp.tools.translate import _
30 from openerp import netsvc
31 from openerp import tools
32 from openerp.tools import float_compare
33 import openerp.addons.decimal_precision as dp
34 import logging
35 _logger = logging.getLogger(__name__)
36
37 #----------------------------------------------------------
38 # Incoterms
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41     _name = "stock.incoterms"
42     _description = "Incoterms"
43     _columns = {
44         'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms.They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
45         'code': fields.char('Code', size=3, required=True, help="Code for Incoterms"),
46         'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM without deleting it."),
47     }
48     _defaults = {
49         'active': True,
50     }
51
52 stock_incoterms()
53
54 class stock_journal(osv.osv):
55     _name = "stock.journal"
56     _description = "Stock Journal"
57     _columns = {
58         'name': fields.char('Stock Journal', size=32, required=True),
59         'user_id': fields.many2one('res.users', 'Responsible'),
60     }
61     _defaults = {
62         'user_id': lambda s, c, u, ctx: u
63     }
64
65 stock_journal()
66
67 #----------------------------------------------------------
68 # Stock Location
69 #----------------------------------------------------------
70 class stock_location(osv.osv):
71     _name = "stock.location"
72     _description = "Location"
73     _parent_name = "location_id"
74     _parent_store = True
75     _parent_order = 'posz,name'
76     _order = 'parent_left'
77
78     def name_get(self, cr, uid, ids, context=None):
79         # always return the full hierarchical name
80         res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
81         return res.items()
82
83     def _complete_name(self, cr, uid, ids, name, args, context=None):
84         """ Forms complete name of location from parent location to child location.
85         @return: Dictionary of values
86         """
87         res = {}
88         for m in self.browse(cr, uid, ids, context=context):
89             names = [m.name]
90             parent = m.location_id
91             while parent:
92                 names.append(parent.name)
93                 parent = parent.location_id
94             res[m.id] = ' / '.join(reversed(names))
95         return res
96
97     def _get_sublocations(self, cr, uid, ids, context=None):
98         """ return all sublocations of the given stock locations (included) """
99         return self.search(cr, uid, [('id', 'child_of', ids)], context=context)
100
101     def _product_value(self, cr, uid, ids, field_names, arg, context=None):
102         """Computes stock value (real and virtual) for a product, as well as stock qty (real and virtual).
103         @param field_names: Name of field
104         @return: Dictionary of values
105         """
106         prod_id = context and context.get('product_id', False)
107
108         if not prod_id:
109             return dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
110
111         product_product_obj = self.pool.get('product.product')
112
113         cr.execute('select distinct product_id, location_id from stock_move where location_id in %s', (tuple(ids), ))
114         dict1 = cr.dictfetchall()
115         cr.execute('select distinct product_id, location_dest_id as location_id from stock_move where location_dest_id in %s', (tuple(ids), ))
116         dict2 = cr.dictfetchall()
117         res_products_by_location = sorted(dict1+dict2, key=itemgetter('location_id'))
118         products_by_location = dict((k, [v['product_id'] for v in itr]) for k, itr in groupby(res_products_by_location, itemgetter('location_id')))
119
120         result = dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
121         result.update(dict([(i, {}.fromkeys(field_names, 0.0)) for i in list(set([aaa['location_id'] for aaa in res_products_by_location]))]))
122
123         currency_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id
124         currency_obj = self.pool.get('res.currency')
125         currency = currency_obj.browse(cr, uid, currency_id, context=context)
126         for loc_id, product_ids in products_by_location.items():
127             if prod_id:
128                 product_ids = [prod_id]
129             c = (context or {}).copy()
130             c['location'] = loc_id
131             for prod in product_product_obj.browse(cr, uid, product_ids, context=c):
132                 for f in field_names:
133                     if f == 'stock_real':
134                         if loc_id not in result:
135                             result[loc_id] = {}
136                         result[loc_id][f] += prod.qty_available
137                     elif f == 'stock_virtual':
138                         result[loc_id][f] += prod.virtual_available
139                     elif f == 'stock_real_value':
140                         amount = prod.qty_available * prod.standard_price
141                         amount = currency_obj.round(cr, uid, currency, amount)
142                         result[loc_id][f] += amount
143                     elif f == 'stock_virtual_value':
144                         amount = prod.virtual_available * prod.standard_price
145                         amount = currency_obj.round(cr, uid, currency, amount)
146                         result[loc_id][f] += amount
147         return result
148
149     _columns = {
150         'name': fields.char('Location Name', size=64, required=True, translate=True),
151         'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
152         'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
153                  help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
154                        \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
155                        \n* Internal Location: Physical locations inside your own warehouses,
156                        \n* Customer Location: Virtual location representing the destination location for products sent to your customers
157                        \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
158                        \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.
159                        \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
160                       """, select = True),
161          # temporarily removed, as it's unused: 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
162         'complete_name': fields.function(_complete_name, type='char', size=256, string="Location Name",
163                             store={'stock.location': (_get_sublocations, ['name', 'location_id'], 10)}),
164
165         'stock_real': fields.function(_product_value, type='float', string='Real Stock', multi="stock"),
166         'stock_virtual': fields.function(_product_value, type='float', string='Virtual Stock', multi="stock"),
167
168         'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
169         'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
170
171         'chained_journal_id': fields.many2one('stock.journal', 'Chaining Journal',help="Inventory Journal in which the chained move will be written, if the Chaining Type is not Transparent (no journal is used if left empty)"),
172         'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
173         'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
174             'Chained Location Type', required=True,
175             help="Determines whether this location is chained to another location, i.e. any incoming product in this location \n" \
176                 "should next go to the chained location. The chained location is determined according to the type :"\
177                 "\n* None: No chaining at all"\
178                 "\n* Customer: The chained location will be taken from the Customer Location field on the Partner form of the Partner that is specified in the Picking list of the incoming products." \
179                 "\n* Fixed Location: The chained location is taken from the next field: Chained Location if Fixed." \
180                 ),
181         'chained_auto_packing': fields.selection(
182             [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
183             'Chaining Type',
184             required=True,
185             help="This is used only if you select a chained location type.\n" \
186                 "The 'Automatic Move' value will create a stock move after the current one that will be "\
187                 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
188                 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
189             ),
190         'chained_picking_type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', help="Shipping Type of the Picking List that will contain the chained move (leave empty to automatically detect the type based on the source and destination locations)."),
191         'chained_company_id': fields.many2one('res.company', 'Chained Company', help='The company the Picking List containing the chained move will belong to (leave empty to use the default company determination rules'),
192         'chained_delay': fields.integer('Chaining Lead Time',help="Delay between original move and chained move in days"),
193         'partner_id': fields.many2one('res.partner', 'Location Address',help="Address of  customer or supplier."),
194         'icon': fields.selection(tools.icons, 'Icon', size=64,help="Icon show in  hierarchical tree view"),
195
196         'comment': fields.text('Additional Information'),
197         'posx': fields.integer('Corridor (X)',help="Optional localization details, for information purpose only"),
198         'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
199         'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
200
201         'parent_left': fields.integer('Left Parent', select=1),
202         'parent_right': fields.integer('Right Parent', select=1),
203         'stock_real_value': fields.function(_product_value, type='float', string='Real Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
204         'stock_virtual_value': fields.function(_product_value, type='float', string='Virtual Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
205         'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
206         'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'),
207         'valuation_in_account_id': fields.many2one('account.account', 'Stock Valuation Account (Incoming)', domain = [('type','=','other')],
208                                                    help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
209                                                         "this account will be used to hold the value of products being moved from an internal location "
210                                                         "into this location, instead of the generic Stock Output Account set on the product. "
211                                                         "This has no effect for internal locations."),
212         'valuation_out_account_id': fields.many2one('account.account', 'Stock Valuation Account (Outgoing)', domain = [('type','=','other')],
213                                                    help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
214                                                         "this account will be used to hold the value of products being moved out of this location "
215                                                         "and into an internal location, instead of the generic Stock Output Account set on the product. "
216                                                         "This has no effect for internal locations."),
217     }
218     _defaults = {
219         'active': True,
220         'usage': 'internal',
221         'chained_location_type': 'none',
222         'chained_auto_packing': 'manual',
223         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
224         'posx': 0,
225         'posy': 0,
226         'posz': 0,
227         'icon': False,
228         'scrap_location': False,
229     }
230
231     def chained_location_get(self, cr, uid, location, partner=None, product=None, context=None):
232         """ Finds chained location
233         @param location: Location id
234         @param partner: Partner id
235         @param product: Product id
236         @return: List of values
237         """
238         result = None
239         if location.chained_location_type == 'customer':
240             if partner:
241                 result = partner.property_stock_customer
242         elif location.chained_location_type == 'fixed':
243             result = location.chained_location_id
244         if result:
245             return result, location.chained_auto_packing, location.chained_delay, location.chained_journal_id and location.chained_journal_id.id or False, location.chained_company_id and location.chained_company_id.id or False, location.chained_picking_type, False
246         return result
247
248     def picking_type_get(self, cr, uid, from_location, to_location, context=None):
249         """ Gets type of picking.
250         @param from_location: Source location
251         @param to_location: Destination location
252         @return: Location type
253         """
254         result = 'internal'
255         if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
256             result = 'out'
257         elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage == 'internal'):
258             result = 'in'
259         return result
260
261     def _product_get_all_report(self, cr, uid, ids, product_ids=False, context=None):
262         return self._product_get_report(cr, uid, ids, product_ids, context, recursive=True)
263
264     def _product_get_report(self, cr, uid, ids, product_ids=False,
265             context=None, recursive=False):
266         """ Finds the product quantity and price for particular location.
267         @param product_ids: Ids of product
268         @param recursive: True or False
269         @return: Dictionary of values
270         """
271         if context is None:
272             context = {}
273         product_obj = self.pool.get('product.product')
274         # Take the user company and pricetype
275         context['currency_id'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
276
277         # To be able to offer recursive or non-recursive reports we need to prevent recursive quantities by default
278         context['compute_child'] = False
279
280         if not product_ids:
281             product_ids = product_obj.search(cr, uid, [], context={'active_test': False})
282
283         products = product_obj.browse(cr, uid, product_ids, context=context)
284         products_by_uom = {}
285         products_by_id = {}
286         for product in products:
287             products_by_uom.setdefault(product.uom_id.id, [])
288             products_by_uom[product.uom_id.id].append(product)
289             products_by_id.setdefault(product.id, [])
290             products_by_id[product.id] = product
291
292         result = {}
293         result['product'] = []
294         for id in ids:
295             quantity_total = 0.0
296             total_price = 0.0
297             for uom_id in products_by_uom.keys():
298                 fnc = self._product_get
299                 if recursive:
300                     fnc = self._product_all_get
301                 ctx = context.copy()
302                 ctx['uom'] = uom_id
303                 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
304                         context=ctx)
305                 for product_id in qty.keys():
306                     if not qty[product_id]:
307                         continue
308                     product = products_by_id[product_id]
309                     quantity_total += qty[product_id]
310
311                     # Compute based on pricetype
312                     # Choose the right filed standard_price to read
313                     amount_unit = product.price_get('standard_price', context=context)[product.id]
314                     price = qty[product_id] * amount_unit
315
316                     total_price += price
317                     result['product'].append({
318                         'price': amount_unit,
319                         'prod_name': product.name,
320                         'code': product.default_code, # used by lot_overview_all report!
321                         'variants': product.variants or '',
322                         'uom': product.uom_id.name,
323                         'prod_qty': qty[product_id],
324                         'price_value': price,
325                     })
326         result['total'] = quantity_total
327         result['total_price'] = total_price
328         return result
329
330     def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context=None,
331                                     states=['done'], what=('in', 'out')):
332         """
333         @param product_ids: Ids of product
334         @param states: List of states
335         @param what: Tuple of
336         @return:
337         """
338         product_obj = self.pool.get('product.product')
339         if context is None:
340             context = {}
341         context.update({
342             'states': states,
343             'what': what,
344             'location': ids
345         })
346         return product_obj.get_product_available(cr, uid, product_ids, context=context)
347
348     def _product_get(self, cr, uid, id, product_ids=False, context=None, states=None):
349         """
350         @param product_ids:
351         @param states:
352         @return:
353         """
354         if states is None:
355             states = ['done']
356         ids = id and [id] or []
357         return self._product_get_multi_location(cr, uid, ids, product_ids, context=context, states=states)
358
359     def _product_all_get(self, cr, uid, id, product_ids=False, context=None, states=None):
360         if states is None:
361             states = ['done']
362         # build the list of ids of children of the location given by id
363         ids = id and [id] or []
364         location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
365         return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
366
367     def _product_virtual_get(self, cr, uid, id, product_ids=False, context=None, states=None):
368         if states is None:
369             states = ['done']
370         return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
371
372     def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None, lock=False):
373         """
374         Attempt to find a quantity ``product_qty`` (in the product's default uom or the uom passed in ``context``) of product ``product_id``
375         in locations with id ``ids`` and their child locations. If ``lock`` is True, the stock.move lines
376         of product with id ``product_id`` in the searched location will be write-locked using Postgres's
377         "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back, to prevent reservin
378         twice the same products.
379         If ``lock`` is True and the lock cannot be obtained (because another transaction has locked some of
380         the same stock.move lines), a log line will be output and False will be returned, as if there was
381         not enough stock.
382
383         :param product_id: Id of product to reserve
384         :param product_qty: Quantity of product to reserve (in the product's default uom or the uom passed in ``context``)
385         :param lock: if True, the stock.move lines of product with id ``product_id`` in all locations (and children locations) with ``ids`` will
386                      be write-locked using postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back. This is
387                      to prevent reserving twice the same products.
388         :param context: optional context dictionary: if a 'uom' key is present it will be used instead of the default product uom to
389                         compute the ``product_qty`` and in the return value.
390         :return: List of tuples in the form (qty, location_id) with the (partial) quantities that can be taken in each location to
391                  reach the requested product_qty (``qty`` is expressed in the default uom of the product), of False if enough
392                  products could not be found, or the lock could not be obtained (and ``lock`` was True).
393         """
394         result = []
395         amount = 0.0
396         if context is None:
397             context = {}
398         uom_obj = self.pool.get('product.uom')
399         uom_rounding = self.pool.get('product.product').browse(cr, uid, product_id, context=context).uom_id.rounding
400         if context.get('uom'):
401             uom_rounding = uom_obj.browse(cr, uid, context.get('uom'), context=context).rounding
402         for id in self.search(cr, uid, [('location_id', 'child_of', ids)]):
403             if lock:
404                 try:
405                     # Must lock with a separate select query because FOR UPDATE can't be used with
406                     # aggregation/group by's (when individual rows aren't identifiable).
407                     # We use a SAVEPOINT to be able to rollback this part of the transaction without
408                     # failing the whole transaction in case the LOCK cannot be acquired.
409                     cr.execute("SAVEPOINT stock_location_product_reserve")
410                     cr.execute("""SELECT id FROM stock_move
411                                   WHERE product_id=%s AND
412                                           (
413                                             (location_dest_id=%s AND
414                                              location_id<>%s AND
415                                              state='done')
416                                             OR
417                                             (location_id=%s AND
418                                              location_dest_id<>%s AND
419                                              state in ('done', 'assigned'))
420                                           )
421                                   FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False)
422                 except Exception:
423                     # Here it's likely that the FOR UPDATE NOWAIT failed to get the LOCK,
424                     # so we ROLLBACK to the SAVEPOINT to restore the transaction to its earlier
425                     # state, we return False as if the products were not available, and log it:
426                     cr.execute("ROLLBACK TO stock_location_product_reserve")
427                     _logger.warning("Failed attempt to reserve %s x product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_qty, product_id)
428                     _logger.debug("Trace of the failed product reservation attempt: ", exc_info=True)
429                     return False
430
431             # XXX TODO: rewrite this with one single query, possibly even the quantity conversion
432             cr.execute("""SELECT product_uom, sum(product_qty) AS product_qty
433                           FROM stock_move
434                           WHERE location_dest_id=%s AND
435                                 location_id<>%s AND
436                                 product_id=%s AND
437                                 state='done'
438                           GROUP BY product_uom
439                        """,
440                        (id, id, product_id))
441             results = cr.dictfetchall()
442             cr.execute("""SELECT product_uom,-sum(product_qty) AS product_qty
443                           FROM stock_move
444                           WHERE location_id=%s AND
445                                 location_dest_id<>%s AND
446                                 product_id=%s AND
447                                 state in ('done', 'assigned')
448                           GROUP BY product_uom
449                        """,
450                        (id, id, product_id))
451             results += cr.dictfetchall()
452             total = 0.0
453             results2 = 0.0
454             for r in results:
455                 amount = uom_obj._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
456                 results2 += amount
457                 total += amount
458             if total <= 0.0:
459                 continue
460
461             amount = results2
462             compare_qty = float_compare(amount, 0, precision_rounding=uom_rounding)
463             if compare_qty == 1:
464                 if amount > min(total, product_qty):
465                     amount = min(product_qty, total)
466                 result.append((amount, id))
467                 product_qty -= amount
468                 total -= amount
469                 if product_qty <= 0.0:
470                     return result
471                 if total <= 0.0:
472                     continue
473         return False
474
475 stock_location()
476
477
478 class stock_tracking(osv.osv):
479     _name = "stock.tracking"
480     _description = "Packs"
481
482     def checksum(sscc):
483         salt = '31' * 8 + '3'
484         sum = 0
485         for sscc_part, salt_part in zip(sscc, salt):
486             sum += int(sscc_part) * int(salt_part)
487         return (10 - (sum % 10)) % 10
488     checksum = staticmethod(checksum)
489
490     def make_sscc(self, cr, uid, context=None):
491         sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
492         try:
493             return sequence + str(self.checksum(sequence))
494         except Exception:
495             return sequence
496
497     _columns = {
498         'name': fields.char('Pack Reference', size=64, required=True, select=True, help="By default, the pack reference is generated following the sscc standard. (Serial number + 1 check digit)"),
499         'active': fields.boolean('Active', help="By unchecking the active field, you may hide a pack without deleting it."),
500         'serial': fields.char('Additional Reference', size=64, select=True, help="Other reference or serial number"),
501         'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves for this pack', readonly=True),
502         'date': fields.datetime('Creation Date', required=True),
503     }
504     _defaults = {
505         'active': 1,
506         'name': make_sscc,
507         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
508     }
509
510     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
511         if not args:
512             args = []
513         ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
514         ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
515         return self.name_get(cr, user, ids, context)
516
517     def name_get(self, cr, uid, ids, context=None):
518         """Append the serial to the name"""
519         if not len(ids):
520             return []
521         res = [ (r['id'], r['serial'] and '%s [%s]' % (r['name'], r['serial'])
522                                       or r['name'] )
523                 for r in self.read(cr, uid, ids, ['name', 'serial'],
524                                    context=context) ]
525         return res
526
527     def unlink(self, cr, uid, ids, context=None):
528         raise osv.except_osv(_('Error!'), _('You cannot remove a lot line.'))
529
530     def action_traceability(self, cr, uid, ids, context=None):
531         """ It traces the information of a product
532         @param self: The object pointer.
533         @param cr: A database cursor
534         @param uid: ID of the user currently logged in
535         @param ids: List of IDs selected
536         @param context: A standard dictionary
537         @return: A dictionary of values
538         """
539         return self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
540
541 stock_tracking()
542
543 #----------------------------------------------------------
544 # Stock Picking
545 #----------------------------------------------------------
546 class stock_picking(osv.osv):
547     _name = "stock.picking"
548     _inherit = ['mail.thread']
549     _description = "Picking List"
550
551     def _set_maximum_date(self, cr, uid, ids, name, value, arg, context=None):
552         """ Calculates planned date if it is greater than 'value'.
553         @param name: Name of field
554         @param value: Value of field
555         @param arg: User defined argument
556         @return: True or False
557         """
558         if not value:
559             return False
560         if isinstance(ids, (int, long)):
561             ids = [ids]
562         for pick in self.browse(cr, uid, ids, context=context):
563             sql_str = """update stock_move set
564                     date='%s'
565                 where
566                     picking_id=%d """ % (value, pick.id)
567
568             if pick.max_date:
569                 sql_str += " and (date='" + pick.max_date + "' or date>'" + value + "')"
570             cr.execute(sql_str)
571         return True
572
573     def _set_minimum_date(self, cr, uid, ids, name, value, arg, context=None):
574         """ Calculates planned date if it is less than 'value'.
575         @param name: Name of field
576         @param value: Value of field
577         @param arg: User defined argument
578         @return: True or False
579         """
580         if not value:
581             return False
582         if isinstance(ids, (int, long)):
583             ids = [ids]
584         for pick in self.browse(cr, uid, ids, context=context):
585             sql_str = """update stock_move set
586                     date='%s'
587                 where
588                     picking_id=%s """ % (value, pick.id)
589             if pick.min_date:
590                 sql_str += " and (date='" + pick.min_date + "' or date<'" + value + "')"
591             cr.execute(sql_str)
592         return True
593
594     def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
595         """ Finds minimum and maximum dates for picking.
596         @return: Dictionary of values
597         """
598         res = {}
599         for id in ids:
600             res[id] = {'min_date': False, 'max_date': False}
601         if not ids:
602             return res
603         cr.execute("""select
604                 picking_id,
605                 min(date_expected),
606                 max(date_expected)
607             from
608                 stock_move
609             where
610                 picking_id IN %s
611             group by
612                 picking_id""",(tuple(ids),))
613         for pick, dt1, dt2 in cr.fetchall():
614             res[pick]['min_date'] = dt1
615             res[pick]['max_date'] = dt2
616         return res
617
618     def create(self, cr, user, vals, context=None):
619         if ('name' not in vals) or (vals.get('name')=='/') or (vals.get('name') == False):
620             seq_obj_name =  self._name
621             vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
622         new_id = super(stock_picking, self).create(cr, user, vals, context)
623         return new_id
624
625     _columns = {
626         'name': fields.char('Reference', size=64, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
627         'origin': fields.char('Source Document', size=64, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Reference of the document", select=True),
628         '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),
629         'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."),
630         'note': fields.text('Notes', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
631         'stock_journal_id': fields.many2one('stock.journal','Stock Journal', select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
632         'location_id': fields.many2one('stock.location', 'Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Keep empty if you produce at the location where the finished products are needed." \
633                 "Set a location if you produce at a fixed location. This can be a partner location " \
634                 "if you subcontract the manufacturing operations.", select=True),
635         'location_dest_id': fields.many2one('stock.location', 'Dest. Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Location where the system will stock the finished products.", select=True),
636         '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"),
637         'state': fields.selection([
638             ('draft', 'Draft'),
639             ('cancel', 'Cancelled'),
640             ('auto', 'Waiting Another Operation'),
641             ('confirmed', 'Waiting Availability'),
642             ('assigned', 'Ready to Transfer'),
643             ('done', 'Transferred'),
644             ], 'Status', readonly=True, select=True, track_visibility='onchange', help="""
645             * Draft: not confirmed yet and will not be scheduled until confirmed\n
646             * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
647             * Waiting Availability: still waiting for the availability of products\n
648             * Ready to Transfer: products reserved, simply waiting for confirmation.\n
649             * Transferred: has been processed, can't be modified or cancelled anymore\n
650             * Cancelled: has been cancelled, can't be confirmed anymore"""
651         ),
652         'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
653                  store=True, type='datetime', string='Scheduled Time', select=1, help="Scheduled time for the shipment to be processed"),
654         'date': fields.datetime('Time', help="Creation time, usually the time of the order.", select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
655         'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
656         'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
657                  store=True, type='datetime', string='Max. Expected Date', select=2),
658         'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
659         'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
660         'auto_picking': fields.boolean('Auto-Picking', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
661         'partner_id': fields.many2one('res.partner', 'Partner', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
662         'invoice_state': fields.selection([
663             ("invoiced", "Invoiced"),
664             ("2binvoiced", "To Be Invoiced"),
665             ("none", "Not Applicable")], "Invoice Control",
666             select=True, required=True, readonly=True, track_visibility='onchange', states={'draft': [('readonly', False)]}),
667         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
668     }
669     _defaults = {
670         'name': lambda self, cr, uid, context: '/',
671         'state': 'draft',
672         'move_type': 'direct',
673         'type': 'internal',
674         'invoice_state': 'none',
675         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
676         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
677     }
678     _sql_constraints = [
679         ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per Company!'),
680     ]
681
682     def action_process(self, cr, uid, ids, context=None):
683         if context is None:
684             context = {}
685         """Open the partial picking wizard"""
686         context.update({
687             'active_model': self._name,
688             'active_ids': ids,
689             'active_id': len(ids) and ids[0] or False
690         })
691         return {
692             'view_type': 'form',
693             'view_mode': 'form',
694             'res_model': 'stock.partial.picking',
695             'type': 'ir.actions.act_window',
696             'target': 'new',
697             'context': context,
698             'nodestroy': True,
699         }
700
701     def copy(self, cr, uid, id, default=None, context=None):
702         if default is None:
703             default = {}
704         default = default.copy()
705         picking_obj = self.browse(cr, uid, id, context=context)
706         move_obj = self.pool.get('stock.move')
707         if ('name' not in default) or (picking_obj.name == '/'):
708             seq_obj_name = 'stock.picking.' + picking_obj.type
709             default['name'] = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
710             default['origin'] = ''
711             default['backorder_id'] = False
712         if 'invoice_state' not in default and picking_obj.invoice_state == 'invoiced':
713             default['invoice_state'] = '2binvoiced'
714         res = super(stock_picking, self).copy(cr, uid, id, default, context)
715         if res:
716             picking_obj = self.browse(cr, uid, res, context=context)
717             for move in picking_obj.move_lines:
718                 move_obj.write(cr, uid, [move.id], {'tracking_id': False, 'prodlot_id': False, 'move_history_ids2': [(6, 0, [])], 'move_history_ids': [(6, 0, [])]})
719         return res
720
721     def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
722         if view_type == 'form' and not view_id:
723             mod_obj = self.pool.get('ir.model.data')
724             if self._name == "stock.picking.in":
725                 model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_in_form')
726             if self._name == "stock.picking.out":
727                 model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_out_form')
728         return super(stock_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
729
730     def onchange_partner_in(self, cr, uid, ids, partner_id=None, context=None):
731         return {}
732
733     def action_explode(self, cr, uid, moves, context=None):
734         """Hook to allow other modules to split the moves of a picking."""
735         return moves
736
737     def action_confirm(self, cr, uid, ids, context=None):
738         """ Confirms picking.
739         @return: True
740         """
741         pickings = self.browse(cr, uid, ids, context=context)
742         self.write(cr, uid, ids, {'state': 'confirmed'})
743         todo = []
744         for picking in pickings:
745             for r in picking.move_lines:
746                 if r.state == 'draft':
747                     todo.append(r.id)
748         todo = self.action_explode(cr, uid, todo, context)
749         if len(todo):
750             self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
751         return True
752
753     def test_auto_picking(self, cr, uid, ids):
754         # TODO: Check locations to see if in the same location ?
755         return True
756
757     def action_assign(self, cr, uid, ids, *args):
758         """ Changes state of picking to available if all moves are confirmed.
759         @return: True
760         """
761         for pick in self.browse(cr, uid, ids):
762             if pick.state == 'draft':
763                 self.signal_button_confirm(cr, uid, [pick.id])
764             move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
765             if not move_ids:
766                 raise osv.except_osv(_('Warning!'),_('Not enough stock, unable to reserve the products.'))
767             self.pool.get('stock.move').action_assign(cr, uid, move_ids)
768         return True
769
770     def force_assign(self, cr, uid, ids, *args):
771         """ Changes state of picking to available if moves are confirmed or waiting.
772         @return: True
773         """
774         wf_service = netsvc.LocalService("workflow")
775         for pick in self.browse(cr, uid, ids):
776             move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
777             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
778             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
779         return True
780
781     def draft_force_assign(self, cr, uid, ids, *args):
782         """ Confirms picking directly from draft state.
783         @return: True
784         """
785         for pick in self.browse(cr, uid, ids):
786             if not pick.move_lines:
787                 raise osv.except_osv(_('Error!'),_('You cannot process picking without stock moves.'))
788             self.signal_button_confirm(cr, uid, [pick.id])
789         return True
790
791     def draft_validate(self, cr, uid, ids, context=None):
792         """ Validates picking directly from draft state.
793         @return: True
794         """
795         wf_service = netsvc.LocalService("workflow")
796         self.draft_force_assign(cr, uid, ids)
797         for pick in self.browse(cr, uid, ids, context=context):
798             move_ids = [x.id for x in pick.move_lines]
799             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
800             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
801         return self.action_process(
802             cr, uid, ids, context=context)
803     def cancel_assign(self, cr, uid, ids, *args):
804         """ Cancels picking and moves.
805         @return: True
806         """
807         wf_service = netsvc.LocalService("workflow")
808         for pick in self.browse(cr, uid, ids):
809             move_ids = [x.id for x in pick.move_lines]
810             self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
811             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
812         return True
813
814     def action_assign_wkf(self, cr, uid, ids, context=None):
815         """ Changes picking state to assigned.
816         @return: True
817         """
818         self.write(cr, uid, ids, {'state': 'assigned'})
819         return True
820
821     def test_finished(self, cr, uid, ids):
822         """ Tests whether the move is in done or cancel state or not.
823         @return: True or False
824         """
825         move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
826         for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
827             if move.state not in ('done', 'cancel'):
828
829                 if move.product_qty != 0.0:
830                     return False
831                 else:
832                     move.write({'state': 'done'})
833         return True
834
835     def test_assigned(self, cr, uid, ids):
836         """ Tests whether the move is in assigned state or not.
837         @return: True or False
838         """
839         #TOFIX: assignment of move lines should be call before testing assigment otherwise picking never gone in assign state
840         ok = True
841         for pick in self.browse(cr, uid, ids):
842             mt = pick.move_type
843             # incomming shipments are always set as available if they aren't chained
844             if pick.type == 'in':
845                 if all([x.state != 'waiting' for x in pick.move_lines]):
846                     return True
847             for move in pick.move_lines:
848                 if (move.state in ('confirmed', 'draft')) and (mt == 'one'):
849                     return False
850                 if (mt == 'direct') and (move.state == 'assigned') and (move.product_qty):
851                     return True
852                 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
853         return ok
854
855     def action_cancel(self, cr, uid, ids, context=None):
856         """ Changes picking state to cancel.
857         @return: True
858         """
859         for pick in self.browse(cr, uid, ids, context=context):
860             ids2 = [move.id for move in pick.move_lines]
861             self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
862         self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
863         return True
864
865     #
866     # TODO: change and create a move if not parents
867     #
868     def action_done(self, cr, uid, ids, context=None):
869         """Changes picking state to done.
870         
871         This method is called at the end of the workflow by the activity "done".
872         @return: True
873         """
874         self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
875         return True
876
877     def action_move(self, cr, uid, ids, context=None):
878         """Process the Stock Moves of the Picking
879         
880         This method is called by the workflow by the activity "move".
881         Normally that happens when the signal button_done is received (button 
882         "Done" pressed on a Picking view). 
883         @return: True
884         """
885         for pick in self.browse(cr, uid, ids, context=context):
886             todo = []
887             for move in pick.move_lines:
888                 if move.state == 'draft':
889                     self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
890                         context=context)
891                     todo.append(move.id)
892                 elif move.state in ('assigned','confirmed'):
893                     todo.append(move.id)
894             if len(todo):
895                 self.pool.get('stock.move').action_done(cr, uid, todo,
896                         context=context)
897         return True
898
899     def get_currency_id(self, cr, uid, picking):
900         return False
901
902     def _get_partner_to_invoice(self, cr, uid, picking, context=None):
903         """ Gets the partner that will be invoiced
904             Note that this function is inherited in the sale and purchase modules
905             @param picking: object of the picking for which we are selecting the partner to invoice
906             @return: object of the partner to invoice
907         """
908         return picking.partner_id and picking.partner_id.id
909
910     def _get_comment_invoice(self, cr, uid, picking):
911         """
912         @return: comment string for invoice
913         """
914         return picking.note or ''
915
916     def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None):
917         """ Gets price unit for invoice
918         @param move_line: Stock move lines
919         @param type: Type of invoice
920         @return: The price unit for the move line
921         """
922         if context is None:
923             context = {}
924
925         if type in ('in_invoice', 'in_refund'):
926             # Take the user company and pricetype
927             context['currency_id'] = move_line.company_id.currency_id.id
928             amount_unit = move_line.product_id.price_get('standard_price', context=context)[move_line.product_id.id]
929             return amount_unit
930         else:
931             return move_line.product_id.list_price
932
933     def _get_discount_invoice(self, cr, uid, move_line):
934         '''Return the discount for the move line'''
935         return 0.0
936
937     def _get_taxes_invoice(self, cr, uid, move_line, type):
938         """ Gets taxes on invoice
939         @param move_line: Stock move lines
940         @param type: Type of invoice
941         @return: Taxes Ids for the move line
942         """
943         if type in ('in_invoice', 'in_refund'):
944             taxes = move_line.product_id.supplier_taxes_id
945         else:
946             taxes = move_line.product_id.taxes_id
947
948         if move_line.picking_id and move_line.picking_id.partner_id and move_line.picking_id.partner_id.id:
949             return self.pool.get('account.fiscal.position').map_tax(
950                 cr,
951                 uid,
952                 move_line.picking_id.partner_id.property_account_position,
953                 taxes
954             )
955         else:
956             return map(lambda x: x.id, taxes)
957
958     def _get_account_analytic_invoice(self, cr, uid, picking, move_line):
959         return False
960
961     def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
962         '''Call after the creation of the invoice line'''
963         return
964
965     def _invoice_hook(self, cr, uid, picking, invoice_id):
966         '''Call after the creation of the invoice'''
967         return
968
969     def _get_invoice_type(self, pick):
970         src_usage = dest_usage = None
971         inv_type = None
972         if pick.invoice_state == '2binvoiced':
973             if pick.move_lines:
974                 src_usage = pick.move_lines[0].location_id.usage
975                 dest_usage = pick.move_lines[0].location_dest_id.usage
976             if pick.type == 'out' and dest_usage == 'supplier':
977                 inv_type = 'in_refund'
978             elif pick.type == 'out' and dest_usage == 'customer':
979                 inv_type = 'out_invoice'
980             elif pick.type == 'in' and src_usage == 'supplier':
981                 inv_type = 'in_invoice'
982             elif pick.type == 'in' and src_usage == 'customer':
983                 inv_type = 'out_refund'
984             else:
985                 inv_type = 'out_invoice'
986         return inv_type
987
988     def _prepare_invoice_group(self, cr, uid, picking, partner, invoice, context=None):
989         """ Builds the dict for grouped invoices
990             @param picking: picking object
991             @param partner: object of the partner to invoice (not used here, but may be usefull if this function is inherited)
992             @param invoice: object of the invoice that we are updating
993             @return: dict that will be used to update the invoice
994         """
995         comment = self._get_comment_invoice(cr, uid, picking)
996         return {
997             'name': (invoice.name or '') + ', ' + (picking.name or ''),
998             'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
999             'comment': (comment and (invoice.comment and invoice.comment + "\n" + comment or comment)) or (invoice.comment and invoice.comment or ''),
1000             'date_invoice': context.get('date_inv', False),
1001             'user_id': uid,
1002         }
1003
1004     def _prepare_invoice(self, cr, uid, picking, partner, inv_type, journal_id, context=None):
1005         """ Builds the dict containing the values for the invoice
1006             @param picking: picking object
1007             @param partner: object of the partner to invoice
1008             @param inv_type: type of the invoice ('out_invoice', 'in_invoice', ...)
1009             @param journal_id: ID of the accounting journal
1010             @return: dict that will be used to create the invoice object
1011         """
1012         if isinstance(partner, int):
1013             partner = self.pool.get('res.partner').browse(cr, uid, partner, context=context)
1014         if inv_type in ('out_invoice', 'out_refund'):
1015             account_id = partner.property_account_receivable.id
1016             payment_term = partner.property_payment_term.id or False
1017         else:
1018             account_id = partner.property_account_payable.id
1019             payment_term = partner.property_supplier_payment_term.id or False
1020         comment = self._get_comment_invoice(cr, uid, picking)
1021         invoice_vals = {
1022             'name': picking.name,
1023             'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
1024             'type': inv_type,
1025             'account_id': account_id,
1026             'partner_id': partner.id,
1027             'comment': comment,
1028             'payment_term': payment_term,
1029             'fiscal_position': partner.property_account_position.id,
1030             'date_invoice': context.get('date_inv', False),
1031             'company_id': picking.company_id.id,
1032             'user_id': uid,
1033         }
1034         cur_id = self.get_currency_id(cr, uid, picking)
1035         if cur_id:
1036             invoice_vals['currency_id'] = cur_id
1037         if journal_id:
1038             invoice_vals['journal_id'] = journal_id
1039         return invoice_vals
1040
1041     def _prepare_invoice_line(self, cr, uid, group, picking, move_line, invoice_id,
1042         invoice_vals, context=None):
1043         """ Builds the dict containing the values for the invoice line
1044             @param group: True or False
1045             @param picking: picking object
1046             @param: move_line: move_line object
1047             @param: invoice_id: ID of the related invoice
1048             @param: invoice_vals: dict used to created the invoice
1049             @return: dict that will be used to create the invoice line
1050         """
1051         if group:
1052             name = (picking.name or '') + '-' + move_line.name
1053         else:
1054             name = move_line.name
1055         origin = move_line.picking_id.name or ''
1056         if move_line.picking_id.origin:
1057             origin += ':' + move_line.picking_id.origin
1058
1059         if invoice_vals['type'] in ('out_invoice', 'out_refund'):
1060             account_id = move_line.product_id.property_account_income.id
1061             if not account_id:
1062                 account_id = move_line.product_id.categ_id.\
1063                         property_account_income_categ.id
1064         else:
1065             account_id = move_line.product_id.property_account_expense.id
1066             if not account_id:
1067                 account_id = move_line.product_id.categ_id.\
1068                         property_account_expense_categ.id
1069         if invoice_vals['fiscal_position']:
1070             fp_obj = self.pool.get('account.fiscal.position')
1071             fiscal_position = fp_obj.browse(cr, uid, invoice_vals['fiscal_position'], context=context)
1072             account_id = fp_obj.map_account(cr, uid, fiscal_position, account_id)
1073         # set UoS if it's a sale and the picking doesn't have one
1074         uos_id = move_line.product_uos and move_line.product_uos.id or False
1075         if not uos_id and invoice_vals['type'] in ('out_invoice', 'out_refund'):
1076             uos_id = move_line.product_uom.id
1077
1078         return {
1079             'name': name,
1080             'origin': origin,
1081             'invoice_id': invoice_id,
1082             'uos_id': uos_id,
1083             'product_id': move_line.product_id.id,
1084             'account_id': account_id,
1085             'price_unit': self._get_price_unit_invoice(cr, uid, move_line, invoice_vals['type']),
1086             'discount': self._get_discount_invoice(cr, uid, move_line),
1087             'quantity': move_line.product_uos_qty or move_line.product_qty,
1088             'invoice_line_tax_id': [(6, 0, self._get_taxes_invoice(cr, uid, move_line, invoice_vals['type']))],
1089             'account_analytic_id': self._get_account_analytic_invoice(cr, uid, picking, move_line),
1090         }
1091
1092     def action_invoice_create(self, cr, uid, ids, journal_id=False,
1093             group=False, type='out_invoice', context=None):
1094         """ Creates invoice based on the invoice state selected for picking.
1095         @param journal_id: Id of journal
1096         @param group: Whether to create a group invoice or not
1097         @param type: Type invoice to be created
1098         @return: Ids of created invoices for the pickings
1099         """
1100         if context is None:
1101             context = {}
1102
1103         invoice_obj = self.pool.get('account.invoice')
1104         invoice_line_obj = self.pool.get('account.invoice.line')
1105         partner_obj = self.pool.get('res.partner')
1106         invoices_group = {}
1107         res = {}
1108         inv_type = type
1109         for picking in self.browse(cr, uid, ids, context=context):
1110             if picking.invoice_state != '2binvoiced':
1111                 continue
1112             partner = self._get_partner_to_invoice(cr, uid, picking, context=context)
1113             if isinstance(partner, int):
1114                 partner = partner_obj.browse(cr, uid, [partner], context=context)[0]
1115             if not partner:
1116                 raise osv.except_osv(_('Error, no partner !'),
1117                     _('Please put a partner on the picking list if you want to generate invoice.'))
1118
1119             if not inv_type:
1120                 inv_type = self._get_invoice_type(picking)
1121
1122             if group and partner.id in invoices_group:
1123                 invoice_id = invoices_group[partner.id]
1124                 invoice = invoice_obj.browse(cr, uid, invoice_id)
1125                 invoice_vals_group = self._prepare_invoice_group(cr, uid, picking, partner, invoice, context=context)
1126                 invoice_obj.write(cr, uid, [invoice_id], invoice_vals_group, context=context)
1127             else:
1128                 invoice_vals = self._prepare_invoice(cr, uid, picking, partner, inv_type, journal_id, context=context)
1129                 invoice_id = invoice_obj.create(cr, uid, invoice_vals, context=context)
1130                 invoices_group[partner.id] = invoice_id
1131             res[picking.id] = invoice_id
1132             for move_line in picking.move_lines:
1133                 if move_line.state == 'cancel':
1134                     continue
1135                 if move_line.scrapped:
1136                     # do no invoice scrapped products
1137                     continue
1138                 vals = self._prepare_invoice_line(cr, uid, group, picking, move_line,
1139                                 invoice_id, invoice_vals, context=context)
1140                 if vals:
1141                     invoice_line_id = invoice_line_obj.create(cr, uid, vals, context=context)
1142                     self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
1143
1144             invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
1145                     set_total=(inv_type in ('in_invoice', 'in_refund')))
1146             self.write(cr, uid, [picking.id], {
1147                 'invoice_state': 'invoiced',
1148                 }, context=context)
1149             self._invoice_hook(cr, uid, picking, invoice_id)
1150         self.write(cr, uid, res.keys(), {
1151             'invoice_state': 'invoiced',
1152             }, context=context)
1153         return res
1154
1155     def test_done(self, cr, uid, ids, context=None):
1156         """ Test whether the move lines are done or not.
1157         @return: True or False
1158         """
1159         ok = False
1160         for pick in self.browse(cr, uid, ids, context=context):
1161             if not pick.move_lines:
1162                 return True
1163             for move in pick.move_lines:
1164                 if move.state not in ('cancel','done'):
1165                     return False
1166                 if move.state=='done':
1167                     ok = True
1168         return ok
1169
1170     def test_cancel(self, cr, uid, ids, context=None):
1171         """ Test whether the move lines are canceled or not.
1172         @return: True or False
1173         """
1174         for pick in self.browse(cr, uid, ids, context=context):
1175             for move in pick.move_lines:
1176                 if move.state not in ('cancel',):
1177                     return False
1178         return True
1179
1180     def allow_cancel(self, cr, uid, ids, context=None):
1181         for pick in self.browse(cr, uid, ids, context=context):
1182             if not pick.move_lines:
1183                 return True
1184             for move in pick.move_lines:
1185                 if move.state == 'done':
1186                     raise osv.except_osv(_('Error!'), _('You cannot cancel the picking as some moves have been done. You should cancel the picking lines.'))
1187         return True
1188
1189     def unlink(self, cr, uid, ids, context=None):
1190         move_obj = self.pool.get('stock.move')
1191         if context is None:
1192             context = {}
1193         for pick in self.browse(cr, uid, ids, context=context):
1194             if pick.state in ['done','cancel']:
1195                 raise osv.except_osv(_('Error!'), _('You cannot remove the picking which is in %s state!')%(pick.state,))
1196             else:
1197                 ids2 = [move.id for move in pick.move_lines]
1198                 ctx = context.copy()
1199                 ctx.update({'call_unlink':True})
1200                 if pick.state != 'draft':
1201                     #Cancelling the move in order to affect Virtual stock of product
1202                     move_obj.action_cancel(cr, uid, ids2, ctx)
1203                 #Removing the move
1204                 move_obj.unlink(cr, uid, ids2, ctx)
1205
1206         return super(stock_picking, self).unlink(cr, uid, ids, context=context)
1207
1208     # FIXME: needs refactoring, this code is partially duplicated in stock_move.do_partial()!
1209     def do_partial(self, cr, uid, ids, partial_datas, context=None):
1210         """ Makes partial picking and moves done.
1211         @param partial_datas : Dictionary containing details of partial picking
1212                           like partner_id, partner_id, delivery_date,
1213                           delivery moves with product_id, product_qty, uom
1214         @return: Dictionary of values
1215         """
1216         if context is None:
1217             context = {}
1218         else:
1219             context = dict(context)
1220         res = {}
1221         move_obj = self.pool.get('stock.move')
1222         product_obj = self.pool.get('product.product')
1223         currency_obj = self.pool.get('res.currency')
1224         uom_obj = self.pool.get('product.uom')
1225         sequence_obj = self.pool.get('ir.sequence')
1226         wf_service = netsvc.LocalService("workflow")
1227         for pick in self.browse(cr, uid, ids, context=context):
1228             new_picking = None
1229             complete, too_many, too_few = [], [], []
1230             move_product_qty, prodlot_ids, product_avail, partial_qty, product_uoms = {}, {}, {}, {}, {}
1231             for move in pick.move_lines:
1232                 if move.state in ('done', 'cancel'):
1233                     continue
1234                 partial_data = partial_datas.get('move%s'%(move.id), {})
1235                 product_qty = partial_data.get('product_qty',0.0)
1236                 move_product_qty[move.id] = product_qty
1237                 product_uom = partial_data.get('product_uom',False)
1238                 product_price = partial_data.get('product_price',0.0)
1239                 product_currency = partial_data.get('product_currency',False)
1240                 prodlot_id = partial_data.get('prodlot_id')
1241                 prodlot_ids[move.id] = prodlot_id
1242                 product_uoms[move.id] = product_uom
1243                 partial_qty[move.id] = uom_obj._compute_qty(cr, uid, product_uoms[move.id], product_qty, move.product_uom.id)
1244                 if move.product_qty == partial_qty[move.id]:
1245                     complete.append(move)
1246                 elif move.product_qty > partial_qty[move.id]:
1247                     too_few.append(move)
1248                 else:
1249                     too_many.append(move)
1250
1251                 # Average price computation
1252                 if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
1253                     product = product_obj.browse(cr, uid, move.product_id.id)
1254                     move_currency_id = move.company_id.currency_id.id
1255                     context['currency_id'] = move_currency_id
1256                     qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
1257
1258                     if product.id in product_avail:
1259                         product_avail[product.id] += qty
1260                     else:
1261                         product_avail[product.id] = product.qty_available
1262
1263                     if qty > 0:
1264                         new_price = currency_obj.compute(cr, uid, product_currency,
1265                                 move_currency_id, product_price)
1266                         new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
1267                                 product.uom_id.id)
1268                         if product.qty_available <= 0:
1269                             new_std_price = new_price
1270                         else:
1271                             # Get the standard price
1272                             amount_unit = product.price_get('standard_price', context=context)[product.id]
1273                             new_std_price = ((amount_unit * product_avail[product.id])\
1274                                 + (new_price * qty))/(product_avail[product.id] + qty)
1275                         # Write the field according to price type field
1276                         product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price})
1277
1278                         # Record the values that were chosen in the wizard, so they can be
1279                         # used for inventory valuation if real-time valuation is enabled.
1280                         move_obj.write(cr, uid, [move.id],
1281                                 {'price_unit': product_price,
1282                                  'price_currency_id': product_currency})
1283
1284
1285             for move in too_few:
1286                 product_qty = move_product_qty[move.id]
1287                 if not new_picking:
1288                     new_picking_name = pick.name
1289                     self.write(cr, uid, [pick.id], 
1290                                {'name': sequence_obj.get(cr, uid,
1291                                             'stock.picking.%s'%(pick.type)),
1292                                })
1293                     new_picking = self.copy(cr, uid, pick.id,
1294                             {
1295                                 'name': new_picking_name,
1296                                 'move_lines' : [],
1297                                 'state':'draft',
1298                             })
1299                 if product_qty != 0:
1300                     defaults = {
1301                             'product_qty' : product_qty,
1302                             'product_uos_qty': product_qty, #TODO: put correct uos_qty
1303                             'picking_id' : new_picking,
1304                             'state': 'assigned',
1305                             'move_dest_id': False,
1306                             'price_unit': move.price_unit,
1307                             'product_uom': product_uoms[move.id]
1308                     }
1309                     prodlot_id = prodlot_ids[move.id]
1310                     if prodlot_id:
1311                         defaults.update(prodlot_id=prodlot_id)
1312                     move_obj.copy(cr, uid, move.id, defaults)
1313                 move_obj.write(cr, uid, [move.id],
1314                         {
1315                             'product_qty': move.product_qty - partial_qty[move.id],
1316                             'product_uos_qty': move.product_qty - partial_qty[move.id], #TODO: put correct uos_qty
1317                             'prodlot_id': False,
1318                             'tracking_id': False,
1319                         })
1320
1321             if new_picking:
1322                 move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
1323             for move in complete:
1324                 defaults = {'product_uom': product_uoms[move.id], 'product_qty': move_product_qty[move.id]}
1325                 if prodlot_ids.get(move.id):
1326                     defaults.update({'prodlot_id': prodlot_ids[move.id]})
1327                 move_obj.write(cr, uid, [move.id], defaults)
1328             for move in too_many:
1329                 product_qty = move_product_qty[move.id]
1330                 defaults = {
1331                     'product_qty' : product_qty,
1332                     'product_uos_qty': product_qty, #TODO: put correct uos_qty
1333                     'product_uom': product_uoms[move.id]
1334                 }
1335                 prodlot_id = prodlot_ids.get(move.id)
1336                 if prodlot_ids.get(move.id):
1337                     defaults.update(prodlot_id=prodlot_id)
1338                 if new_picking:
1339                     defaults.update(picking_id=new_picking)
1340                 move_obj.write(cr, uid, [move.id], defaults)
1341
1342             # At first we confirm the new picking (if necessary)
1343             if new_picking:
1344                 self.signal_button_confirm(cr, uid, [new_picking])
1345                 # Then we finish the good picking
1346                 self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
1347                 self.action_move(cr, uid, [new_picking], context=context)
1348                 self.signal_button_done(cr, uid, [new_picking])
1349                 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
1350                 delivered_pack_id = new_picking
1351                 back_order_name = self.browse(cr, uid, delivered_pack_id, context=context).name
1352                 self.message_post(cr, uid, ids, body=_("Back order <em>%s</em> has been <b>created</b>.") % (back_order_name), context=context)
1353             else:
1354                 self.action_move(cr, uid, [pick.id], context=context)
1355                 self.signal_button_done(cr, uid, [pick.id])
1356                 delivered_pack_id = pick.id
1357
1358             delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
1359             res[pick.id] = {'delivered_picking': delivered_pack.id or False}
1360
1361         return res
1362     
1363     # views associated to each picking type
1364     _VIEW_LIST = {
1365         'out': 'view_picking_out_form',
1366         'in': 'view_picking_in_form',
1367         'internal': 'view_picking_form',
1368     }
1369     def _get_view_id(self, cr, uid, type):
1370         """Get the view id suiting the given type
1371         
1372         @param type: the picking type as a string
1373         @return: view i, or False if no view found
1374         """
1375         res = self.pool.get('ir.model.data').get_object_reference(cr, uid, 
1376             'stock', self._VIEW_LIST.get(type, 'view_picking_form'))            
1377         return res and res[1] or False
1378
1379
1380 class stock_production_lot(osv.osv):
1381
1382     def name_get(self, cr, uid, ids, context=None):
1383         if not ids:
1384             return []
1385         reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
1386         res = []
1387         for record in reads:
1388             name = record['name']
1389             prefix = record['prefix']
1390             if prefix:
1391                 name = prefix + '/' + name
1392             if record['ref']:
1393                 name = '%s [%s]' % (name, record['ref'])
1394             res.append((record['id'], name))
1395         return res
1396
1397     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
1398         args = args or []
1399         ids = []
1400         if name:
1401             ids = self.search(cr, uid, [('prefix', '=', name)] + args, limit=limit, context=context)
1402             if not ids:
1403                 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
1404         else:
1405             ids = self.search(cr, uid, args, limit=limit, context=context)
1406         return self.name_get(cr, uid, ids, context)
1407
1408     _name = 'stock.production.lot'
1409     _description = 'Serial Number'
1410
1411     def _get_stock(self, cr, uid, ids, field_name, arg, context=None):
1412         """ Gets stock of products for locations
1413         @return: Dictionary of values
1414         """
1415         if context is None:
1416             context = {}
1417         if 'location_id' not in context:
1418             locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
1419         else:
1420             locations = context['location_id'] and [context['location_id']] or []
1421
1422         if isinstance(ids, (int, long)):
1423             ids = [ids]
1424
1425         res = {}.fromkeys(ids, 0.0)
1426         if locations:
1427             cr.execute('''select
1428                     prodlot_id,
1429                     sum(qty)
1430                 from
1431                     stock_report_prodlots
1432                 where
1433                     location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),))
1434             res.update(dict(cr.fetchall()))
1435
1436         return res
1437
1438     def _stock_search(self, cr, uid, obj, name, args, context=None):
1439         """ Searches Ids of products
1440         @return: Ids of locations
1441         """
1442         locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
1443         cr.execute('''select
1444                 prodlot_id,
1445                 sum(qty)
1446             from
1447                 stock_report_prodlots
1448             where
1449                 location_id IN %s group by prodlot_id
1450             having  sum(qty) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),))
1451         res = cr.fetchall()
1452         ids = [('id', 'in', map(lambda x: x[0], res))]
1453         return ids
1454
1455     _columns = {
1456         'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number, will be displayed as: PREFIX/SERIAL [INT_REF]"),
1457         'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1458         'prefix': fields.char('Prefix', size=64, help="Optional prefix to prepend when displaying this serial number: PREFIX/SERIAL [INT_REF]"),
1459         'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1460         'date': fields.datetime('Creation Date', required=True),
1461         'stock_available': fields.function(_get_stock, fnct_search=_stock_search, type="float", string="Available", select=True,
1462             help="Current quantity of products with this Serial Number available in company warehouses",
1463             digits_compute=dp.get_precision('Product Unit of Measure')),
1464         'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
1465         'company_id': fields.many2one('res.company', 'Company', select=True),
1466         'move_ids': fields.one2many('stock.move', 'prodlot_id', 'Moves for this serial number', readonly=True),
1467     }
1468     _defaults = {
1469         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1470         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1471         'product_id': lambda x, y, z, c: c.get('product_id', False),
1472     }
1473     _sql_constraints = [
1474         ('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
1475     ]
1476     def action_traceability(self, cr, uid, ids, context=None):
1477         """ It traces the information of a product
1478         @param self: The object pointer.
1479         @param cr: A database cursor
1480         @param uid: ID of the user currently logged in
1481         @param ids: List of IDs selected
1482         @param context: A standard dictionary
1483         @return: A dictionary of values
1484         """
1485         value=self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
1486         return value
1487
1488     def copy(self, cr, uid, id, default=None, context=None):
1489         context = context or {}
1490         default = default and default.copy() or {}
1491         default.update(date=time.strftime('%Y-%m-%d %H:%M:%S'), move_ids=[])
1492         return super(stock_production_lot, self).copy(cr, uid, id, default=default, context=context)
1493
1494 stock_production_lot()
1495
1496 class stock_production_lot_revision(osv.osv):
1497     _name = 'stock.production.lot.revision'
1498     _description = 'Serial Number Revision'
1499
1500     _columns = {
1501         'name': fields.char('Revision Name', size=64, required=True),
1502         'description': fields.text('Description'),
1503         'date': fields.date('Revision Date'),
1504         'indice': fields.char('Revision Number', size=16),
1505         'author_id': fields.many2one('res.users', 'Author'),
1506         'lot_id': fields.many2one('stock.production.lot', 'Serial Number', select=True, ondelete='cascade'),
1507         'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True),
1508     }
1509
1510     _defaults = {
1511         'author_id': lambda x, y, z, c: z,
1512         'date': fields.date.context_today,
1513     }
1514
1515 stock_production_lot_revision()
1516
1517 # ----------------------------------------------------
1518 # Move
1519 # ----------------------------------------------------
1520
1521 #
1522 # Fields:
1523 #   location_dest_id is only used for predicting futur stocks
1524 #
1525 class stock_move(osv.osv):
1526
1527     def _getSSCC(self, cr, uid, context=None):
1528         cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
1529         res = cr.fetchone()
1530         return (res and res[0]) or False
1531
1532     _name = "stock.move"
1533     _description = "Stock Move"
1534     _order = 'date_expected desc, id'
1535     _log_create = False
1536
1537     def action_partial_move(self, cr, uid, ids, context=None):
1538         if context is None: context = {}
1539         if context.get('active_model') != self._name:
1540             context.update(active_ids=ids, active_model=self._name)
1541         partial_id = self.pool.get("stock.partial.move").create(
1542             cr, uid, {}, context=context)
1543         return {
1544             'name':_("Products to Process"),
1545             'view_mode': 'form',
1546             'view_id': False,
1547             'view_type': 'form',
1548             'res_model': 'stock.partial.move',
1549             'res_id': partial_id,
1550             'type': 'ir.actions.act_window',
1551             'nodestroy': True,
1552             'target': 'new',
1553             'domain': '[]',
1554             'context': context
1555         }
1556
1557
1558     def name_get(self, cr, uid, ids, context=None):
1559         res = []
1560         for line in self.browse(cr, uid, ids, context=context):
1561             name = line.location_id.name+' > '+line.location_dest_id.name
1562             # optional prefixes
1563             if line.product_id.code:
1564                 name = line.product_id.code + ': ' + name
1565             if line.picking_id.origin:
1566                 name = line.picking_id.origin + '/ ' + name
1567             res.append((line.id, name))
1568         return res
1569
1570     def _check_tracking(self, cr, uid, ids, context=None):
1571         """ Checks if serial number is assigned to stock move or not.
1572         @return: True or False
1573         """
1574         for move in self.browse(cr, uid, ids, context=context):
1575             if not move.prodlot_id and \
1576                (move.state == 'done' and \
1577                ( \
1578                    (move.product_id.track_production and move.location_id.usage == 'production') or \
1579                    (move.product_id.track_production and move.location_dest_id.usage == 'production') or \
1580                    (move.product_id.track_incoming and move.location_id.usage == 'supplier') or \
1581                    (move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \
1582                    (move.product_id.track_incoming and move.location_id.usage == 'inventory') \
1583                )):
1584                 return False
1585         return True
1586
1587     def _check_product_lot(self, cr, uid, ids, context=None):
1588         """ Checks whether move is done or not and production lot is assigned to that move.
1589         @return: True or False
1590         """
1591         for move in self.browse(cr, uid, ids, context=context):
1592             if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id):
1593                 return False
1594         return True
1595
1596     _columns = {
1597         'name': fields.char('Description', required=True, select=True),
1598         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1599         'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1600         '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)]}),
1601         'date_expected': fields.datetime('Scheduled Date', states={'done': [('readonly', True)]},required=True, select=True, help="Scheduled date for the processing of this move"),
1602         'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type','<>','service')],states={'done': [('readonly', True)]}),
1603
1604         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1605             required=True,states={'done': [('readonly', True)]},
1606             help="This is the quantity of products from an inventory "
1607                 "point of view. For moves in the state 'done', this is the "
1608                 "quantity of products that were actually moved. For other "
1609                 "moves, this is the quantity of product that is planned to "
1610                 "be moved. Lowering this quantity does not generate a "
1611                 "backorder. Changing this quantity on assigned moves affects "
1612                 "the product reservation, and should be done with care."
1613         ),
1614         'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True,states={'done': [('readonly', True)]}),
1615         'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1616         'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1617         'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1618
1619         '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."),
1620         '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."),
1621         '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"),
1622
1623         'prodlot_id': fields.many2one('stock.production.lot', 'Serial Number', states={'done': [('readonly', True)]}, help="Serial number is used to put a serial number on the production", select=True),
1624         'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, states={'done': [('readonly', True)]}, help="Logistical shipping unit: pallet, box, pack ..."),
1625
1626         'auto_validate': fields.boolean('Auto Validate'),
1627
1628         'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1629         'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History (child moves)'),
1630         'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History (parent moves)'),
1631         'picking_id': fields.many2one('stock.picking', 'Reference', select=True,states={'done': [('readonly', True)]}),
1632         'note': fields.text('Notes'),
1633         'state': fields.selection([('draft', 'New'),
1634                                    ('cancel', 'Cancelled'),
1635                                    ('waiting', 'Waiting Another Move'),
1636                                    ('confirmed', 'Waiting Availability'),
1637                                    ('assigned', 'Available'),
1638                                    ('done', 'Done'),
1639                                    ], 'Status', readonly=True, select=True,
1640                  help= "* New: When the stock move is created and not yet confirmed.\n"\
1641                        "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1642                        "* 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"\
1643                        "* Available: When products are reserved, it is set to \'Available\'.\n"\
1644                        "* Done: When the shipment is processed, the state is \'Done\'."),
1645         'price_unit': fields.float('Unit Price', digits_compute= dp.get_precision('Account'), help="Technical field used to record the product cost set by the user during a picking confirmation (when average price costing method is used)"),
1646         'price_currency_id': fields.many2one('res.currency', 'Currency for average price', help="Technical field used to record the currency chosen by the user during a picking confirmation (when average price costing method is used)"),
1647         'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1648         'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Order of", select=True),
1649         'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Source", store=True),
1650
1651         # used for colors in tree views:
1652         'scrapped': fields.related('location_dest_id','scrap_location',type='boolean',relation='stock.location',string='Scrapped', readonly=True),
1653         'type': fields.related('picking_id', 'type', type='selection', selection=[('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], string='Shipping Type'),
1654     }
1655
1656     def _check_location(self, cr, uid, ids, context=None):
1657         for record in self.browse(cr, uid, ids, context=context):
1658             if (record.state=='done') and (record.location_id.usage == 'view'):
1659                 raise osv.except_osv(_('Error'), _('You cannot move product %s from a location of type view %s.')% (record.product_id.name, record.location_id.name))
1660             if (record.state=='done') and (record.location_dest_id.usage == 'view' ):
1661                 raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.')% (record.product_id.name, record.location_dest_id.name))
1662         return True
1663
1664     _constraints = [
1665         (_check_tracking,
1666             'You must assign a serial number for this product.',
1667             ['prodlot_id']),
1668         (_check_location, 'You cannot move products from or to a location of the type view.',
1669             ['location_id','location_dest_id']),
1670         (_check_product_lot,
1671             'You try to assign a lot which is not from the same product.',
1672             ['prodlot_id'])]
1673
1674     def _default_location_destination(self, cr, uid, context=None):
1675         """ Gets default address of partner for destination location
1676         @return: Address id or False
1677         """
1678         mod_obj = self.pool.get('ir.model.data')
1679         picking_type = context.get('picking_type')
1680         location_id = False
1681         if context is None:
1682             context = {}
1683         if context.get('move_line', []):
1684             if context['move_line'][0]:
1685                 if isinstance(context['move_line'][0], (tuple, list)):
1686                     location_id = context['move_line'][0][2] and context['move_line'][0][2].get('location_dest_id',False)
1687                 else:
1688                     move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1689                     location_id = move_list and move_list['location_dest_id'][0] or False
1690         elif context.get('address_out_id', False):
1691             property_out = self.pool.get('res.partner').browse(cr, uid, context['address_out_id'], context).property_stock_customer
1692             location_id = property_out and property_out.id or False
1693         else:
1694             location_xml_id = False
1695             if picking_type in ('in', 'internal'):
1696                 location_xml_id = 'stock_location_stock'
1697             elif picking_type == 'out':
1698                 location_xml_id = 'stock_location_customers'
1699             if location_xml_id:
1700                 location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id)
1701         return location_id
1702
1703     def _default_location_source(self, cr, uid, context=None):
1704         """ Gets default address of partner for source location
1705         @return: Address id or False
1706         """
1707         mod_obj = self.pool.get('ir.model.data')
1708         picking_type = context.get('picking_type')
1709         location_id = False
1710
1711         if context is None:
1712             context = {}
1713         if context.get('move_line', []):
1714             try:
1715                 location_id = context['move_line'][0][2]['location_id']
1716             except:
1717                 pass
1718         elif context.get('address_in_id', False):
1719             part_obj_add = self.pool.get('res.partner').browse(cr, uid, context['address_in_id'], context=context)
1720             if part_obj_add:
1721                 location_id = part_obj_add.property_stock_supplier.id
1722         else:
1723             location_xml_id = False
1724             if picking_type == 'in':
1725                 location_xml_id = 'stock_location_suppliers'
1726             elif picking_type in ('out', 'internal'):
1727                 location_xml_id = 'stock_location_stock'
1728             if location_xml_id:
1729                 location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id)
1730         return location_id
1731
1732     def _default_destination_address(self, cr, uid, context=None):
1733         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1734         return user.company_id.partner_id.id
1735
1736     def _default_move_type(self, cr, uid, context=None):
1737         """ Gets default type of move
1738         @return: type
1739         """
1740         if context is None:
1741             context = {}
1742         picking_type = context.get('picking_type')
1743         type = 'internal'
1744         if picking_type == 'in':
1745             type = 'in'
1746         elif picking_type == 'out':
1747             type = 'out'
1748         return type
1749
1750     _defaults = {
1751         'location_id': _default_location_source,
1752         'location_dest_id': _default_location_destination,
1753         'partner_id': _default_destination_address,
1754         'type': _default_move_type,
1755         'state': 'draft',
1756         'priority': '1',
1757         'product_qty': 1.0,
1758         'scrapped' :  False,
1759         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1760         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1761         'date_expected': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1762     }
1763
1764     def write(self, cr, uid, ids, vals, context=None):
1765         if isinstance(ids, (int, long)):
1766             ids = [ids]
1767         if uid != 1:
1768             frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1769             for move in self.browse(cr, uid, ids, context=context):
1770                 if move.state == 'done':
1771                     if frozen_fields.intersection(vals):
1772                         raise osv.except_osv(_('Operation forbidden !'),
1773                                              _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1774         return  super(stock_move, self).write(cr, uid, ids, vals, context=context)
1775
1776     def copy(self, cr, uid, id, default=None, context=None):
1777         if default is None:
1778             default = {}
1779         default = default.copy()
1780         default.update({'move_history_ids2': [], 'move_history_ids': []})
1781         return super(stock_move, self).copy(cr, uid, id, default, context=context)
1782
1783     def _auto_init(self, cursor, context=None):
1784         res = super(stock_move, self)._auto_init(cursor, context=context)
1785         cursor.execute('SELECT indexname \
1786                 FROM pg_indexes \
1787                 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1788         if not cursor.fetchone():
1789             cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1790                     ON stock_move (product_id, state, location_id, location_dest_id)')
1791         return res
1792
1793     def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
1794                         loc_id=False, product_id=False, uom_id=False, context=None):
1795         """ On change of production lot gives a warning message.
1796         @param prodlot_id: Changed production lot id
1797         @param product_qty: Quantity of product
1798         @param loc_id: Location id
1799         @param product_id: Product id
1800         @return: Warning message
1801         """
1802         if not prodlot_id or not loc_id:
1803             return {}
1804         ctx = context and context.copy() or {}
1805         ctx['location_id'] = loc_id
1806         ctx.update({'raise-exception': True})
1807         uom_obj = self.pool.get('product.uom')
1808         product_obj = self.pool.get('product.product')
1809         product_uom = product_obj.browse(cr, uid, product_id, context=ctx).uom_id
1810         prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, context=ctx)
1811         location = self.pool.get('stock.location').browse(cr, uid, loc_id, context=ctx)
1812         uom = uom_obj.browse(cr, uid, uom_id, context=ctx)
1813         amount_actual = uom_obj._compute_qty_obj(cr, uid, product_uom, prodlot.stock_available, uom, context=ctx)
1814         warning = {}
1815         if (location.usage == 'internal') and (product_qty > (amount_actual or 0.0)):
1816             warning = {
1817                 'title': _('Insufficient Stock for Serial Number !'),
1818                 'message': _('You are moving %.2f %s but only %.2f %s available for this serial number.') % (product_qty, uom.name, amount_actual, uom.name)
1819             }
1820         return {'warning': warning}
1821
1822     def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
1823                           product_uom, product_uos):
1824         """ On change of product quantity finds UoM and UoS quantities
1825         @param product_id: Product id
1826         @param product_qty: Changed Quantity of product
1827         @param product_uom: Unit of measure of product
1828         @param product_uos: Unit of sale of product
1829         @return: Dictionary of values
1830         """
1831         result = {
1832                   'product_uos_qty': 0.00
1833           }
1834         warning = {}
1835
1836         if (not product_id) or (product_qty <=0.0):
1837             result['product_qty'] = 0.0
1838             return {'value': result}
1839
1840         product_obj = self.pool.get('product.product')
1841         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1842         
1843         # Warn if the quantity was decreased 
1844         if ids:
1845             for move in self.read(cr, uid, ids, ['product_qty']):
1846                 if product_qty < move['product_qty']:
1847                     warning.update({
1848                        'title': _('Information'),
1849                        'message': _("By changing this quantity here, you accept the "
1850                                 "new quantity as complete: OpenERP will not "
1851                                 "automatically generate a back order.") })
1852                 break
1853
1854         if product_uos and product_uom and (product_uom != product_uos):
1855             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1856         else:
1857             result['product_uos_qty'] = product_qty
1858
1859         return {'value': result, 'warning': warning}
1860
1861     def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1862                           product_uos, product_uom):
1863         """ On change of product quantity finds UoM and UoS quantities
1864         @param product_id: Product id
1865         @param product_uos_qty: Changed UoS Quantity of product
1866         @param product_uom: Unit of measure of product
1867         @param product_uos: Unit of sale of product
1868         @return: Dictionary of values
1869         """
1870         result = {
1871                   'product_qty': 0.00
1872           }
1873         warning = {}
1874
1875         if (not product_id) or (product_uos_qty <=0.0):
1876             result['product_uos_qty'] = 0.0
1877             return {'value': result}
1878
1879         product_obj = self.pool.get('product.product')
1880         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1881         
1882         # Warn if the quantity was decreased 
1883         for move in self.read(cr, uid, ids, ['product_uos_qty']):
1884             if product_uos_qty < move['product_uos_qty']:
1885                 warning.update({
1886                    'title': _('Warning: No Back Order'),
1887                    'message': _("By changing the quantity here, you accept the "
1888                                 "new quantity as complete: OpenERP will not "
1889                                 "automatically generate a Back Order.") })
1890                 break
1891
1892         if product_uos and product_uom and (product_uom != product_uos):
1893             result['product_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1894         else:
1895             result['product_qty'] = product_uos_qty
1896         return {'value': result, 'warning': warning}
1897
1898     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
1899                             loc_dest_id=False, partner_id=False):
1900         """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1901         @param prod_id: Changed Product id
1902         @param loc_id: Source location id
1903         @param loc_dest_id: Destination location id
1904         @param partner_id: Address id of partner
1905         @return: Dictionary of values
1906         """
1907         if not prod_id:
1908             return {}
1909         lang = False
1910         if partner_id:
1911             addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1912             if addr_rec:
1913                 lang = addr_rec and addr_rec.lang or False
1914         ctx = {'lang': lang}
1915
1916         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1917         uos_id  = product.uos_id and product.uos_id.id or False
1918         result = {
1919             'product_uom': product.uom_id.id,
1920             'product_uos': uos_id,
1921             'product_qty': 1.00,
1922             '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'],
1923             'prodlot_id' : False,
1924         }
1925         if not ids:
1926             result['name'] = product.partner_ref
1927         if loc_id:
1928             result['location_id'] = loc_id
1929         if loc_dest_id:
1930             result['location_dest_id'] = loc_dest_id
1931         return {'value': result}
1932
1933     def onchange_move_type(self, cr, uid, ids, type, context=None):
1934         """ On change of move type gives sorce and destination location.
1935         @param type: Move Type
1936         @return: Dictionary of values
1937         """
1938         mod_obj = self.pool.get('ir.model.data')
1939         location_source_id = 'stock_location_stock'
1940         location_dest_id = 'stock_location_stock'
1941         if type == 'in':
1942             location_source_id = 'stock_location_suppliers'
1943             location_dest_id = 'stock_location_stock'
1944         elif type == 'out':
1945             location_source_id = 'stock_location_stock'
1946             location_dest_id = 'stock_location_customers'
1947         source_location = mod_obj.get_object_reference(cr, uid, 'stock', location_source_id)
1948         dest_location = mod_obj.get_object_reference(cr, uid, 'stock', location_dest_id)
1949         return {'value':{'location_id': source_location and source_location[1] or False, 'location_dest_id': dest_location and dest_location[1] or False}}
1950
1951     def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
1952         """ On change of Scheduled Date gives a Move date.
1953         @param date_expected: Scheduled Date
1954         @param date: Move Date
1955         @return: Move Date
1956         """
1957         if not date_expected:
1958             date_expected = time.strftime('%Y-%m-%d %H:%M:%S')
1959         return {'value':{'date': date_expected}}
1960
1961     def _chain_compute(self, cr, uid, moves, context=None):
1962         """ Finds whether the location has chained location type or not.
1963         @param moves: Stock moves
1964         @return: Dictionary containing destination location with chained location type.
1965         """
1966         result = {}
1967         for m in moves:
1968             dest = self.pool.get('stock.location').chained_location_get(
1969                 cr,
1970                 uid,
1971                 m.location_dest_id,
1972                 m.picking_id and m.picking_id.partner_id and m.picking_id.partner_id,
1973                 m.product_id,
1974                 context
1975             )
1976             if dest:
1977                 if dest[1] == 'transparent':
1978                     newdate = (datetime.strptime(m.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d')
1979                     self.write(cr, uid, [m.id], {
1980                         'date': newdate,
1981                         'location_dest_id': dest[0].id})
1982                     if m.picking_id and (dest[3] or dest[5]):
1983                         self.pool.get('stock.picking').write(cr, uid, [m.picking_id.id], {
1984                             'stock_journal_id': dest[3] or m.picking_id.stock_journal_id.id,
1985                             'type': dest[5] or m.picking_id.type
1986                         }, context=context)
1987                     m.location_dest_id = dest[0]
1988                     res2 = self._chain_compute(cr, uid, [m], context=context)
1989                     for pick_id in res2.keys():
1990                         result.setdefault(pick_id, [])
1991                         result[pick_id] += res2[pick_id]
1992                 else:
1993                     result.setdefault(m.picking_id, [])
1994                     result[m.picking_id].append( (m, dest) )
1995         return result
1996
1997     def _prepare_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
1998         """Prepare the definition (values) to create a new chained picking.
1999
2000            :param str picking_name: desired new picking name
2001            :param browse_record picking: source picking (being chained to)
2002            :param str picking_type: desired new picking type
2003            :param list moves_todo: specification of the stock moves to be later included in this
2004                picking, in the form::
2005
2006                    [[move, (dest_location, auto_packing, chained_delay, chained_journal,
2007                                   chained_company_id, chained_picking_type)],
2008                     ...
2009                    ]
2010
2011                See also :meth:`stock_location.chained_location_get`.
2012         """
2013         res_company = self.pool.get('res.company')
2014         return {
2015                     'name': picking_name,
2016                     'origin': tools.ustr(picking.origin or ''),
2017                     'type': picking_type,
2018                     'note': picking.note,
2019                     'move_type': picking.move_type,
2020                     'auto_picking': moves_todo[0][1][1] == 'auto',
2021                     'stock_journal_id': moves_todo[0][1][3],
2022                     'company_id': moves_todo[0][1][4] or res_company._company_default_get(cr, uid, 'stock.company', context=context),
2023                     'partner_id': picking.partner_id.id,
2024                     'invoice_state': 'none',
2025                     'date': picking.date,
2026                 }
2027
2028     def _create_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
2029         picking_obj = self.pool.get('stock.picking')
2030         return picking_obj.create(cr, uid, self._prepare_chained_picking(cr, uid, picking_name, picking, picking_type, moves_todo, context=context))
2031
2032     def create_chained_picking(self, cr, uid, moves, context=None):
2033         res_obj = self.pool.get('res.company')
2034         location_obj = self.pool.get('stock.location')
2035         move_obj = self.pool.get('stock.move')
2036         new_moves = []
2037         if context is None:
2038             context = {}
2039         seq_obj = self.pool.get('ir.sequence')
2040         for picking, todo in self._chain_compute(cr, uid, moves, context=context).items():
2041             ptype = todo[0][1][5] and todo[0][1][5] or location_obj.picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
2042             if picking:
2043                 # name of new picking according to its type
2044                 new_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + ptype)
2045                 pickid = self._create_chained_picking(cr, uid, new_pick_name, picking, ptype, todo, context=context)
2046                 # Need to check name of old picking because it always considers picking as "OUT" when created from Sales Order
2047                 old_ptype = location_obj.picking_type_get(cr, uid, picking.move_lines[0].location_id, picking.move_lines[0].location_dest_id)
2048                 if old_ptype != picking.type:
2049                     old_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + old_ptype)
2050                     self.pool.get('stock.picking').write(cr, uid, [picking.id], {'name': old_pick_name, 'type': old_ptype}, context=context)
2051             else:
2052                 pickid = False
2053             for move, (loc, dummy, delay, dummy, company_id, ptype, invoice_state) in todo:
2054                 new_id = move_obj.copy(cr, uid, move.id, {
2055                     'location_id': move.location_dest_id.id,
2056                     'location_dest_id': loc.id,
2057                     'date': time.strftime('%Y-%m-%d'),
2058                     'picking_id': pickid,
2059                     'state': 'waiting',
2060                     'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context=context)  ,
2061                     'move_history_ids': [],
2062                     'date_expected': (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
2063                     'move_history_ids2': []}
2064                 )
2065                 move_obj.write(cr, uid, [move.id], {
2066                     'move_dest_id': new_id,
2067                     'move_history_ids': [(4, new_id)]
2068                 })
2069                 new_moves.append(self.browse(cr, uid, [new_id])[0])
2070             if pickid:
2071                 self.signal_button_confirm(cr, uid, [pickid])
2072         if new_moves:
2073             new_moves += self.create_chained_picking(cr, uid, new_moves, context)
2074         return new_moves
2075
2076     def action_confirm(self, cr, uid, ids, context=None):
2077         """ Confirms stock move.
2078         @return: List of ids.
2079         """
2080         moves = self.browse(cr, uid, ids, context=context)
2081         self.write(cr, uid, ids, {'state': 'confirmed'})
2082         self.create_chained_picking(cr, uid, moves, context)
2083         return []
2084
2085     def action_assign(self, cr, uid, ids, *args):
2086         """ Changes state to confirmed or waiting.
2087         @return: List of values
2088         """
2089         todo = []
2090         for move in self.browse(cr, uid, ids):
2091             if move.state in ('confirmed', 'waiting'):
2092                 todo.append(move.id)
2093         res = self.check_assign(cr, uid, todo)
2094         return res
2095
2096     def force_assign(self, cr, uid, ids, context=None):
2097         """ Changes the state to assigned.
2098         @return: True
2099         """
2100         self.write(cr, uid, ids, {'state': 'assigned'})
2101         wf_service = netsvc.LocalService('workflow')
2102         for move in self.browse(cr, uid, ids, context):
2103             if move.picking_id:
2104                 wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
2105         return True
2106
2107     def cancel_assign(self, cr, uid, ids, context=None):
2108         """ Changes the state to confirmed.
2109         @return: True
2110         """
2111         self.write(cr, uid, ids, {'state': 'confirmed'})
2112
2113         # fix for bug lp:707031
2114         # called write of related picking because changing move availability does
2115         # not trigger workflow of picking in order to change the state of picking
2116         wf_service = netsvc.LocalService('workflow')
2117         for move in self.browse(cr, uid, ids, context):
2118             if move.picking_id:
2119                 wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
2120         return True
2121
2122     #
2123     # Duplicate stock.move
2124     #
2125     def check_assign(self, cr, uid, ids, context=None):
2126         """ Checks the product type and accordingly writes the state.
2127         @return: No. of moves done
2128         """
2129         done = []
2130         count = 0
2131         pickings = {}
2132         if context is None:
2133             context = {}
2134         for move in self.browse(cr, uid, ids, context=context):
2135             if move.product_id.type == 'consu' or move.location_id.usage == 'supplier':
2136                 if move.state in ('confirmed', 'waiting'):
2137                     done.append(move.id)
2138                 pickings[move.picking_id.id] = 1
2139                 continue
2140             if move.state in ('confirmed', 'waiting'):
2141                 # Important: we must pass lock=True to _product_reserve() to avoid race conditions and double reservations
2142                 res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id}, lock=True)
2143                 if res:
2144                     #_product_available_test depends on the next status for correct functioning
2145                     #the test does not work correctly if the same product occurs multiple times
2146                     #in the same order. This is e.g. the case when using the button 'split in two' of
2147                     #the stock outgoing form
2148                     self.write(cr, uid, [move.id], {'state':'assigned'})
2149                     done.append(move.id)
2150                     pickings[move.picking_id.id] = 1
2151                     r = res.pop(0)
2152                     product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, ids, move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty']
2153                     cr.execute('update stock_move set location_id=%s, product_qty=%s, product_uos_qty=%s where id=%s', (r[1], r[0],product_uos_qty, move.id))
2154
2155                     while res:
2156                         r = res.pop(0)
2157                         move_id = self.copy(cr, uid, move.id, {'product_uos_qty': product_uos_qty, 'product_qty': r[0], 'location_id': r[1]})
2158                         done.append(move_id)
2159         if done:
2160             count += len(done)
2161             self.write(cr, uid, done, {'state': 'assigned'})
2162
2163         if count:
2164             for pick_id in pickings:
2165                 wf_service = netsvc.LocalService("workflow")
2166                 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
2167         return count
2168
2169     def setlast_tracking(self, cr, uid, ids, context=None):
2170         tracking_obj = self.pool.get('stock.tracking')
2171         picking = self.browse(cr, uid, ids, context=context)[0].picking_id
2172         if picking:
2173             last_track = [line.tracking_id.id for line in picking.move_lines if line.tracking_id]
2174             if not last_track:
2175                 last_track = tracking_obj.create(cr, uid, {}, context=context)
2176             else:
2177                 last_track.sort()
2178                 last_track = last_track[-1]
2179             self.write(cr, uid, ids, {'tracking_id': last_track})
2180         return True
2181
2182     #
2183     # Cancel move => cancel others move and pickings
2184     #
2185     def action_cancel(self, cr, uid, ids, context=None):
2186         """ Cancels the moves and if all moves are cancelled it cancels the picking.
2187         @return: True
2188         """
2189         if not len(ids):
2190             return True
2191         if context is None:
2192             context = {}
2193         wf_service = netsvc.LocalService("workflow")
2194         pickings = set()
2195         for move in self.browse(cr, uid, ids, context=context):
2196             if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
2197                 if move.picking_id:
2198                     pickings.add(move.picking_id.id)
2199             if move.move_dest_id and move.move_dest_id.state == 'waiting':
2200                 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
2201                 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
2202                     wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
2203         self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
2204         if not context.get('call_unlink',False):
2205             for pick in self.pool.get('stock.picking').browse(cr, uid, list(pickings), context=context):
2206                 if all(move.state == 'cancel' for move in pick.move_lines):
2207                     self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
2208
2209         for id in ids:
2210             wf_service.trg_trigger(uid, 'stock.move', id, cr)
2211         return True
2212
2213     def _get_accounting_data_for_valuation(self, cr, uid, move, context=None):
2214         """
2215         Return the accounts and journal to use to post Journal Entries for the real-time
2216         valuation of the move.
2217
2218         :param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key
2219         :raise: osv.except_osv() is any mandatory account or journal is not defined.
2220         """
2221         product_obj=self.pool.get('product.product')
2222         accounts = product_obj.get_product_accounts(cr, uid, move.product_id.id, context)
2223         if move.location_id.valuation_out_account_id:
2224             acc_src = move.location_id.valuation_out_account_id.id
2225         else:
2226             acc_src = accounts['stock_account_input']
2227
2228         if move.location_dest_id.valuation_in_account_id:
2229             acc_dest = move.location_dest_id.valuation_in_account_id.id
2230         else:
2231             acc_dest = accounts['stock_account_output']
2232
2233         acc_valuation = accounts.get('property_stock_valuation_account_id', False)
2234         journal_id = accounts['stock_journal']
2235
2236         if acc_dest == acc_valuation:
2237             raise osv.except_osv(_('Error!'),  _('Cannot create Journal Entry, Output Account of this product and Valuation account on category of this product are same.'))
2238
2239         if acc_src == acc_valuation:
2240             raise osv.except_osv(_('Error!'),  _('Cannot create Journal Entry, Input Account of this product and Valuation account on category of this product are same.'))
2241
2242         if not acc_src:
2243             raise osv.except_osv(_('Error!'),  _('Please define stock input account for this product or its category: "%s" (id: %d)') % \
2244                                     (move.product_id.name, move.product_id.id,))
2245         if not acc_dest:
2246             raise osv.except_osv(_('Error!'),  _('Please define stock output account for this product or its category: "%s" (id: %d)') % \
2247                                     (move.product_id.name, move.product_id.id,))
2248         if not journal_id:
2249             raise osv.except_osv(_('Error!'), _('Please define journal on the product category: "%s" (id: %d)') % \
2250                                     (move.product_id.categ_id.name, move.product_id.categ_id.id,))
2251         if not acc_valuation:
2252             raise osv.except_osv(_('Error!'), _('Please define inventory valuation account on the product category: "%s" (id: %d)') % \
2253                                     (move.product_id.categ_id.name, move.product_id.categ_id.id,))
2254         return journal_id, acc_src, acc_dest, acc_valuation
2255
2256     def _get_reference_accounting_values_for_valuation(self, cr, uid, move, context=None):
2257         """
2258         Return the reference amount and reference currency representing the inventory valuation for this move.
2259         These reference values should possibly be converted before being posted in Journals to adapt to the primary
2260         and secondary currencies of the relevant accounts.
2261         """
2262         product_uom_obj = self.pool.get('product.uom')
2263
2264         # by default the reference currency is that of the move's company
2265         reference_currency_id = move.company_id.currency_id.id
2266
2267         default_uom = move.product_id.uom_id.id
2268         qty = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
2269
2270         # if product is set to average price and a specific value was entered in the picking wizard,
2271         # we use it
2272         if move.product_id.cost_method == 'average' and move.price_unit:
2273             reference_amount = qty * move.price_unit
2274             reference_currency_id = move.price_currency_id.id or reference_currency_id
2275
2276         # Otherwise we default to the company's valuation price type, considering that the values of the
2277         # valuation field are expressed in the default currency of the move's company.
2278         else:
2279             if context is None:
2280                 context = {}
2281             currency_ctx = dict(context, currency_id = move.company_id.currency_id.id)
2282             amount_unit = move.product_id.price_get('standard_price', context=currency_ctx)[move.product_id.id]
2283             reference_amount = amount_unit * qty
2284
2285         return reference_amount, reference_currency_id
2286
2287
2288     def _create_product_valuation_moves(self, cr, uid, move, context=None):
2289         """
2290         Generate the appropriate accounting moves if the product being moves is subject
2291         to real_time valuation tracking, and the source or destination location is
2292         a transit location or is outside of the company.
2293         """
2294         if move.product_id.valuation == 'real_time': # FIXME: product valuation should perhaps be a property?
2295             if context is None:
2296                 context = {}
2297             src_company_ctx = dict(context,force_company=move.location_id.company_id.id)
2298             dest_company_ctx = dict(context,force_company=move.location_dest_id.company_id.id)
2299             account_moves = []
2300             # Outgoing moves (or cross-company output part)
2301             if move.location_id.company_id \
2302                 and (move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal'\
2303                      or move.location_id.company_id != move.location_dest_id.company_id):
2304                 journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, src_company_ctx)
2305                 reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx)
2306                 #returning goods to supplier
2307                 if move.location_dest_id.usage == 'supplier':
2308                     account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_src, reference_amount, reference_currency_id, context))]
2309                 else:
2310                     account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_dest, reference_amount, reference_currency_id, context))]
2311
2312             # Incoming moves (or cross-company input part)
2313             if move.location_dest_id.company_id \
2314                 and (move.location_id.usage != 'internal' and move.location_dest_id.usage == 'internal'\
2315                      or move.location_id.company_id != move.location_dest_id.company_id):
2316                 journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, dest_company_ctx)
2317                 reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx)
2318                 #goods return from customer
2319                 if move.location_id.usage == 'customer':
2320                     account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_dest, acc_valuation, reference_amount, reference_currency_id, context))]
2321                 else:
2322                     account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_src, acc_valuation, reference_amount, reference_currency_id, context))]
2323
2324             move_obj = self.pool.get('account.move')
2325             for j_id, move_lines in account_moves:
2326                 move_obj.create(cr, uid,
2327                         {
2328                          'journal_id': j_id,
2329                          'line_id': move_lines,
2330                          'ref': move.picking_id and move.picking_id.name})
2331
2332
2333     def action_done(self, cr, uid, ids, context=None):
2334         """ Makes the move done and if all moves are done, it will finish the picking.
2335         @return:
2336         """
2337         picking_ids = []
2338         move_ids = []
2339         wf_service = netsvc.LocalService("workflow")
2340         if context is None:
2341             context = {}
2342
2343         todo = []
2344         for move in self.browse(cr, uid, ids, context=context):
2345             if move.state=="draft":
2346                 todo.append(move.id)
2347         if todo:
2348             self.action_confirm(cr, uid, todo, context=context)
2349             todo = []
2350
2351         for move in self.browse(cr, uid, ids, context=context):
2352             if move.state in ['done','cancel']:
2353                 continue
2354             move_ids.append(move.id)
2355
2356             if move.picking_id:
2357                 picking_ids.append(move.picking_id.id)
2358             if move.move_dest_id.id and (move.state != 'done'):
2359                 # Downstream move should only be triggered if this move is the last pending upstream move
2360                 other_upstream_move_ids = self.search(cr, uid, [('id','!=',move.id),('state','not in',['done','cancel']),
2361                                             ('move_dest_id','=',move.move_dest_id.id)], context=context)
2362                 if not other_upstream_move_ids:
2363                     self.write(cr, uid, [move.id], {'move_history_ids': [(4, move.move_dest_id.id)]})
2364                     if move.move_dest_id.state in ('waiting', 'confirmed'):
2365                         self.force_assign(cr, uid, [move.move_dest_id.id], context=context)
2366                         if move.move_dest_id.picking_id:
2367                             wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
2368                         if move.move_dest_id.auto_validate:
2369                             self.action_done(cr, uid, [move.move_dest_id.id], context=context)
2370
2371             self._create_product_valuation_moves(cr, uid, move, context=context)
2372             if move.state not in ('confirmed','done','assigned'):
2373                 todo.append(move.id)
2374
2375         if todo:
2376             self.action_confirm(cr, uid, todo, context=context)
2377
2378         self.write(cr, uid, move_ids, {'state': 'done', 'date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
2379         for id in move_ids:
2380              wf_service.trg_trigger(uid, 'stock.move', id, cr)
2381
2382         for pick_id in picking_ids:
2383             wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
2384
2385         return True
2386
2387     def _create_account_move_line(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=None):
2388         """
2389         Generate the account.move.line values to post to track the stock valuation difference due to the
2390         processing of the given stock move.
2391         """
2392         # prepare default values considering that the destination accounts have the reference_currency_id as their main currency
2393         partner_id = (move.picking_id.partner_id and self.pool.get('res.partner')._find_accounting_partner(move.picking_id.partner_id).id) or False
2394         debit_line_vals = {
2395                     'name': move.name,
2396                     'product_id': move.product_id and move.product_id.id or False,
2397                     'quantity': move.product_qty,
2398                     'ref': move.picking_id and move.picking_id.name or False,
2399                     'date': time.strftime('%Y-%m-%d'),
2400                     'partner_id': partner_id,
2401                     'debit': reference_amount,
2402                     'account_id': dest_account_id,
2403         }
2404         credit_line_vals = {
2405                     'name': move.name,
2406                     'product_id': move.product_id and move.product_id.id or False,
2407                     'quantity': move.product_qty,
2408                     'ref': move.picking_id and move.picking_id.name or False,
2409                     'date': time.strftime('%Y-%m-%d'),
2410                     'partner_id': partner_id,
2411                     'credit': reference_amount,
2412                     'account_id': src_account_id,
2413         }
2414
2415         # if we are posting to accounts in a different currency, provide correct values in both currencies correctly
2416         # when compatible with the optional secondary currency on the account.
2417         # Financial Accounts only accept amounts in secondary currencies if there's no secondary currency on the account
2418         # or if it's the same as that of the secondary amount being posted.
2419         account_obj = self.pool.get('account.account')
2420         src_acct, dest_acct = account_obj.browse(cr, uid, [src_account_id, dest_account_id], context=context)
2421         src_main_currency_id = src_acct.company_id.currency_id.id
2422         dest_main_currency_id = dest_acct.company_id.currency_id.id
2423         cur_obj = self.pool.get('res.currency')
2424         if reference_currency_id != src_main_currency_id:
2425             # fix credit line:
2426             credit_line_vals['credit'] = cur_obj.compute(cr, uid, reference_currency_id, src_main_currency_id, reference_amount, context=context)
2427             if (not src_acct.currency_id) or src_acct.currency_id.id == reference_currency_id:
2428                 credit_line_vals.update(currency_id=reference_currency_id, amount_currency=reference_amount)
2429         if reference_currency_id != dest_main_currency_id:
2430             # fix debit line:
2431             debit_line_vals['debit'] = cur_obj.compute(cr, uid, reference_currency_id, dest_main_currency_id, reference_amount, context=context)
2432             if (not dest_acct.currency_id) or dest_acct.currency_id.id == reference_currency_id:
2433                 debit_line_vals.update(currency_id=reference_currency_id, amount_currency=reference_amount)
2434
2435         return [(0, 0, debit_line_vals), (0, 0, credit_line_vals)]
2436
2437     def unlink(self, cr, uid, ids, context=None):
2438         if context is None:
2439             context = {}
2440         ctx = context.copy()
2441         for move in self.browse(cr, uid, ids, context=context):
2442             if move.state != 'draft' and not ctx.get('call_unlink', False):
2443                 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2444         return super(stock_move, self).unlink(
2445             cr, uid, ids, context=ctx)
2446
2447     # _create_lot function is not used anywhere
2448     def _create_lot(self, cr, uid, ids, product_id, prefix=False):
2449         """ Creates production lot
2450         @return: Production lot id
2451         """
2452         prodlot_obj = self.pool.get('stock.production.lot')
2453         prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
2454         return prodlot_id
2455
2456     def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
2457         """ Move the scrap/damaged product into scrap location
2458         @param cr: the database cursor
2459         @param uid: the user id
2460         @param ids: ids of stock move object to be scrapped
2461         @param quantity : specify scrap qty
2462         @param location_id : specify scrap location
2463         @param context: context arguments
2464         @return: Scraped lines
2465         """
2466         #quantity should in MOVE UOM
2467         if quantity <= 0:
2468             raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2469         res = []
2470         for move in self.browse(cr, uid, ids, context=context):
2471             source_location = move.location_id
2472             if move.state == 'done':
2473                 source_location = move.location_dest_id
2474             if source_location.usage != 'internal':
2475                 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2476                 raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2477             move_qty = move.product_qty
2478             uos_qty = quantity / move_qty * move.product_uos_qty
2479             default_val = {
2480                 'location_id': source_location.id,
2481                 'product_qty': quantity,
2482                 'product_uos_qty': uos_qty,
2483                 'state': move.state,
2484                 'scrapped': True,
2485                 'location_dest_id': location_id,
2486                 'tracking_id': move.tracking_id.id,
2487                 'prodlot_id': move.prodlot_id.id,
2488             }
2489             new_move = self.copy(cr, uid, move.id, default_val)
2490
2491             res += [new_move]
2492             product_obj = self.pool.get('product.product')
2493             for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2494                 if move.picking_id:
2495                     uom = product.uom_id.name if product.uom_id else ''
2496                     message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2497                     move.picking_id.message_post(body=message)
2498
2499         self.action_done(cr, uid, res, context=context)
2500         return res
2501
2502     # action_split function is not used anywhere
2503     # FIXME: deprecate this method
2504     def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
2505         """ Split Stock Move lines into production lot which specified split by quantity.
2506         @param cr: the database cursor
2507         @param uid: the user id
2508         @param ids: ids of stock move object to be splited
2509         @param split_by_qty : specify split by qty
2510         @param prefix : specify prefix of production lot
2511         @param with_lot : if true, prodcution lot will assign for split line otherwise not.
2512         @param context: context arguments
2513         @return: Splited move lines
2514         """
2515
2516         if context is None:
2517             context = {}
2518         if quantity <= 0:
2519             raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
2520
2521         res = []
2522
2523         for move in self.browse(cr, uid, ids, context=context):
2524             if split_by_qty <= 0 or quantity == 0:
2525                 return res
2526
2527             uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
2528
2529             quantity_rest = quantity % split_by_qty
2530             uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
2531
2532             update_val = {
2533                 'product_qty': split_by_qty,
2534                 'product_uos_qty': uos_qty,
2535             }
2536             for idx in range(int(quantity//split_by_qty)):
2537                 if not idx and move.product_qty<=quantity:
2538                     current_move = move.id
2539                 else:
2540                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
2541                 res.append(current_move)
2542                 if with_lot:
2543                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
2544
2545                 self.write(cr, uid, [current_move], update_val)
2546
2547
2548             if quantity_rest > 0:
2549                 idx = int(quantity//split_by_qty)
2550                 update_val['product_qty'] = quantity_rest
2551                 update_val['product_uos_qty'] = uos_qty_rest
2552                 if not idx and move.product_qty<=quantity:
2553                     current_move = move.id
2554                 else:
2555                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
2556
2557                 res.append(current_move)
2558
2559
2560                 if with_lot:
2561                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
2562
2563                 self.write(cr, uid, [current_move], update_val)
2564         return res
2565
2566     def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
2567         """ Consumed product with specific quatity from specific source location
2568         @param cr: the database cursor
2569         @param uid: the user id
2570         @param ids: ids of stock move object to be consumed
2571         @param quantity : specify consume quantity
2572         @param location_id : specify source location
2573         @param context: context arguments
2574         @return: Consumed lines
2575         """
2576         #quantity should in MOVE UOM
2577         if context is None:
2578             context = {}
2579         if quantity <= 0:
2580             raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
2581         res = []
2582         for move in self.browse(cr, uid, ids, context=context):
2583             move_qty = move.product_qty
2584             if move_qty <= 0:
2585                 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
2586             quantity_rest = move.product_qty
2587             quantity_rest -= quantity
2588             uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
2589             if quantity_rest <= 0:
2590                 quantity_rest = 0
2591                 uos_qty_rest = 0
2592                 quantity = move.product_qty
2593
2594             uos_qty = quantity / move_qty * move.product_uos_qty
2595             if quantity_rest > 0:
2596                 default_val = {
2597                     'product_qty': quantity,
2598                     'product_uos_qty': uos_qty,
2599                     'state': move.state,
2600                     'location_id': location_id or move.location_id.id,
2601                 }
2602                 current_move = self.copy(cr, uid, move.id, default_val)
2603                 res += [current_move]
2604                 update_val = {}
2605                 update_val['product_qty'] = quantity_rest
2606                 update_val['product_uos_qty'] = uos_qty_rest
2607                 self.write(cr, uid, [move.id], update_val)
2608
2609             else:
2610                 quantity_rest = quantity
2611                 uos_qty_rest =  uos_qty
2612                 res += [move.id]
2613                 update_val = {
2614                         'product_qty' : quantity_rest,
2615                         'product_uos_qty' : uos_qty_rest,
2616                         'location_id': location_id or move.location_id.id,
2617                 }
2618                 self.write(cr, uid, [move.id], update_val)
2619
2620         self.action_done(cr, uid, res, context=context)
2621
2622         return res
2623
2624     # FIXME: needs refactoring, this code is partially duplicated in stock_picking.do_partial()!
2625     def do_partial(self, cr, uid, ids, partial_datas, context=None):
2626         """ Makes partial pickings and moves done.
2627         @param partial_datas: Dictionary containing details of partial picking
2628                           like partner_id, delivery_date, delivery
2629                           moves with product_id, product_qty, uom
2630         """
2631         res = {}
2632         picking_obj = self.pool.get('stock.picking')
2633         product_obj = self.pool.get('product.product')
2634         currency_obj = self.pool.get('res.currency')
2635         uom_obj = self.pool.get('product.uom')
2636
2637         if context is None:
2638             context = {}
2639
2640         complete, too_many, too_few = [], [], []
2641         move_product_qty = {}
2642         prodlot_ids = {}
2643         for move in self.browse(cr, uid, ids, context=context):
2644             if move.state in ('done', 'cancel'):
2645                 continue
2646             partial_data = partial_datas.get('move%s'%(move.id), False)
2647             assert partial_data, _('Missing partial picking data for move #%s.') % (move.id)
2648             product_qty = partial_data.get('product_qty',0.0)
2649             move_product_qty[move.id] = product_qty
2650             product_uom = partial_data.get('product_uom',False)
2651             product_price = partial_data.get('product_price',0.0)
2652             product_currency = partial_data.get('product_currency',False)
2653             prodlot_ids[move.id] = partial_data.get('prodlot_id')
2654             if move.product_qty == product_qty:
2655                 complete.append(move)
2656             elif move.product_qty > product_qty:
2657                 too_few.append(move)
2658             else:
2659                 too_many.append(move)
2660
2661             # Average price computation
2662             if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
2663                 product = product_obj.browse(cr, uid, move.product_id.id)
2664                 move_currency_id = move.company_id.currency_id.id
2665                 context['currency_id'] = move_currency_id
2666                 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
2667                 if qty > 0:
2668                     new_price = currency_obj.compute(cr, uid, product_currency,
2669                             move_currency_id, product_price)
2670                     new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
2671                             product.uom_id.id)
2672                     if product.qty_available <= 0:
2673                         new_std_price = new_price
2674                     else:
2675                         # Get the standard price
2676                         amount_unit = product.price_get('standard_price', context=context)[product.id]
2677                         new_std_price = ((amount_unit * product.qty_available)\
2678                             + (new_price * qty))/(product.qty_available + qty)
2679
2680                     product_obj.write(cr, uid, [product.id],{'standard_price': new_std_price})
2681
2682                     # Record the values that were chosen in the wizard, so they can be
2683                     # used for inventory valuation if real-time valuation is enabled.
2684                     self.write(cr, uid, [move.id],
2685                                 {'price_unit': product_price,
2686                                  'price_currency_id': product_currency,
2687                                 })
2688
2689         for move in too_few:
2690             product_qty = move_product_qty[move.id]
2691             if product_qty != 0:
2692                 defaults = {
2693                             'product_qty' : product_qty,
2694                             'product_uos_qty': product_qty,
2695                             'picking_id' : move.picking_id.id,
2696                             'state': 'assigned',
2697                             'move_dest_id': False,
2698                             'price_unit': move.price_unit,
2699                             }
2700                 prodlot_id = prodlot_ids[move.id]
2701                 if prodlot_id:
2702                     defaults.update(prodlot_id=prodlot_id)
2703                 new_move = self.copy(cr, uid, move.id, defaults)
2704                 complete.append(self.browse(cr, uid, new_move))
2705             self.write(cr, uid, [move.id],
2706                     {
2707                         'product_qty': move.product_qty - product_qty,
2708                         'product_uos_qty': move.product_qty - product_qty,
2709                         'prodlot_id': False,
2710                         'tracking_id': False,
2711                     })
2712
2713
2714         for move in too_many:
2715             self.write(cr, uid, [move.id],
2716                     {
2717                         'product_qty': move.product_qty,
2718                         'product_uos_qty': move.product_qty,
2719                     })
2720             complete.append(move)
2721
2722         for move in complete:
2723             if prodlot_ids.get(move.id):
2724                 self.write(cr, uid, [move.id],{'prodlot_id': prodlot_ids.get(move.id)})
2725             self.action_done(cr, uid, [move.id], context=context)
2726             if  move.picking_id.id :
2727                 # TOCHECK : Done picking if all moves are done
2728                 cr.execute("""
2729                     SELECT move.id FROM stock_picking pick
2730                     RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
2731                     WHERE pick.id = %s""",
2732                             ('done', move.picking_id.id))
2733                 res = cr.fetchall()
2734                 if len(res) == len(move.picking_id.move_lines):
2735                     picking_obj.action_move(cr, uid, [move.picking_id.id])
2736                     picking_obj.signal_button_done(cr, uid, [move.picking_id.id])
2737
2738         return [move.id for move in complete]
2739
2740 stock_move()
2741
2742 class stock_inventory(osv.osv):
2743     _name = "stock.inventory"
2744     _description = "Inventory"
2745     _columns = {
2746         'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
2747         'date': fields.datetime('Creation Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2748         'date_done': fields.datetime('Date done'),
2749         'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
2750         'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
2751         'state': fields.selection( (('draft', 'Draft'), ('cancel','Cancelled'), ('confirm','Confirmed'), ('done', 'Done')), 'Status', readonly=True, select=True),
2752         'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft':[('readonly',False)]}),
2753
2754     }
2755     _defaults = {
2756         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
2757         'state': 'draft',
2758         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
2759     }
2760
2761     def copy(self, cr, uid, id, default=None, context=None):
2762         if default is None:
2763             default = {}
2764         default = default.copy()
2765         default.update({'move_ids': [], 'date_done': False})
2766         return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2767
2768     def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2769         """ Creates a stock move from an inventory line
2770         @param inventory_line:
2771         @param move_vals:
2772         @return:
2773         """
2774         return self.pool.get('stock.move').create(cr, uid, move_vals)
2775
2776     def action_done(self, cr, uid, ids, context=None):
2777         """ Finish the inventory
2778         @return: True
2779         """
2780         if context is None:
2781             context = {}
2782         move_obj = self.pool.get('stock.move')
2783         for inv in self.browse(cr, uid, ids, context=context):
2784             move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2785             self.write(cr, uid, [inv.id], {'state':'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
2786         return True
2787
2788     def action_confirm(self, cr, uid, ids, context=None):
2789         """ Confirm the inventory and writes its finished date
2790         @return: True
2791         """
2792         if context is None:
2793             context = {}
2794         # to perform the correct inventory corrections we need analyze stock location by
2795         # location, never recursively, so we use a special context
2796         product_context = dict(context, compute_child=False)
2797
2798         location_obj = self.pool.get('stock.location')
2799         for inv in self.browse(cr, uid, ids, context=context):
2800             move_ids = []
2801             for line in inv.inventory_line_id:
2802                 pid = line.product_id.id
2803                 product_context.update(uom=line.product_uom.id, to_date=inv.date, date=inv.date, prodlot_id=line.prod_lot_id.id)
2804                 amount = location_obj._product_get(cr, uid, line.location_id.id, [pid], product_context)[pid]
2805                 change = line.product_qty - amount
2806                 lot_id = line.prod_lot_id.id
2807                 if change:
2808                     location_id = line.product_id.property_stock_inventory.id
2809                     value = {
2810                         'name': _('INV:') + (line.inventory_id.name or ''),
2811                         'product_id': line.product_id.id,
2812                         'product_uom': line.product_uom.id,
2813                         'prodlot_id': lot_id,
2814                         'date': inv.date,
2815                     }
2816
2817                     if change > 0:
2818                         value.update( {
2819                             'product_qty': change,
2820                             'location_id': location_id,
2821                             'location_dest_id': line.location_id.id,
2822                         })
2823                     else:
2824                         value.update( {
2825                             'product_qty': -change,
2826                             'location_id': line.location_id.id,
2827                             'location_dest_id': location_id,
2828                         })
2829                     move_ids.append(self._inventory_line_hook(cr, uid, line, value))
2830             self.write(cr, uid, [inv.id], {'state': 'confirm', 'move_ids': [(6, 0, move_ids)]})
2831             self.pool.get('stock.move').action_confirm(cr, uid, move_ids, context=context)
2832         return True
2833
2834     def action_cancel_draft(self, cr, uid, ids, context=None):
2835         """ Cancels the stock move and change inventory state to draft.
2836         @return: True
2837         """
2838         for inv in self.browse(cr, uid, ids, context=context):
2839             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2840             self.write(cr, uid, [inv.id], {'state':'draft'}, context=context)
2841         return True
2842
2843     def action_cancel_inventory(self, cr, uid, ids, context=None):
2844         """ Cancels both stock move and inventory
2845         @return: True
2846         """
2847         move_obj = self.pool.get('stock.move')
2848         account_move_obj = self.pool.get('account.move')
2849         for inv in self.browse(cr, uid, ids, context=context):
2850             move_obj.action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2851             for move in inv.move_ids:
2852                  account_move_ids = account_move_obj.search(cr, uid, [('name', '=', move.name)])
2853                  if account_move_ids:
2854                      account_move_data_l = account_move_obj.read(cr, uid, account_move_ids, ['state'], context=context)
2855                      for account_move in account_move_data_l:
2856                          if account_move['state'] == 'posted':
2857                              raise osv.except_osv(_('User Error!'),
2858                                                   _('In order to cancel this inventory, you must first unpost related journal entries.'))
2859                          account_move_obj.unlink(cr, uid, [account_move['id']], context=context)
2860             self.write(cr, uid, [inv.id], {'state': 'cancel'}, context=context)
2861         return True
2862
2863 stock_inventory()
2864
2865 class stock_inventory_line(osv.osv):
2866     _name = "stock.inventory.line"
2867     _description = "Inventory Line"
2868     _rec_name = "inventory_id"
2869     _columns = {
2870         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2871         'location_id': fields.many2one('stock.location', 'Location', required=True),
2872         'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2873         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2874         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2875         'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True, select=True, readonly=True),
2876         'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2877         'state': fields.related('inventory_id','state',type='char',string='Status',readonly=True),
2878     }
2879
2880     def _default_stock_location(self, cr, uid, context=None):
2881         stock_location = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2882         return stock_location.id
2883
2884     _defaults = {
2885         'location_id': _default_stock_location
2886     }
2887
2888     def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, to_date=False):
2889         """ Changes UoM and name if product_id changes.
2890         @param location_id: Location id
2891         @param product: Changed product_id
2892         @param uom: UoM product
2893         @return:  Dictionary of changed values
2894         """
2895         if not product:
2896             return {'value': {'product_qty': 0.0, 'product_uom': False, 'prod_lot_id': False}}
2897         obj_product = self.pool.get('product.product').browse(cr, uid, product)
2898         uom = uom or obj_product.uom_id.id
2899         amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date, 'compute_child': False})[product]
2900         result = {'product_qty': amount, 'product_uom': uom, 'prod_lot_id': False}
2901         return {'value': result}
2902
2903 stock_inventory_line()
2904
2905 #----------------------------------------------------------
2906 # Stock Warehouse
2907 #----------------------------------------------------------
2908 class stock_warehouse(osv.osv):
2909     _name = "stock.warehouse"
2910     _description = "Warehouse"
2911     _columns = {
2912         'name': fields.char('Name', size=128, required=True, select=True),
2913         'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
2914         'partner_id': fields.many2one('res.partner', 'Owner Address'),
2915         'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
2916         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','=','internal')]),
2917         'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
2918     }
2919
2920     def _default_lot_input_stock_id(self, cr, uid, context=None):
2921         lot_input_stock = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_stock')
2922         return lot_input_stock.id
2923
2924     def _default_lot_output_id(self, cr, uid, context=None):
2925         lot_output = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'stock_location_output')
2926         return lot_output.id
2927
2928     _defaults = {
2929         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2930         'lot_input_id': _default_lot_input_stock_id,
2931         'lot_stock_id': _default_lot_input_stock_id,
2932         'lot_output_id': _default_lot_output_id,
2933     }
2934
2935 stock_warehouse()
2936
2937 #----------------------------------------------------------
2938 # "Empty" Classes that are used to vary from the original stock.picking  (that are dedicated to the internal pickings)
2939 #   in order to offer a different usability with different views, labels, available reports/wizards...
2940 #----------------------------------------------------------
2941 class stock_picking_in(osv.osv):
2942     _name = "stock.picking.in"
2943     _inherit = "stock.picking"
2944     _table = "stock_picking"
2945     _description = "Incoming Shipments"
2946
2947     def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2948         return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
2949
2950     def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
2951         return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
2952
2953     def check_access_rights(self, cr, uid, operation, raise_exception=True):
2954         #override in order to redirect the check of acces rights on the stock.picking object
2955         return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
2956
2957     def check_access_rule(self, cr, uid, ids, operation, context=None):
2958         #override in order to redirect the check of acces rules on the stock.picking object
2959         return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
2960
2961     def create_workflow(self, cr, uid, ids, context=None):
2962         # overridden in order to trigger the workflow of stock.picking at the end of create,
2963         # write and unlink operation instead of its own workflow (which is not existing)
2964         return self.pool.get('stock.picking').create_workflow(cr, uid, ids, context=context)
2965
2966     def delete_workflow(self, cr, uid, ids, context=None):
2967         # overridden in order to trigger the workflow of stock.picking at the end of create,
2968         # write and unlink operation instead of its own workflow (which is not existing)
2969         return self.pool.get('stock.picking').delete_workflow(cr, uid, ids, context=context)
2970
2971     def step_workflow(self, cr, uid, ids, context=None):
2972         # overridden in order to trigger the workflow of stock.picking at the end of create,
2973         # write and unlink operation instead of its own workflow (which is not existing)
2974         return self.pool.get('stock.picking').step_workflow(cr, uid, ids, context=context)
2975
2976     def signal_workflow(self, cr, uid, ids, signal, context=None):
2977         # overridden in order to fire the workflow signal on given stock.picking workflow instance
2978         # instead of its own workflow (which is not existing)
2979         return self.pool.get('stock.picking').signal_workflow(cr, uid, ids, signal, context=context)
2980
2981     _columns = {
2982         'backorder_id': fields.many2one('stock.picking.in', '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),
2983         'state': fields.selection(
2984             [('draft', 'Draft'),
2985             ('auto', 'Waiting Another Operation'),
2986             ('confirmed', 'Waiting Availability'),
2987             ('assigned', 'Ready to Receive'),
2988             ('done', 'Received'),
2989             ('cancel', 'Cancelled'),],
2990             'Status', readonly=True, select=True,
2991             help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
2992                  * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
2993                  * Waiting Availability: still waiting for the availability of products\n
2994                  * Ready to Receive: products reserved, simply waiting for confirmation.\n
2995                  * Received: has been processed, can't be modified or cancelled anymore\n
2996                  * Cancelled: has been cancelled, can't be confirmed anymore"""),
2997     }
2998     _defaults = {
2999         'type': 'in',
3000     }
3001
3002 class stock_picking_out(osv.osv):
3003     _name = "stock.picking.out"
3004     _inherit = "stock.picking"
3005     _table = "stock_picking"
3006     _description = "Delivery Orders"
3007
3008     def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
3009         return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
3010
3011     def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
3012         return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
3013
3014     def check_access_rights(self, cr, uid, operation, raise_exception=True):
3015         #override in order to redirect the check of acces rights on the stock.picking object
3016         return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
3017
3018     def check_access_rule(self, cr, uid, ids, operation, context=None):
3019         #override in order to redirect the check of acces rules on the stock.picking object
3020         return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
3021
3022     def create_workflow(self, cr, uid, ids, context=None):
3023         # overridden in order to trigger the workflow of stock.picking at the end of create,
3024         # write and unlink operation instead of its own workflow (which is not existing)
3025         return self.pool.get('stock.picking').create_workflow(cr, uid, ids, context=context)
3026
3027     def delete_workflow(self, cr, uid, ids, context=None):
3028         # overridden in order to trigger the workflow of stock.picking at the end of create,
3029         # write and unlink operation instead of its own workflow (which is not existing)
3030         return self.pool.get('stock.picking').delete_workflow(cr, uid, ids, context=context)
3031
3032     def step_workflow(self, cr, uid, ids, context=None):
3033         # overridden in order to trigger the workflow of stock.picking at the end of create,
3034         # write and unlink operation instead of its own workflow (which is not existing)
3035         return self.pool.get('stock.picking').step_workflow(cr, uid, ids, context=context)
3036
3037     def signal_workflow(self, cr, uid, ids, signal, context=None):
3038         # overridden in order to fire the workflow signal on given stock.picking workflow instance
3039         # instead of its own workflow (which is not existing)
3040         return self.pool.get('stock.picking').signal_workflow(cr, uid, ids, signal, context=context)
3041
3042     _columns = {
3043         'backorder_id': fields.many2one('stock.picking.out', '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),
3044         'state': fields.selection(
3045             [('draft', 'Draft'),
3046             ('auto', 'Waiting Another Operation'),
3047             ('confirmed', 'Waiting Availability'),
3048             ('assigned', 'Ready to Deliver'),
3049             ('done', 'Delivered'),
3050             ('cancel', 'Cancelled'),],
3051             'Status', readonly=True, select=True,
3052             help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
3053                  * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
3054                  * Waiting Availability: still waiting for the availability of products\n
3055                  * Ready to Deliver: products reserved, simply waiting for confirmation.\n
3056                  * Delivered: has been processed, can't be modified or cancelled anymore\n
3057                  * Cancelled: has been cancelled, can't be confirmed anymore"""),
3058     }
3059     _defaults = {
3060         'type': 'out',
3061     }
3062
3063 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: