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