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