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