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