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