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