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