1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import datetime
23 from dateutil.relativedelta import relativedelta
25 from operator import itemgetter
26 from itertools import groupby
28 from openerp.osv import fields, osv, orm
29 from openerp.tools.translate import _
30 from openerp import netsvc
31 from openerp import tools
32 from openerp.tools import float_compare, DEFAULT_SERVER_DATETIME_FORMAT
33 import openerp.addons.decimal_precision as dp
35 _logger = logging.getLogger(__name__)
37 #----------------------------------------------------------
39 #----------------------------------------------------------
40 class stock_incoterms(osv.osv):
41 _name = "stock.incoterms"
42 _description = "Incoterms"
44 'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms.They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
45 'code': fields.char('Code', size=3, required=True, help="Code for Incoterms"),
46 'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM without deleting it."),
54 class stock_journal(osv.osv):
55 _name = "stock.journal"
56 _description = "Stock Journal"
58 'name': fields.char('Stock Journal', size=32, required=True),
59 'user_id': fields.many2one('res.users', 'Responsible'),
62 'user_id': lambda s, c, u, ctx: u
67 #----------------------------------------------------------
69 #----------------------------------------------------------
70 class stock_location(osv.osv):
71 _name = "stock.location"
72 _description = "Location"
73 _parent_name = "location_id"
75 _parent_order = 'posz,name'
76 _order = 'parent_left'
78 # TODO: implement name_search() in a way that matches the results of name_get!
80 def name_get(self, cr, uid, ids, context=None):
81 # always return the full hierarchical name
82 res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
85 def _complete_name(self, cr, uid, ids, name, args, context=None):
86 """ Forms complete name of location from parent location to child location.
87 @return: Dictionary of values
90 for m in self.browse(cr, uid, ids, context=context):
92 parent = m.location_id
94 names.append(parent.name)
95 parent = parent.location_id
96 res[m.id] = ' / '.join(reversed(names))
99 def _get_sublocations(self, cr, uid, ids, context=None):
100 """ return all sublocations of the given stock locations (included) """
101 return self.search(cr, uid, [('id', 'child_of', ids)], context=context)
103 def _product_value(self, cr, uid, ids, field_names, arg, context=None):
104 """Computes stock value (real and virtual) for a product, as well as stock qty (real and virtual).
105 @param field_names: Name of field
106 @return: Dictionary of values
108 prod_id = context and context.get('product_id', False)
111 return dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
113 product_product_obj = self.pool.get('product.product')
115 cr.execute('select distinct product_id, location_id from stock_move where location_id in %s', (tuple(ids), ))
116 dict1 = cr.dictfetchall()
117 cr.execute('select distinct product_id, location_dest_id as location_id from stock_move where location_dest_id in %s', (tuple(ids), ))
118 dict2 = cr.dictfetchall()
119 res_products_by_location = sorted(dict1+dict2, key=itemgetter('location_id'))
120 products_by_location = dict((k, [v['product_id'] for v in itr]) for k, itr in groupby(res_products_by_location, itemgetter('location_id')))
122 result = dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
123 result.update(dict([(i, {}.fromkeys(field_names, 0.0)) for i in list(set([aaa['location_id'] for aaa in res_products_by_location]))]))
125 currency_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id
126 currency_obj = self.pool.get('res.currency')
127 currency = currency_obj.browse(cr, uid, currency_id, context=context)
128 for loc_id, product_ids in products_by_location.items():
130 product_ids = [prod_id]
131 c = (context or {}).copy()
132 c['location'] = loc_id
133 for prod in product_product_obj.browse(cr, uid, product_ids, context=c):
134 for f in field_names:
135 if f == 'stock_real':
136 if loc_id not in result:
138 result[loc_id][f] += prod.qty_available
139 elif f == 'stock_virtual':
140 result[loc_id][f] += prod.virtual_available
141 elif f == 'stock_real_value':
142 amount = prod.qty_available * prod.standard_price
143 amount = currency_obj.round(cr, uid, currency, amount)
144 result[loc_id][f] += amount
145 elif f == 'stock_virtual_value':
146 amount = prod.virtual_available * prod.standard_price
147 amount = currency_obj.round(cr, uid, currency, amount)
148 result[loc_id][f] += amount
152 'name': fields.char('Location Name', size=64, required=True, translate=True),
153 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
154 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
155 help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
156 \n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
157 \n* Internal Location: Physical locations inside your own warehouses,
158 \n* Customer Location: Virtual location representing the destination location for products sent to your customers
159 \n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
160 \n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running.
161 \n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
163 # temporarily removed, as it's unused: 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
164 'complete_name': fields.function(_complete_name, type='char', size=256, string="Location Name",
165 store={'stock.location': (_get_sublocations, ['name', 'location_id'], 10)}),
167 'stock_real': fields.function(_product_value, type='float', string='Real Stock', multi="stock"),
168 'stock_virtual': fields.function(_product_value, type='float', string='Virtual Stock', multi="stock"),
170 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
171 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
173 'chained_journal_id': fields.many2one('stock.journal', 'Chaining Journal',help="Inventory Journal in which the chained move will be written, if the Chaining Type is not Transparent (no journal is used if left empty)"),
174 'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
175 'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
176 'Chained Location Type', required=True,
177 help="Determines whether this location is chained to another location, i.e. any incoming product in this location \n" \
178 "should next go to the chained location. The chained location is determined according to the type :"\
179 "\n* None: No chaining at all"\
180 "\n* Customer: The chained location will be taken from the Customer Location field on the Partner form of the Partner that is specified in the Picking list of the incoming products." \
181 "\n* Fixed Location: The chained location is taken from the next field: Chained Location if Fixed." \
183 'chained_auto_packing': fields.selection(
184 [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
187 help="This is used only if you select a chained location type.\n" \
188 "The 'Automatic Move' value will create a stock move after the current one that will be "\
189 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
190 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
192 'chained_picking_type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', help="Shipping Type of the Picking List that will contain the chained move (leave empty to automatically detect the type based on the source and destination locations)."),
193 'chained_company_id': fields.many2one('res.company', 'Chained Company', help='The company the Picking List containing the chained move will belong to (leave empty to use the default company determination rules'),
194 'chained_delay': fields.integer('Chaining Lead Time',help="Delay between original move and chained move in days"),
195 'partner_id': fields.many2one('res.partner', 'Location Address',help="Address of customer or supplier."),
196 'icon': fields.selection(tools.icons, 'Icon', size=64,help="Icon show in hierarchical tree view"),
198 'comment': fields.text('Additional Information'),
199 'posx': fields.integer('Corridor (X)',help="Optional localization details, for information purpose only"),
200 'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
201 'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
203 'parent_left': fields.integer('Left Parent', select=1),
204 'parent_right': fields.integer('Right Parent', select=1),
205 'stock_real_value': fields.function(_product_value, type='float', string='Real Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
206 'stock_virtual_value': fields.function(_product_value, type='float', string='Virtual Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
207 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
208 'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'),
209 'valuation_in_account_id': fields.many2one('account.account', 'Stock Valuation Account (Incoming)', domain = [('type','=','other')],
210 help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
211 "this account will be used to hold the value of products being moved from an internal location "
212 "into this location, instead of the generic Stock Output Account set on the product. "
213 "This has no effect for internal locations."),
214 'valuation_out_account_id': fields.many2one('account.account', 'Stock Valuation Account (Outgoing)', domain = [('type','=','other')],
215 help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
216 "this account will be used to hold the value of products being moved out of this location "
217 "and into an internal location, instead of the generic Stock Output Account set on the product. "
218 "This has no effect for internal locations."),
223 'chained_location_type': 'none',
224 'chained_auto_packing': 'manual',
225 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
230 'scrap_location': False,
233 def chained_location_get(self, cr, uid, location, partner=None, product=None, context=None):
234 """ Finds chained location
235 @param location: Location id
236 @param partner: Partner id
237 @param product: Product id
238 @return: List of values
241 if location.chained_location_type == 'customer':
243 result = partner.property_stock_customer
245 loc_id = self.pool['res.partner'].default_get(cr, uid, ['property_stock_customer'], context=context)['property_stock_customer']
246 result = self.pool['stock.location'].browse(cr, uid, loc_id, context=context)
247 elif location.chained_location_type == 'fixed':
248 result = location.chained_location_id
250 return result, location.chained_auto_packing, location.chained_delay, location.chained_journal_id and location.chained_journal_id.id or False, location.chained_company_id and location.chained_company_id.id or False, location.chained_picking_type, False
253 def picking_type_get(self, cr, uid, from_location, to_location, context=None):
254 """ Gets type of picking.
255 @param from_location: Source location
256 @param to_location: Destination location
257 @return: Location type
260 if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
262 elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage == 'internal'):
266 def _product_get_all_report(self, cr, uid, ids, product_ids=False, context=None):
267 return self._product_get_report(cr, uid, ids, product_ids, context, recursive=True)
269 def _product_get_report(self, cr, uid, ids, product_ids=False,
270 context=None, recursive=False):
271 """ Finds the product quantity and price for particular location.
272 @param product_ids: Ids of product
273 @param recursive: True or False
274 @return: Dictionary of values
278 product_obj = self.pool.get('product.product')
279 # Take the user company and pricetype
280 context['currency_id'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
282 # To be able to offer recursive or non-recursive reports we need to prevent recursive quantities by default
283 context['compute_child'] = False
286 product_ids = product_obj.search(cr, uid, [], context={'active_test': False})
288 products = product_obj.browse(cr, uid, product_ids, context=context)
291 for product in products:
292 products_by_uom.setdefault(product.uom_id.id, [])
293 products_by_uom[product.uom_id.id].append(product)
294 products_by_id.setdefault(product.id, [])
295 products_by_id[product.id] = product
298 result['product'] = []
302 for uom_id in products_by_uom.keys():
303 fnc = self._product_get
305 fnc = self._product_all_get
308 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
310 for product_id in qty.keys():
311 if not qty[product_id]:
313 product = products_by_id[product_id]
314 quantity_total += qty[product_id]
316 # Compute based on pricetype
317 # Choose the right filed standard_price to read
318 amount_unit = product.price_get('standard_price', context=context)[product.id]
319 price = qty[product_id] * amount_unit
322 result['product'].append({
323 'price': amount_unit,
324 'prod_name': product.name,
325 'code': product.default_code, # used by lot_overview_all report!
326 'variants': product.variants or '',
327 'uom': product.uom_id.name,
328 'prod_qty': qty[product_id],
329 'price_value': price,
331 result['total'] = quantity_total
332 result['total_price'] = total_price
335 def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context=None,
336 states=['done'], what=('in', 'out')):
338 @param product_ids: Ids of product
339 @param states: List of states
340 @param what: Tuple of
343 product_obj = self.pool.get('product.product')
351 return product_obj.get_product_available(cr, uid, product_ids, context=context)
353 def _product_get(self, cr, uid, id, product_ids=False, context=None, states=None):
361 ids = id and [id] or []
362 return self._product_get_multi_location(cr, uid, ids, product_ids, context=context, states=states)
364 def _product_all_get(self, cr, uid, id, product_ids=False, context=None, states=None):
367 # build the list of ids of children of the location given by id
368 ids = id and [id] or []
369 location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
370 return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
372 def _product_virtual_get(self, cr, uid, id, product_ids=False, context=None, states=None):
375 return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
377 def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None, lock=False):
379 Attempt to find a quantity ``product_qty`` (in the product's default uom or the uom passed in ``context``) of product ``product_id``
380 in locations with id ``ids`` and their child locations. If ``lock`` is True, the stock.move lines
381 of product with id ``product_id`` in the searched location will be write-locked using Postgres's
382 "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back, to prevent reservin
383 twice the same products.
384 If ``lock`` is True and the lock cannot be obtained (because another transaction has locked some of
385 the same stock.move lines), a log line will be output and False will be returned, as if there was
388 :param product_id: Id of product to reserve
389 :param product_qty: Quantity of product to reserve (in the product's default uom or the uom passed in ``context``)
390 :param lock: if True, the stock.move lines of product with id ``product_id`` in all locations (and children locations) with ``ids`` will
391 be write-locked using postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back. This is
392 to prevent reserving twice the same products.
393 :param context: optional context dictionary: if a 'uom' key is present it will be used instead of the default product uom to
394 compute the ``product_qty`` and in the return value.
395 :return: List of tuples in the form (qty, location_id) with the (partial) quantities that can be taken in each location to
396 reach the requested product_qty (``qty`` is expressed in the default uom of the product), of False if enough
397 products could not be found, or the lock could not be obtained (and ``lock`` was True).
403 uom_obj = self.pool.get('product.uom')
404 uom_rounding = self.pool.get('product.product').browse(cr, uid, product_id, context=context).uom_id.rounding
405 if context.get('uom'):
406 uom_rounding = uom_obj.browse(cr, uid, context.get('uom'), context=context).rounding
408 locations_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
410 # Fetch only the locations in which this product has ever been processed (in or out)
411 cr.execute("""SELECT l.id FROM stock_location l WHERE l.id in %s AND
412 EXISTS (SELECT 1 FROM stock_move m WHERE m.product_id = %s
413 AND ((state = 'done' AND m.location_dest_id = l.id)
414 OR (state in ('done','assigned') AND m.location_id = l.id)))
415 """, (tuple(locations_ids), product_id,))
416 locations_ids = [i for (i,) in cr.fetchall()]
417 for id in locations_ids:
420 # Must lock with a separate select query because FOR UPDATE can't be used with
421 # aggregation/group by's (when individual rows aren't identifiable).
422 # We use a SAVEPOINT to be able to rollback this part of the transaction without
423 # failing the whole transaction in case the LOCK cannot be acquired.
424 cr.execute("SAVEPOINT stock_location_product_reserve")
425 cr.execute("""SELECT id FROM stock_move
426 WHERE product_id=%s AND
428 (location_dest_id=%s AND
433 location_dest_id<>%s AND
434 state in ('done', 'assigned'))
436 FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False)
438 # Here it's likely that the FOR UPDATE NOWAIT failed to get the LOCK,
439 # so we ROLLBACK to the SAVEPOINT to restore the transaction to its earlier
440 # state, we return False as if the products were not available, and log it:
441 cr.execute("ROLLBACK TO stock_location_product_reserve")
442 _logger.warning("Failed attempt to reserve %s x product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_qty, product_id)
443 _logger.debug("Trace of the failed product reservation attempt: ", exc_info=True)
446 # XXX TODO: rewrite this with one single query, possibly even the quantity conversion
447 cr.execute("""SELECT product_uom, sum(product_qty) AS product_qty
449 WHERE location_dest_id=%s AND
455 (id, id, product_id))
456 results = cr.dictfetchall()
457 cr.execute("""SELECT product_uom,-sum(product_qty) AS product_qty
459 WHERE location_id=%s AND
460 location_dest_id<>%s AND
462 state in ('done', 'assigned')
465 (id, id, product_id))
466 results += cr.dictfetchall()
470 amount = uom_obj._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
477 compare_qty = float_compare(amount, 0, precision_rounding=uom_rounding)
479 if amount > min(total, product_qty):
480 amount = min(product_qty, total)
481 result.append((amount, id))
482 product_qty -= amount
484 if product_qty <= 0.0:
493 class stock_tracking(osv.osv):
494 _name = "stock.tracking"
495 _description = "Packs"
498 salt = '31' * 8 + '3'
500 for sscc_part, salt_part in zip(sscc, salt):
501 sum += int(sscc_part) * int(salt_part)
502 return (10 - (sum % 10)) % 10
503 checksum = staticmethod(checksum)
505 def make_sscc(self, cr, uid, context=None):
506 sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
508 return sequence + str(self.checksum(sequence))
513 'name': fields.char('Pack Reference', size=64, required=True, select=True, help="By default, the pack reference is generated following the sscc standard. (Serial number + 1 check digit)"),
514 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a pack without deleting it."),
515 'serial': fields.char('Additional Reference', size=64, select=True, help="Other reference or serial number"),
516 'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves for this pack', readonly=True),
517 'date': fields.datetime('Creation Date', required=True),
522 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
525 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
528 ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
529 ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
530 return self.name_get(cr, user, ids, context)
532 def name_get(self, cr, uid, ids, context=None):
533 """Append the serial to the name"""
536 res = [ (r['id'], r['serial'] and '%s [%s]' % (r['name'], r['serial'])
538 for r in self.read(cr, uid, ids, ['name', 'serial'],
542 def unlink(self, cr, uid, ids, context=None):
543 raise osv.except_osv(_('Error!'), _('You cannot remove a lot line.'))
545 def action_traceability(self, cr, uid, ids, context=None):
546 """ It traces the information of a product
547 @param self: The object pointer.
548 @param cr: A database cursor
549 @param uid: ID of the user currently logged in
550 @param ids: List of IDs selected
551 @param context: A standard dictionary
552 @return: A dictionary of values
554 return self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
558 #----------------------------------------------------------
560 #----------------------------------------------------------
561 class stock_picking(osv.osv):
562 _name = "stock.picking"
563 _inherit = ['mail.thread']
564 _description = "Picking List"
567 def _set_maximum_date(self, cr, uid, ids, name, value, arg, context=None):
568 """ Calculates planned date if it is greater than 'value'.
569 @param name: Name of field
570 @param value: Value of field
571 @param arg: User defined argument
572 @return: True or False
576 if isinstance(ids, (int, long)):
578 for pick in self.browse(cr, uid, ids, context=context):
579 sql_str = """update stock_move set
582 picking_id=%d """ % (value, pick.id)
584 sql_str += " and (date_expected='" + pick.max_date + "')"
588 def _set_minimum_date(self, cr, uid, ids, name, value, arg, context=None):
589 """ Calculates planned date if it is less than 'value'.
590 @param name: Name of field
591 @param value: Value of field
592 @param arg: User defined argument
593 @return: True or False
597 if isinstance(ids, (int, long)):
599 for pick in self.browse(cr, uid, ids, context=context):
600 sql_str = """update stock_move set
603 picking_id=%s """ % (value, pick.id)
605 sql_str += " and (date_expected='" + pick.min_date + "')"
609 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
610 """ Finds minimum and maximum dates for picking.
611 @return: Dictionary of values
615 res[id] = {'min_date': False, 'max_date': False}
627 picking_id""",(tuple(ids),))
628 for pick, dt1, dt2 in cr.fetchall():
629 res[pick]['min_date'] = dt1
630 res[pick]['max_date'] = dt2
633 def _get_stock_move_changes(self, cr, uid, ids, context=None):
634 '''Return the ids of pickings that should change, due to changes
636 move_pool = self.pool['stock.move']
638 for move_obj in move_pool.browse(cr, uid, ids, context=context):
639 if move_obj.picking_id:
640 picking_ids.add(move_obj.picking_id.id)
641 return list(picking_ids)
643 def create(self, cr, user, vals, context=None):
644 if ('name' not in vals) or (vals.get('name')=='/'):
645 seq_obj_name = 'stock.picking.%s' % vals.get('type', 'internal')
646 vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
647 new_id = super(stock_picking, self).create(cr, user, vals, context)
651 'name': fields.char('Reference', size=64, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
652 'origin': fields.char('Source Document', size=64, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Reference of the document", select=True),
653 'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
654 'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."),
655 'note': fields.text('Notes', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
656 'stock_journal_id': fields.many2one('stock.journal','Stock Journal', select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
657 'location_id': fields.many2one('stock.location', 'Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Keep empty if you produce at the location where the finished products are needed." \
658 "Set a location if you produce at a fixed location. This can be a partner location " \
659 "if you subcontract the manufacturing operations.", select=True),
660 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Location where the system will stock the finished products.", select=True),
661 'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="It specifies goods to be deliver partially or all at once"),
662 'state': fields.selection([
664 ('cancel', 'Cancelled'),
665 ('auto', 'Waiting Another Operation'),
666 ('confirmed', 'Waiting Availability'),
667 ('assigned', 'Ready to Transfer'),
668 ('done', 'Transferred'),
669 ], 'Status', readonly=True, select=True, track_visibility='onchange', help="""
670 * Draft: not confirmed yet and will not be scheduled until confirmed\n
671 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
672 * Waiting Availability: still waiting for the availability of products\n
673 * Ready to Transfer: products reserved, simply waiting for confirmation.\n
674 * Transferred: has been processed, can't be modified or cancelled anymore\n
675 * Cancelled: has been cancelled, can't be confirmed anymore"""
677 'min_date': fields.function(
679 fnct_inv=_set_minimum_date, multi='min_max_date',
682 _get_stock_move_changes,
683 ['date_expected'], 10,
686 type='datetime', string='Scheduled Time', select=True,
687 help="Scheduled time for the shipment to be processed"
689 'date': fields.datetime('Creation Date', help="Creation date, usually the time of the order.", select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
690 'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
691 'max_date': fields.function(
693 fnct_inv=_set_maximum_date, multi='min_max_date',
696 _get_stock_move_changes,
697 ['date_expected'], 10,
700 type='datetime', string='Max. Expected Date', select=True
702 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
703 'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
704 'auto_picking': fields.boolean('Auto-Picking', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
705 'partner_id': fields.many2one('res.partner', 'Partner', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
706 'invoice_state': fields.selection([
707 ("invoiced", "Invoiced"),
708 ("2binvoiced", "To Be Invoiced"),
709 ("none", "Not Applicable")], "Invoice Control",
710 select=True, required=True, readonly=True, track_visibility='onchange', states={'draft': [('readonly', False)]}),
711 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
714 'name': lambda self, cr, uid, context: '/',
716 'move_type': 'direct',
718 'invoice_state': 'none',
719 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
720 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
723 ('name_uniq', 'unique(name, company_id)', 'Reference must be unique per Company!'),
726 def action_process(self, cr, uid, ids, context=None):
729 """Open the partial picking wizard"""
731 'active_model': self._name,
733 'active_id': len(ids) and ids[0] or False
738 'res_model': 'stock.partial.picking',
739 'type': 'ir.actions.act_window',
745 def copy(self, cr, uid, id, default=None, context=None):
748 default = default.copy()
749 picking_obj = self.browse(cr, uid, id, context=context)
750 if ('name' not in default) or (picking_obj.name == '/'):
751 seq_obj_name = 'stock.picking.' + picking_obj.type
752 default['name'] = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
753 default['backorder_id'] = False
754 if 'origin' not in default:
755 default['origin'] = ''
756 if 'invoice_state' not in default and picking_obj.invoice_state == 'invoiced':
757 default['invoice_state'] = '2binvoiced'
758 res = super(stock_picking, self).copy(cr, uid, id, default, context)
761 def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
762 if view_type == 'form' and not view_id:
763 mod_obj = self.pool.get('ir.model.data')
764 if self._name == "stock.picking.in":
765 model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_in_form')
766 if self._name == "stock.picking.out":
767 model, view_id = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_out_form')
768 return super(stock_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
770 def onchange_partner_in(self, cr, uid, ids, partner_id=None, context=None):
773 def action_explode(self, cr, uid, moves, context=None):
774 """Hook to allow other modules to split the moves of a picking."""
777 def action_confirm(self, cr, uid, ids, context=None):
778 """ Confirms picking.
781 pickings = self.browse(cr, uid, ids, context=context)
783 for pick in pickings:
784 if pick.state != 'confirmed':
785 to_update.append(pick.id)
787 self.write(cr, uid, to_update, {'state': 'confirmed'})
789 for picking in pickings:
790 for r in picking.move_lines:
791 if r.state == 'draft':
793 todo = self.action_explode(cr, uid, todo, context)
795 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
798 def test_auto_picking(self, cr, uid, ids):
799 # TODO: Check locations to see if in the same location ?
802 def action_assign(self, cr, uid, ids, *args):
803 """ Changes state of picking to available if all moves are confirmed.
806 wf_service = netsvc.LocalService("workflow")
807 for pick in self.browse(cr, uid, ids):
808 if pick.state == 'draft':
809 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_confirm', cr)
810 move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
812 raise osv.except_osv(_('Warning!'),_('Not enough stock, unable to reserve the products.'))
813 self.pool.get('stock.move').action_assign(cr, uid, move_ids)
816 def force_assign(self, cr, uid, ids, *args):
817 """ Changes state of picking to available if moves are confirmed or waiting.
820 wf_service = netsvc.LocalService("workflow")
821 for pick in self.browse(cr, uid, ids):
822 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
823 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
824 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
827 def draft_force_assign(self, cr, uid, ids, *args):
828 """ Confirms picking directly from draft state.
831 wf_service = netsvc.LocalService("workflow")
832 for pick in self.browse(cr, uid, ids):
833 if not pick.move_lines:
834 raise osv.except_osv(_('Error!'),_('You cannot process picking without stock moves.'))
835 wf_service.trg_validate(uid, 'stock.picking', pick.id,
836 'button_confirm', cr)
839 def draft_validate(self, cr, uid, ids, context=None):
840 """ Validates picking directly from draft state.
843 wf_service = netsvc.LocalService("workflow")
844 self.draft_force_assign(cr, uid, ids)
845 for pick in self.browse(cr, uid, ids, context=context):
846 move_ids = [x.id for x in pick.move_lines]
847 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
848 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
849 return self.action_process(
850 cr, uid, ids, context=context)
851 def cancel_assign(self, cr, uid, ids, *args):
852 """ Cancels picking and moves.
855 for pick in self.browse(cr, uid, ids):
856 move_ids = [x.id for x in pick.move_lines]
857 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
860 def action_assign_wkf(self, cr, uid, ids, context=None):
861 """ Changes picking state to assigned.
865 for pick in self.browse(cr, uid, ids, context=context):
866 if pick.state != 'assigned':
867 to_update.append(pick.id)
869 self.write(cr, uid, to_update, {'state': 'assigned'})
872 def test_finished(self, cr, uid, ids):
873 """ Tests whether the move is in done or cancel state or not.
874 @return: True or False
876 move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
877 for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
878 if move.state not in ('done', 'cancel'):
880 if move.product_qty != 0.0:
883 move.write({'state': 'done'})
886 def test_assigned(self, cr, uid, ids):
887 """ Tests whether the move is in assigned state or not.
888 @return: True or False
890 #TOFIX: assignment of move lines should be call before testing assigment otherwise picking never gone in assign state
892 for pick in self.browse(cr, uid, ids):
894 # incomming shipments are always set as available if they aren't chained
895 if pick.type == 'in':
896 if all([x.state != 'waiting' for x in pick.move_lines]):
898 for move in pick.move_lines:
899 if (move.state) == 'waiting':
901 if (move.state in ('confirmed', 'draft')) and (mt == 'one'):
903 if (mt == 'direct') and (move.state == 'assigned') and (move.product_qty):
905 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
908 def action_cancel(self, cr, uid, ids, context=None):
909 """ Changes picking state to cancel.
912 for pick in self.browse(cr, uid, ids, context=context):
913 ids2 = [move.id for move in pick.move_lines]
914 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
915 self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
919 # TODO: change and create a move if not parents
921 def action_done(self, cr, uid, ids, context=None):
922 """Changes picking state to done.
924 This method is called at the end of the workflow by the activity "done".
927 self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
930 def action_move(self, cr, uid, ids, context=None):
931 """Process the Stock Moves of the Picking
933 This method is called by the workflow by the activity "move".
934 Normally that happens when the signal button_done is received (button
935 "Done" pressed on a Picking view).
938 for pick in self.browse(cr, uid, ids, context=context):
940 for move in pick.move_lines:
941 if move.state == 'draft':
942 self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
945 elif move.state in ('assigned','confirmed'):
948 self.pool.get('stock.move').action_done(cr, uid, todo,
952 def get_currency_id(self, cr, uid, picking):
955 def _get_partner_to_invoice(self, cr, uid, picking, context=None):
956 """ Gets the partner that will be invoiced
957 Note that this function is inherited in the sale and purchase modules
958 @param picking: object of the picking for which we are selecting the partner to invoice
959 @return: object of the partner to invoice
961 return picking.partner_id and picking.partner_id.id
963 def _get_comment_invoice(self, cr, uid, picking):
965 @return: comment string for invoice
967 return picking.note or ''
969 def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None):
970 """ Gets price unit for invoice
971 @param move_line: Stock move lines
972 @param type: Type of invoice
973 @return: The price unit for the move line
978 if type in ('in_invoice', 'in_refund'):
979 # Take the user company and pricetype
980 context['currency_id'] = move_line.company_id.currency_id.id
981 amount_unit = move_line.product_id.price_get('standard_price', context=context)[move_line.product_id.id]
984 return move_line.product_id.list_price
986 def _get_discount_invoice(self, cr, uid, move_line):
987 '''Return the discount for the move line'''
990 def _get_taxes_invoice(self, cr, uid, move_line, type):
991 """ Gets taxes on invoice
992 @param move_line: Stock move lines
993 @param type: Type of invoice
994 @return: Taxes Ids for the move line
996 if type in ('in_invoice', 'in_refund'):
997 taxes = move_line.product_id.supplier_taxes_id
999 taxes = move_line.product_id.taxes_id
1001 if move_line.picking_id and move_line.picking_id.partner_id and move_line.picking_id.partner_id.id:
1002 return self.pool.get('account.fiscal.position').map_tax(
1005 move_line.picking_id.partner_id.property_account_position,
1009 return map(lambda x: x.id, taxes)
1011 def _get_account_analytic_invoice(self, cr, uid, picking, move_line):
1014 def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
1015 '''Call after the creation of the invoice line'''
1018 def _invoice_hook(self, cr, uid, picking, invoice_id):
1019 '''Call after the creation of the invoice'''
1022 def _get_invoice_type(self, pick):
1023 src_usage = dest_usage = None
1025 if pick.invoice_state == '2binvoiced':
1027 src_usage = pick.move_lines[0].location_id.usage
1028 dest_usage = pick.move_lines[0].location_dest_id.usage
1029 if pick.type == 'out' and dest_usage == 'supplier':
1030 inv_type = 'in_refund'
1031 elif pick.type == 'out' and dest_usage == 'customer':
1032 inv_type = 'out_invoice'
1033 elif pick.type == 'in' and src_usage == 'supplier':
1034 inv_type = 'in_invoice'
1035 elif pick.type == 'in' and src_usage == 'customer':
1036 inv_type = 'out_refund'
1038 inv_type = 'out_invoice'
1041 def _prepare_invoice_group(self, cr, uid, picking, partner, invoice, context=None):
1042 """ Builds the dict for grouped invoices
1043 @param picking: picking object
1044 @param partner: object of the partner to invoice (not used here, but may be usefull if this function is inherited)
1045 @param invoice: object of the invoice that we are updating
1046 @return: dict that will be used to update the invoice
1048 comment = self._get_comment_invoice(cr, uid, picking)
1050 'name': (invoice.name or '') + ', ' + (picking.name or ''),
1051 'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
1052 'comment': (comment and (invoice.comment and invoice.comment + "\n" + comment or comment)) or (invoice.comment and invoice.comment or ''),
1053 'date_invoice': context.get('date_inv', False),
1056 def _prepare_invoice(self, cr, uid, picking, partner, inv_type, journal_id, context=None):
1057 """ Builds the dict containing the values for the invoice
1058 @param picking: picking object
1059 @param partner: object of the partner to invoice
1060 @param inv_type: type of the invoice ('out_invoice', 'in_invoice', ...)
1061 @param journal_id: ID of the accounting journal
1062 @return: dict that will be used to create the invoice object
1064 if isinstance(partner, int):
1065 partner = self.pool.get('res.partner').browse(cr, uid, partner, context=context)
1066 if inv_type in ('out_invoice', 'out_refund'):
1067 account_id = partner.property_account_receivable.id
1068 payment_term = partner.property_payment_term.id or False
1070 account_id = partner.property_account_payable.id
1071 payment_term = partner.property_supplier_payment_term.id or False
1072 comment = self._get_comment_invoice(cr, uid, picking)
1074 'name': picking.name,
1075 'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
1077 'account_id': account_id,
1078 'partner_id': partner.id,
1080 'payment_term': payment_term,
1081 'fiscal_position': partner.property_account_position.id,
1082 'date_invoice': context.get('date_inv', False),
1083 'company_id': picking.company_id.id,
1086 cur_id = self.get_currency_id(cr, uid, picking)
1088 invoice_vals['currency_id'] = cur_id
1090 invoice_vals['journal_id'] = journal_id
1093 def _prepare_invoice_line(self, cr, uid, group, picking, move_line, invoice_id,
1094 invoice_vals, context=None):
1095 """ Builds the dict containing the values for the invoice line
1096 @param group: True or False
1097 @param picking: picking object
1098 @param: move_line: move_line object
1099 @param: invoice_id: ID of the related invoice
1100 @param: invoice_vals: dict used to created the invoice
1101 @return: dict that will be used to create the invoice line
1104 name = (picking.name or '') + '-' + move_line.name
1106 name = move_line.name
1107 origin = move_line.picking_id.name or ''
1108 if move_line.picking_id.origin:
1109 origin += ':' + move_line.picking_id.origin
1111 if invoice_vals['type'] in ('out_invoice', 'out_refund'):
1112 account_id = move_line.product_id.property_account_income.id
1114 account_id = move_line.product_id.categ_id.\
1115 property_account_income_categ.id
1117 account_id = move_line.product_id.property_account_expense.id
1119 account_id = move_line.product_id.categ_id.\
1120 property_account_expense_categ.id
1121 if invoice_vals['fiscal_position']:
1122 fp_obj = self.pool.get('account.fiscal.position')
1123 fiscal_position = fp_obj.browse(cr, uid, invoice_vals['fiscal_position'], context=context)
1124 account_id = fp_obj.map_account(cr, uid, fiscal_position, account_id)
1125 # set UoS if it's a sale and the picking doesn't have one
1126 uos_id = move_line.product_uos and move_line.product_uos.id or False
1127 if not uos_id and invoice_vals['type'] in ('out_invoice', 'out_refund'):
1128 uos_id = move_line.product_uom.id
1133 'invoice_id': invoice_id,
1135 'product_id': move_line.product_id.id,
1136 'account_id': account_id,
1137 'price_unit': self._get_price_unit_invoice(cr, uid, move_line, invoice_vals['type']),
1138 'discount': self._get_discount_invoice(cr, uid, move_line),
1139 'quantity': move_line.product_uos_qty or move_line.product_qty,
1140 'invoice_line_tax_id': [(6, 0, self._get_taxes_invoice(cr, uid, move_line, invoice_vals['type']))],
1141 'account_analytic_id': self._get_account_analytic_invoice(cr, uid, picking, move_line),
1144 def action_invoice_create(self, cr, uid, ids, journal_id=False,
1145 group=False, type='out_invoice', context=None):
1146 """ Creates invoice based on the invoice state selected for picking.
1147 @param journal_id: Id of journal
1148 @param group: Whether to create a group invoice or not
1149 @param type: Type invoice to be created
1150 @return: Ids of created invoices for the pickings
1155 invoice_obj = self.pool.get('account.invoice')
1156 invoice_line_obj = self.pool.get('account.invoice.line')
1157 partner_obj = self.pool.get('res.partner')
1161 for picking in self.browse(cr, uid, ids, context=context):
1162 if picking.invoice_state != '2binvoiced':
1164 partner = self._get_partner_to_invoice(cr, uid, picking, context=context)
1165 if isinstance(partner, int):
1166 partner = partner_obj.browse(cr, uid, [partner], context=context)[0]
1168 raise osv.except_osv(_('Error, no partner!'),
1169 _('Please put a partner on the picking list if you want to generate invoice.'))
1172 inv_type = self._get_invoice_type(picking)
1174 invoice_vals = self._prepare_invoice(cr, uid, picking, partner, inv_type, journal_id, context=context)
1175 if group and partner.id in invoices_group:
1176 invoice_id = invoices_group[partner.id]
1177 invoice = invoice_obj.browse(cr, uid, invoice_id)
1178 invoice_vals_group = self._prepare_invoice_group(cr, uid, picking, partner, invoice, context=context)
1179 invoice_obj.write(cr, uid, [invoice_id], invoice_vals_group, context=context)
1181 invoice_id = invoice_obj.create(cr, uid, invoice_vals, context=context)
1182 invoices_group[partner.id] = invoice_id
1183 res[picking.id] = invoice_id
1184 for move_line in picking.move_lines:
1185 if move_line.state == 'cancel':
1187 if move_line.scrapped:
1188 # do no invoice scrapped products
1190 vals = self._prepare_invoice_line(cr, uid, group, picking, move_line,
1191 invoice_id, invoice_vals, context=context)
1193 invoice_line_id = invoice_line_obj.create(cr, uid, vals, context=context)
1194 self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
1196 invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
1197 set_total=(inv_type in ('in_invoice', 'in_refund')))
1198 self.write(cr, uid, [picking.id], {
1199 'invoice_state': 'invoiced',
1201 self._invoice_hook(cr, uid, picking, invoice_id)
1202 self.write(cr, uid, res.keys(), {
1203 'invoice_state': 'invoiced',
1207 def test_done(self, cr, uid, ids, context=None):
1208 """ Test whether the move lines are done or not.
1209 @return: True or False
1212 for pick in self.browse(cr, uid, ids, context=context):
1213 if not pick.move_lines:
1215 for move in pick.move_lines:
1216 if move.state not in ('cancel','done'):
1218 if move.state=='done':
1222 def test_cancel(self, cr, uid, ids, context=None):
1223 """ Test whether the move lines are canceled or not.
1224 @return: True or False
1226 for pick in self.browse(cr, uid, ids, context=context):
1227 for move in pick.move_lines:
1228 if move.state not in ('cancel',):
1232 def allow_cancel(self, cr, uid, ids, context=None):
1233 for pick in self.browse(cr, uid, ids, context=context):
1234 if not pick.move_lines:
1236 for move in pick.move_lines:
1237 if move.state == 'done':
1238 raise osv.except_osv(_('Error!'), _('You cannot cancel the picking as some moves have been done. You should cancel the picking lines.'))
1241 def unlink(self, cr, uid, ids, context=None):
1242 move_obj = self.pool.get('stock.move')
1245 for pick in self.browse(cr, uid, ids, context=context):
1246 if pick.state in ['done','cancel']:
1247 # retrieve the string value of field in user's language
1248 state = dict(self.fields_get(cr, uid, context=context)['state']['selection']).get(pick.state, pick.state)
1249 raise osv.except_osv(_('Error!'), _('You cannot remove the picking which is in %s state!')%(state,))
1251 ids2 = [move.id for move in pick.move_lines]
1252 ctx = context.copy()
1253 ctx.update({'call_unlink':True})
1254 if pick.state != 'draft':
1255 #Cancelling the move in order to affect Virtual stock of product
1256 move_obj.action_cancel(cr, uid, ids2, ctx)
1258 move_obj.unlink(cr, uid, ids2, ctx)
1260 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
1262 # FIXME: needs refactoring, this code is partially duplicated in stock_move.do_partial()!
1263 def do_partial(self, cr, uid, ids, partial_datas, context=None):
1264 """ Makes partial picking and moves done.
1265 @param partial_datas : Dictionary containing details of partial picking
1266 like partner_id, partner_id, delivery_date,
1267 delivery moves with product_id, product_qty, uom
1268 @return: Dictionary of values
1273 context = dict(context)
1275 move_obj = self.pool.get('stock.move')
1276 product_obj = self.pool.get('product.product')
1277 currency_obj = self.pool.get('res.currency')
1278 uom_obj = self.pool.get('product.uom')
1279 sequence_obj = self.pool.get('ir.sequence')
1280 wf_service = netsvc.LocalService("workflow")
1281 for pick in self.browse(cr, uid, ids, context=context):
1283 complete, too_many, too_few = [], [], []
1284 move_product_qty, prodlot_ids, product_avail, partial_qty, uos_qty, product_uoms = {}, {}, {}, {}, {}, {}
1285 for move in pick.move_lines:
1286 if move.state in ('done', 'cancel'):
1288 partial_data = partial_datas.get('move%s'%(move.id), {})
1289 product_qty = partial_data.get('product_qty',0.0)
1290 move_product_qty[move.id] = product_qty
1291 product_uom = partial_data.get('product_uom',False)
1292 product_price = partial_data.get('product_price',0.0)
1293 product_currency = partial_data.get('product_currency',False)
1294 prodlot_id = partial_data.get('prodlot_id')
1295 prodlot_ids[move.id] = prodlot_id
1296 product_uoms[move.id] = product_uom
1297 partial_qty[move.id] = uom_obj._compute_qty(cr, uid, product_uoms[move.id], product_qty, move.product_uom.id)
1298 uos_qty[move.id] = move.product_id._compute_uos_qty(product_uom, product_qty, move.product_uos) if product_qty else 0.0
1299 if move.product_qty == partial_qty[move.id]:
1300 complete.append(move)
1301 elif move.product_qty > partial_qty[move.id]:
1302 too_few.append(move)
1304 too_many.append(move)
1306 # Average price computation
1307 if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
1308 product = product_obj.browse(cr, uid, move.product_id.id)
1309 move_currency_id = move.company_id.currency_id.id
1310 context['currency_id'] = move_currency_id
1311 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
1313 if product.id not in product_avail:
1314 # keep track of stock on hand including processed lines not yet marked as done
1315 product_avail[product.id] = product.qty_available
1318 new_price = currency_obj.compute(cr, uid, product_currency,
1319 move_currency_id, product_price, round=False)
1320 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
1322 if product_avail[product.id] <= 0:
1323 product_avail[product.id] = 0
1324 new_std_price = new_price
1326 # Get the standard price
1327 amount_unit = product.price_get('standard_price', context=context)[product.id]
1328 new_std_price = ((amount_unit * product_avail[product.id])\
1329 + (new_price * qty))/(product_avail[product.id] + qty)
1330 # Write the field according to price type field
1331 product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price})
1333 # Record the values that were chosen in the wizard, so they can be
1334 # used for inventory valuation if real-time valuation is enabled.
1335 move_obj.write(cr, uid, [move.id],
1336 {'price_unit': product_price,
1337 'price_currency_id': product_currency})
1339 product_avail[product.id] += qty
1341 # every line of the picking is empty, do not generate anything
1342 empty_picking = not any(q for q in move_product_qty.values() if q > 0)
1344 for move in too_few:
1345 product_qty = move_product_qty[move.id]
1346 if not new_picking and not empty_picking:
1347 new_picking_name = pick.name
1348 self.write(cr, uid, [pick.id],
1349 {'name': sequence_obj.get(cr, uid,
1350 'stock.picking.%s'%(pick.type)),
1353 new_picking = self.copy(cr, uid, pick.id,
1355 'name': new_picking_name,
1359 if product_qty != 0:
1361 'product_qty' : product_qty,
1362 'product_uos_qty': uos_qty[move.id],
1363 'picking_id' : new_picking,
1364 'state': 'assigned',
1365 'move_dest_id': move.move_dest_id.id,
1366 'price_unit': move.price_unit,
1367 'product_uom': product_uoms[move.id]
1369 prodlot_id = prodlot_ids[move.id]
1371 defaults.update(prodlot_id=prodlot_id)
1372 move_obj.copy(cr, uid, move.id, defaults)
1373 move_obj.write(cr, uid, [move.id],
1375 'product_qty': move.product_qty - partial_qty[move.id],
1376 'product_uos_qty': move.product_uos_qty - uos_qty[move.id],
1377 'prodlot_id': False,
1378 'tracking_id': False,
1382 move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
1383 for move in complete:
1384 defaults = {'product_uom': product_uoms[move.id], 'product_qty': move_product_qty[move.id]}
1385 if prodlot_ids.get(move.id):
1386 defaults.update({'prodlot_id': prodlot_ids[move.id]})
1387 move_obj.write(cr, uid, [move.id], defaults)
1388 for move in too_many:
1389 product_qty = move_product_qty[move.id]
1391 'product_qty' : product_qty,
1392 'product_uos_qty': uos_qty[move.id],
1393 'product_uom': product_uoms[move.id]
1395 prodlot_id = prodlot_ids.get(move.id)
1396 if prodlot_ids.get(move.id):
1397 defaults.update(prodlot_id=prodlot_id)
1399 defaults.update(picking_id=new_picking)
1400 move_obj.write(cr, uid, [move.id], defaults)
1402 # At first we confirm the new picking (if necessary)
1404 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
1405 # Then we finish the good picking
1406 self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
1407 self.action_move(cr, uid, [new_picking], context=context)
1408 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr)
1409 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
1410 delivered_pack_id = new_picking
1411 self.message_post(cr, uid, new_picking, body=_("Back order <em>%s</em> has been <b>created</b>.") % (pick.name), context=context)
1413 delivered_pack_id = pick.id
1415 self.action_move(cr, uid, [pick.id], context=context)
1416 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
1417 delivered_pack_id = pick.id
1419 delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
1420 res[pick.id] = {'delivered_picking': delivered_pack.id or False}
1424 # views associated to each picking type
1426 'out': 'view_picking_out_form',
1427 'in': 'view_picking_in_form',
1428 'internal': 'view_picking_form',
1430 def _get_view_id(self, cr, uid, type):
1431 """Get the view id suiting the given type
1433 @param type: the picking type as a string
1434 @return: view i, or False if no view found
1436 res = self.pool.get('ir.model.data').get_object_reference(cr, uid,
1437 'stock', self._VIEW_LIST.get(type, 'view_picking_form'))
1438 return res and res[1] or False
1441 class stock_production_lot(osv.osv):
1443 def name_get(self, cr, uid, ids, context=None):
1446 reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
1448 for record in reads:
1449 name = record['name']
1450 prefix = record['prefix']
1452 name = prefix + '/' + name
1454 name = '%s [%s]' % (name, record['ref'])
1455 res.append((record['id'], name))
1458 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
1462 ids = self.search(cr, uid, [('prefix', '=', name)] + args, limit=limit, context=context)
1464 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
1466 ids = self.search(cr, uid, args, limit=limit, context=context)
1467 return self.name_get(cr, uid, ids, context)
1469 _name = 'stock.production.lot'
1470 _description = 'Serial Number'
1472 def _get_stock(self, cr, uid, ids, field_name, arg, context=None):
1473 """ Gets stock of products for locations
1474 @return: Dictionary of values
1478 if 'location_id' not in context:
1479 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
1481 locations = context['location_id'] and [context['location_id']] or []
1483 if isinstance(ids, (int, long)):
1486 res = {}.fromkeys(ids, 0.0)
1488 cr.execute('''select
1492 stock_report_prodlots
1494 location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),))
1495 res.update(dict(cr.fetchall()))
1499 def _stock_search(self, cr, uid, obj, name, args, context=None):
1500 """ Searches Ids of products
1501 @return: Ids of locations
1503 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
1504 cr.execute('''select
1508 stock_report_prodlots
1510 location_id IN %s group by prodlot_id
1511 having sum(qty) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),))
1513 ids = [('id', 'in', map(lambda x: x[0], res))]
1517 'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number, will be displayed as: PREFIX/SERIAL [INT_REF]"),
1518 'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
1519 'prefix': fields.char('Prefix', size=64, help="Optional prefix to prepend when displaying this serial number: PREFIX/SERIAL [INT_REF]"),
1520 'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
1521 'date': fields.datetime('Creation Date', required=True),
1522 'stock_available': fields.function(_get_stock, fnct_search=_stock_search, type="float", string="Available", select=True,
1523 help="Current quantity of products with this Serial Number available in company warehouses",
1524 digits_compute=dp.get_precision('Product Unit of Measure')),
1525 'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
1526 'company_id': fields.many2one('res.company', 'Company', select=True),
1527 'move_ids': fields.one2many('stock.move', 'prodlot_id', 'Moves for this serial number', readonly=True),
1530 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1531 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1532 'product_id': lambda x, y, z, c: c.get('product_id', False),
1534 _sql_constraints = [
1535 ('name_ref_uniq', 'unique (name, ref, product_id, company_id)', 'The combination of Serial Number, internal reference, Product and Company must be unique !'),
1537 def action_traceability(self, cr, uid, ids, context=None):
1538 """ It traces the information of a product
1539 @param self: The object pointer.
1540 @param cr: A database cursor
1541 @param uid: ID of the user currently logged in
1542 @param ids: List of IDs selected
1543 @param context: A standard dictionary
1544 @return: A dictionary of values
1546 value=self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
1549 def copy(self, cr, uid, id, default=None, context=None):
1550 context = context or {}
1551 default = default and default.copy() or {}
1552 default.update(date=time.strftime('%Y-%m-%d %H:%M:%S'), move_ids=[])
1553 return super(stock_production_lot, self).copy(cr, uid, id, default=default, context=context)
1555 stock_production_lot()
1557 class stock_production_lot_revision(osv.osv):
1558 _name = 'stock.production.lot.revision'
1559 _description = 'Serial Number Revision'
1562 'name': fields.char('Revision Name', size=64, required=True),
1563 'description': fields.text('Description'),
1564 'date': fields.date('Revision Date'),
1565 'indice': fields.char('Revision Number', size=16),
1566 'author_id': fields.many2one('res.users', 'Author'),
1567 'lot_id': fields.many2one('stock.production.lot', 'Serial Number', select=True, ondelete='cascade'),
1568 'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True),
1572 'author_id': lambda x, y, z, c: z,
1573 'date': fields.date.context_today,
1576 stock_production_lot_revision()
1578 # ----------------------------------------------------
1580 # ----------------------------------------------------
1584 # location_dest_id is only used for predicting futur stocks
1586 class stock_move(osv.osv):
1588 def _getSSCC(self, cr, uid, context=None):
1589 cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
1591 return (res and res[0]) or False
1593 _name = "stock.move"
1594 _description = "Stock Move"
1595 _order = 'date_expected desc, id'
1598 def action_partial_move(self, cr, uid, ids, context=None):
1599 if context is None: context = {}
1600 if context.get('active_model') != self._name:
1601 context.update(active_ids=ids, active_model=self._name)
1602 partial_id = self.pool.get("stock.partial.move").create(
1603 cr, uid, {}, context=context)
1605 'name':_("Products to Process"),
1606 'view_mode': 'form',
1608 'view_type': 'form',
1609 'res_model': 'stock.partial.move',
1610 'res_id': partial_id,
1611 'type': 'ir.actions.act_window',
1619 def name_get(self, cr, uid, ids, context=None):
1621 for line in self.browse(cr, uid, ids, context=context):
1622 name = line.location_id.name+' > '+line.location_dest_id.name
1624 if line.product_id.code:
1625 name = line.product_id.code + ': ' + name
1626 if line.picking_id.origin:
1627 name = line.picking_id.origin + '/ ' + name
1628 res.append((line.id, name))
1631 def _check_tracking(self, cr, uid, ids, context=None):
1632 """ Checks if serial number is assigned to stock move or not.
1633 @return: True or False
1635 for move in self.browse(cr, uid, ids, context=context):
1636 if not move.prodlot_id and \
1637 (move.state == 'done' and \
1639 (move.product_id.track_production and move.location_id.usage == 'production') or \
1640 (move.product_id.track_production and move.location_dest_id.usage == 'production') or \
1641 (move.product_id.track_incoming and move.location_id.usage == 'supplier') or \
1642 (move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \
1643 (move.product_id.track_incoming and move.location_id.usage == 'inventory') \
1648 def _check_product_lot(self, cr, uid, ids, context=None):
1649 """ Checks whether move is done or not and production lot is assigned to that move.
1650 @return: True or False
1652 for move in self.browse(cr, uid, ids, context=context):
1653 if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id):
1658 'name': fields.char('Description', required=True, select=True),
1659 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1660 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
1661 '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)]}),
1662 'date_expected': fields.datetime('Scheduled Date', states={'done': [('readonly', True)]},required=True, select=True, help="Scheduled date for the processing of this move"),
1663 'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type','<>','service')],states={'done': [('readonly', True)]}),
1665 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
1666 required=True,states={'done': [('readonly', True)]},
1667 help="This is the quantity of products from an inventory "
1668 "point of view. For moves in the state 'done', this is the "
1669 "quantity of products that were actually moved. For other "
1670 "moves, this is the quantity of product that is planned to "
1671 "be moved. Lowering this quantity does not generate a "
1672 "backorder. Changing this quantity on assigned moves affects "
1673 "the product reservation, and should be done with care."
1675 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True,states={'done': [('readonly', True)]}),
1676 'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
1677 'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
1678 'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1680 '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."),
1681 '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."),
1682 'partner_id': fields.many2one('res.partner', 'Destination Address ', states={'done': [('readonly', True)]}, help="Optional address where goods are to be delivered, specifically used for allotment"),
1684 'prodlot_id': fields.many2one('stock.production.lot', 'Serial Number', states={'done': [('readonly', True)]}, help="Serial number is used to put a serial number on the production", select=True),
1685 'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, states={'done': [('readonly', True)]}, help="Logistical shipping unit: pallet, box, pack ..."),
1687 'auto_validate': fields.boolean('Auto Validate'),
1689 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
1690 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History (child moves)'),
1691 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History (parent moves)'),
1692 'picking_id': fields.many2one('stock.picking', 'Reference', select=True,states={'done': [('readonly', True)]}),
1693 'note': fields.text('Notes'),
1694 'state': fields.selection([('draft', 'New'),
1695 ('cancel', 'Cancelled'),
1696 ('waiting', 'Waiting Another Move'),
1697 ('confirmed', 'Waiting Availability'),
1698 ('assigned', 'Available'),
1700 ], 'Status', readonly=True, select=True,
1701 help= "* New: When the stock move is created and not yet confirmed.\n"\
1702 "* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
1703 "* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to me manufactured...\n"\
1704 "* Available: When products are reserved, it is set to \'Available\'.\n"\
1705 "* Done: When the shipment is processed, the state is \'Done\'."),
1706 'price_unit': fields.float('Unit Price', digits_compute= dp.get_precision('Product Price'), help="Technical field used to record the product cost set by the user during a picking confirmation (when average price costing method is used)"),
1707 '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)"),
1708 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
1709 'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Order of", select=True),
1710 'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Source", store=True),
1712 # used for colors in tree views:
1713 'scrapped': fields.related('location_dest_id','scrap_location',type='boolean',relation='stock.location',string='Scrapped', readonly=True),
1714 'type': fields.related('picking_id', 'type', type='selection', selection=[('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], string='Shipping Type'),
1717 def _check_location(self, cr, uid, ids, context=None):
1718 for record in self.browse(cr, uid, ids, context=context):
1719 if (record.state=='done') and (record.location_id.usage == 'view'):
1720 raise osv.except_osv(_('Error'), _('You cannot move product %s from a location of type view %s.')% (record.product_id.name, record.location_id.name))
1721 if (record.state=='done') and (record.location_dest_id.usage == 'view' ):
1722 raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.')% (record.product_id.name, record.location_dest_id.name))
1727 'You must assign a serial number for this product.',
1729 (_check_location, 'You cannot move products from or to a location of the type view.',
1730 ['location_id','location_dest_id']),
1731 (_check_product_lot,
1732 'You try to assign a lot which is not from the same product.',
1735 def _default_location_destination(self, cr, uid, context=None):
1736 """ Gets default address of partner for destination location
1737 @return: Address id or False
1739 mod_obj = self.pool.get('ir.model.data')
1740 picking_type = context.get('picking_type')
1744 if context.get('move_line', []):
1745 if context['move_line'][0]:
1746 if isinstance(context['move_line'][0], (tuple, list)):
1747 location_id = context['move_line'][0][2] and context['move_line'][0][2].get('location_dest_id',False)
1749 move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1750 location_id = move_list and move_list['location_dest_id'][0] or False
1751 elif context.get('address_out_id', False):
1752 property_out = self.pool.get('res.partner').browse(cr, uid, context['address_out_id'], context).property_stock_customer
1753 location_id = property_out and property_out.id or False
1755 location_xml_id = False
1756 if picking_type in ('in', 'internal'):
1757 location_xml_id = 'stock_location_stock'
1758 elif picking_type == 'out':
1759 location_xml_id = 'stock_location_customers'
1762 location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id)
1763 with tools.mute_logger('openerp.osv.orm'):
1764 self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
1765 except (orm.except_orm, ValueError):
1770 def _default_location_source(self, cr, uid, context=None):
1771 """ Gets default address of partner for source location
1772 @return: Address id or False
1774 mod_obj = self.pool.get('ir.model.data')
1775 picking_type = context.get('picking_type')
1780 if context.get('move_line', []):
1782 location_id = context['move_line'][0][2]['location_id']
1785 elif context.get('address_in_id', False):
1786 part_obj_add = self.pool.get('res.partner').browse(cr, uid, context['address_in_id'], context=context)
1788 location_id = part_obj_add.property_stock_supplier.id
1790 location_xml_id = False
1791 if picking_type == 'in':
1792 location_xml_id = 'stock_location_suppliers'
1793 elif picking_type in ('out', 'internal'):
1794 location_xml_id = 'stock_location_stock'
1797 location_model, location_id = mod_obj.get_object_reference(cr, uid, 'stock', location_xml_id)
1798 with tools.mute_logger('openerp.osv.orm'):
1799 self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
1800 except (orm.except_orm, ValueError):
1805 def _default_destination_address(self, cr, uid, context=None):
1806 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
1807 return user.company_id.partner_id.id
1809 def _default_move_type(self, cr, uid, context=None):
1810 """ Gets default type of move
1815 picking_type = context.get('picking_type')
1817 if picking_type == 'in':
1819 elif picking_type == 'out':
1824 'location_id': _default_location_source,
1825 'location_dest_id': _default_location_destination,
1826 'partner_id': _default_destination_address,
1827 'type': _default_move_type,
1832 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1833 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1834 'date_expected': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1837 def write(self, cr, uid, ids, vals, context=None):
1838 if isinstance(ids, (int, long)):
1841 frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
1842 for move in self.browse(cr, uid, ids, context=context):
1843 if move.state == 'done':
1844 if frozen_fields.intersection(vals):
1845 raise osv.except_osv(_('Operation Forbidden!'),
1846 _('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
1847 return super(stock_move, self).write(cr, uid, ids, vals, context=context)
1849 def copy_data(self, cr, uid, id, default=None, context=None):
1852 default = default.copy()
1853 default.setdefault('tracking_id', False)
1854 default.setdefault('prodlot_id', False)
1855 default.setdefault('move_history_ids', [])
1856 default.setdefault('move_history_ids2', [])
1857 return super(stock_move, self).copy_data(cr, uid, id, default, context=context)
1859 def _auto_init(self, cursor, context=None):
1860 res = super(stock_move, self)._auto_init(cursor, context=context)
1861 cursor.execute('SELECT indexname \
1863 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1864 if not cursor.fetchone():
1865 cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1866 ON stock_move (product_id, state, location_id, location_dest_id)')
1869 def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
1870 loc_id=False, product_id=False, uom_id=False, context=None):
1871 """ On change of production lot gives a warning message.
1872 @param prodlot_id: Changed production lot id
1873 @param product_qty: Quantity of product
1874 @param loc_id: Location id
1875 @param product_id: Product id
1876 @return: Warning message
1878 if not prodlot_id or not loc_id:
1880 ctx = context and context.copy() or {}
1881 ctx['location_id'] = loc_id
1882 ctx.update({'raise-exception': True})
1883 uom_obj = self.pool.get('product.uom')
1884 product_obj = self.pool.get('product.product')
1885 product_uom = product_obj.browse(cr, uid, product_id, context=ctx).uom_id
1886 prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, context=ctx)
1887 location = self.pool.get('stock.location').browse(cr, uid, loc_id, context=ctx)
1888 uom = uom_obj.browse(cr, uid, uom_id, context=ctx)
1889 amount_actual = uom_obj._compute_qty_obj(cr, uid, product_uom, prodlot.stock_available, uom, context=ctx)
1891 if (location.usage == 'internal') and (product_qty > (amount_actual or 0.0)):
1893 'title': _('Insufficient Stock for Serial Number !'),
1894 'message': _('You are moving %.2f %s but only %.2f %s available for this serial number.') % (product_qty, uom.name, amount_actual, uom.name)
1896 return {'warning': warning}
1898 def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
1899 product_uom, product_uos):
1900 """ On change of product quantity finds UoM and UoS quantities
1901 @param product_id: Product id
1902 @param product_qty: Changed Quantity of product
1903 @param product_uom: Unit of measure of product
1904 @param product_uos: Unit of sale of product
1905 @return: Dictionary of values
1908 'product_uos_qty': 0.00
1912 if (not product_id) or (product_qty <=0.0):
1913 result['product_qty'] = 0.0
1914 return {'value': result}
1916 product_obj = self.pool.get('product.product')
1917 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1919 # Warn if the quantity was decreased
1921 for move in self.read(cr, uid, ids, ['product_qty']):
1922 if product_qty < move['product_qty']:
1924 'title': _('Information'),
1925 'message': _("By changing this quantity here, you accept the "
1926 "new quantity as complete: OpenERP will not "
1927 "automatically generate a back order.") })
1930 if product_uos and product_uom and (product_uom != product_uos):
1931 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1933 result['product_uos_qty'] = product_qty
1935 return {'value': result, 'warning': warning}
1937 def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty,
1938 product_uos, product_uom):
1939 """ On change of product quantity finds UoM and UoS quantities
1940 @param product_id: Product id
1941 @param product_uos_qty: Changed UoS Quantity of product
1942 @param product_uom: Unit of measure of product
1943 @param product_uos: Unit of sale of product
1944 @return: Dictionary of values
1950 if (not product_id) or (product_uos_qty <=0.0):
1951 result['product_uos_qty'] = 0.0
1952 return {'value': result}
1954 product_obj = self.pool.get('product.product')
1955 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1957 # No warning if the quantity was decreased to avoid double warnings:
1958 # The clients should call onchange_quantity too anyway
1960 if product_uos and product_uom and (product_uom != product_uos):
1961 result['product_qty'] = product_uos_qty / uos_coeff['uos_coeff']
1963 result['product_qty'] = product_uos_qty
1964 return {'value': result}
1966 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
1967 loc_dest_id=False, partner_id=False):
1968 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1969 @param prod_id: Changed Product id
1970 @param loc_id: Source location id
1971 @param loc_dest_id: Destination location id
1972 @param partner_id: Address id of partner
1973 @return: Dictionary of values
1977 user = self.pool.get('res.users').browse(cr, uid, uid)
1978 lang = user and user.lang or False
1980 addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
1982 lang = addr_rec and addr_rec.lang or False
1983 ctx = {'lang': lang}
1985 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1986 uos_id = product.uos_id and product.uos_id.id or False
1988 'name': product.partner_ref,
1989 'product_uom': product.uom_id.id,
1990 'product_uos': uos_id,
1991 'product_qty': 1.00,
1992 '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'],
1993 'prodlot_id' : False,
1996 result['location_id'] = loc_id
1998 result['location_dest_id'] = loc_dest_id
1999 return {'value': result}
2001 def onchange_move_type(self, cr, uid, ids, type, context=None):
2002 """ On change of move type gives sorce and destination location.
2003 @param type: Move Type
2004 @return: Dictionary of values
2006 mod_obj = self.pool.get('ir.model.data')
2007 location_source_id = 'stock_location_stock'
2008 location_dest_id = 'stock_location_stock'
2010 location_source_id = 'stock_location_suppliers'
2011 location_dest_id = 'stock_location_stock'
2013 location_source_id = 'stock_location_stock'
2014 location_dest_id = 'stock_location_customers'
2016 source_location = mod_obj.get_object_reference(cr, uid, 'stock', location_source_id)
2017 with tools.mute_logger('openerp.osv.orm'):
2018 self.pool.get('stock.location').check_access_rule(cr, uid, [source_location[1]], 'read', context=context)
2019 except (orm.except_orm, ValueError):
2020 source_location = False
2022 dest_location = mod_obj.get_object_reference(cr, uid, 'stock', location_dest_id)
2023 with tools.mute_logger('openerp.osv.orm'):
2024 self.pool.get('stock.location').check_access_rule(cr, uid, [dest_location[1]], 'read', context=context)
2025 except (orm.except_orm, ValueError):
2026 dest_location = False
2027 return {'value':{'location_id': source_location and source_location[1] or False, 'location_dest_id': dest_location and dest_location[1] or False}}
2029 def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
2030 """ On change of Scheduled Date gives a Move date.
2031 @param date_expected: Scheduled Date
2032 @param date: Move Date
2035 if not date_expected:
2036 date_expected = time.strftime('%Y-%m-%d %H:%M:%S')
2037 return {'value':{'date': date_expected}}
2039 def _chain_compute(self, cr, uid, moves, context=None):
2040 """ Finds whether the location has chained location type or not.
2041 @param moves: Stock moves
2042 @return: Dictionary containing destination location with chained location type.
2046 dest = self.pool.get('stock.location').chained_location_get(
2050 m.picking_id and m.picking_id.partner_id and m.picking_id.partner_id,
2055 if dest[1] == 'transparent':
2056 newdate = (datetime.strptime(m.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d')
2057 self.write(cr, uid, [m.id], {
2059 'location_dest_id': dest[0].id})
2060 if m.picking_id and (dest[3] or dest[5]):
2061 self.pool.get('stock.picking').write(cr, uid, [m.picking_id.id], {
2062 'stock_journal_id': dest[3] or m.picking_id.stock_journal_id.id,
2063 'type': dest[5] or m.picking_id.type
2065 m.location_dest_id = dest[0]
2066 res2 = self._chain_compute(cr, uid, [m], context=context)
2067 for pick_id in res2.keys():
2068 result.setdefault(pick_id, [])
2069 result[pick_id] += res2[pick_id]
2071 result.setdefault(m.picking_id, [])
2072 result[m.picking_id].append( (m, dest) )
2075 def _prepare_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
2076 """Prepare the definition (values) to create a new chained picking.
2078 :param str picking_name: desired new picking name
2079 :param browse_record picking: source picking (being chained to)
2080 :param str picking_type: desired new picking type
2081 :param list moves_todo: specification of the stock moves to be later included in this
2082 picking, in the form::
2084 [[move, (dest_location, auto_packing, chained_delay, chained_journal,
2085 chained_company_id, chained_picking_type)],
2089 See also :meth:`stock_location.chained_location_get`.
2091 res_company = self.pool.get('res.company')
2093 'name': picking_name,
2094 'origin': tools.ustr(picking.origin or ''),
2095 'type': picking_type,
2096 'note': picking.note,
2097 'move_type': picking.move_type,
2098 'auto_picking': moves_todo[0][1][1] == 'auto',
2099 'stock_journal_id': moves_todo[0][1][3],
2100 'company_id': moves_todo[0][1][4] or res_company._company_default_get(cr, uid, 'stock.company', context=context),
2101 'partner_id': picking.partner_id.id,
2102 'invoice_state': 'none',
2103 'date': picking.date,
2106 def _create_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
2107 picking_obj = self.pool.get('stock.picking')
2108 return picking_obj.create(cr, uid, self._prepare_chained_picking(cr, uid, picking_name, picking, picking_type, moves_todo, context=context))
2110 def create_chained_picking(self, cr, uid, moves, context=None):
2111 res_obj = self.pool.get('res.company')
2112 location_obj = self.pool.get('stock.location')
2113 move_obj = self.pool.get('stock.move')
2114 wf_service = netsvc.LocalService("workflow")
2118 seq_obj = self.pool.get('ir.sequence')
2119 for picking, chained_moves in self._chain_compute(cr, uid, moves, context=context).items():
2120 # We group the moves by automatic move type, so it creates different pickings for different types
2122 for move in chained_moves:
2123 moves_by_type.setdefault(move[1][1], []).append(move)
2124 for todo in moves_by_type.values():
2125 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])
2127 # name of new picking according to its type
2128 if ptype == 'internal':
2129 new_pick_name = seq_obj.get(cr, uid,'stock.picking')
2131 new_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + ptype)
2132 pickid = self._create_chained_picking(cr, uid, new_pick_name, picking, ptype, todo, context=context)
2133 # Need to check name of old picking because it always considers picking as "OUT" when created from Sales Order
2134 old_ptype = location_obj.picking_type_get(cr, uid, picking.move_lines[0].location_id, picking.move_lines[0].location_dest_id)
2135 if old_ptype != picking.type:
2136 old_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + old_ptype)
2137 self.pool.get('stock.picking').write(cr, uid, [picking.id], {'name': old_pick_name, 'type': old_ptype}, context=context)
2140 for move, (loc, dummy, delay, dummy, company_id, ptype, invoice_state) in todo:
2141 new_id = move_obj.copy(cr, uid, move.id, {
2142 'location_id': move.location_dest_id.id,
2143 'location_dest_id': loc.id,
2144 'date': time.strftime('%Y-%m-%d'),
2145 'picking_id': pickid,
2147 'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context=context) ,
2148 'move_history_ids': [],
2149 'date_expected': (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
2150 'move_history_ids2': []}
2152 move_obj.write(cr, uid, [move.id], {
2153 'move_dest_id': new_id,
2154 'move_history_ids': [(4, new_id)]
2156 new_moves.append(self.browse(cr, uid, [new_id])[0])
2158 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
2160 new_moves += self.create_chained_picking(cr, uid, new_moves, context)
2163 def action_confirm(self, cr, uid, ids, context=None):
2164 """ Confirms stock move.
2165 @return: List of ids.
2167 moves = self.browse(cr, uid, ids, context=context)
2168 self.write(cr, uid, ids, {'state': 'confirmed'})
2169 self.create_chained_picking(cr, uid, moves, context)
2172 def action_assign(self, cr, uid, ids, *args):
2173 """ Changes state to confirmed or waiting.
2174 @return: List of values
2177 for move in self.browse(cr, uid, ids):
2178 if move.state in ('confirmed', 'waiting'):
2179 todo.append(move.id)
2180 res = self.check_assign(cr, uid, todo)
2183 def force_assign(self, cr, uid, ids, context=None):
2184 """ Changes the state to assigned.
2187 self.write(cr, uid, ids, {'state': 'assigned'})
2188 wf_service = netsvc.LocalService('workflow')
2189 for move in self.browse(cr, uid, ids, context):
2191 wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
2194 def cancel_assign(self, cr, uid, ids, context=None):
2195 """ Changes the state to confirmed.
2198 self.write(cr, uid, ids, {'state': 'confirmed'})
2200 # fix for bug lp:707031
2201 # called write of related picking because changing move availability does
2202 # not trigger workflow of picking in order to change the state of picking
2204 wf_service = netsvc.LocalService('workflow')
2205 for move in self.browse(cr, uid, ids, context):
2206 if move.picking_id and move.picking_id.id not in seen:
2207 wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
2208 seen.add(move.picking_id.id)
2212 # Duplicate stock.move
2214 def check_assign(self, cr, uid, ids, context=None):
2215 """ Checks the product type and accordingly writes the state.
2216 @return: No. of moves done
2223 for move in self.browse(cr, uid, ids, context=context):
2224 if move.product_id.type == 'consu' or move.location_id.usage == 'supplier':
2225 if move.state in ('confirmed', 'waiting'):
2226 done.append(move.id)
2227 pickings[move.picking_id.id] = 1
2229 if move.state in ('confirmed', 'waiting'):
2230 # Important: we must pass lock=True to _product_reserve() to avoid race conditions and double reservations
2231 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)
2233 #_product_available_test depends on the next status for correct functioning
2234 #the test does not work correctly if the same product occurs multiple times
2235 #in the same order. This is e.g. the case when using the button 'split in two' of
2236 #the stock outgoing form
2237 self.write(cr, uid, [move.id], {'state':'assigned'})
2238 done.append(move.id)
2239 pickings[move.picking_id.id] = 1
2241 product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, [move.id], move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty']
2243 'location_id': r[1],
2244 'product_qty': r[0],
2245 'product_uos_qty': product_uos_qty,
2250 product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, [move.id], move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty']
2251 move_id = self.copy(cr, uid, move.id, {'product_uos_qty': product_uos_qty, 'product_qty': r[0], 'location_id': r[1]})
2252 done.append(move_id)
2255 self.write(cr, uid, done, {'state': 'assigned'})
2258 for pick_id in pickings:
2259 wf_service = netsvc.LocalService("workflow")
2260 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
2263 def setlast_tracking(self, cr, uid, ids, context=None):
2264 assert len(ids) == 1, "1 ID expected, got %s" % (ids, )
2265 tracking_obj = self.pool['stock.tracking']
2266 move = self.browse(cr, uid, ids[0], context=context)
2267 picking_id = move.picking_id.id
2269 move_ids = self.search(cr, uid, [
2270 ('picking_id', '=', picking_id),
2271 ('tracking_id', '!=', False)
2272 ], limit=1, order='tracking_id DESC', context=context)
2274 tracking_move = self.browse(cr, uid, move_ids[0],
2276 tracking_id = tracking_move.tracking_id.id
2278 tracking_id = tracking_obj.create(cr, uid, {}, context=context)
2279 self.write(cr, uid, move.id,
2280 {'tracking_id': tracking_id},
2285 # Cancel move => cancel others move and pickings
2287 def action_cancel(self, cr, uid, ids, context=None):
2288 """ Cancels the moves and if all moves are cancelled it cancels the picking.
2296 for move in self.browse(cr, uid, ids, context=context):
2297 if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
2299 pickings.add(move.picking_id.id)
2300 if move.move_dest_id and move.move_dest_id.state == 'waiting':
2301 self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
2302 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
2303 wf_service = netsvc.LocalService("workflow")
2304 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
2305 self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
2306 if not context.get('call_unlink',False):
2307 for pick in self.pool.get('stock.picking').browse(cr, uid, list(pickings), context=context):
2308 if all(move.state == 'cancel' for move in pick.move_lines):
2309 self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'}, context=context)
2311 wf_service = netsvc.LocalService("workflow")
2313 wf_service.trg_trigger(uid, 'stock.move', id, cr)
2316 def _get_accounting_data_for_valuation(self, cr, uid, move, context=None):
2318 Return the accounts and journal to use to post Journal Entries for the real-time
2319 valuation of the move.
2321 :param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key
2322 :raise: osv.except_osv() is any mandatory account or journal is not defined.
2324 product_obj=self.pool.get('product.product')
2325 accounts = product_obj.get_product_accounts(cr, uid, move.product_id.id, context)
2326 if move.location_id.valuation_out_account_id:
2327 acc_src = move.location_id.valuation_out_account_id.id
2329 acc_src = accounts['stock_account_input']
2331 if move.location_dest_id.valuation_in_account_id:
2332 acc_dest = move.location_dest_id.valuation_in_account_id.id
2334 acc_dest = accounts['stock_account_output']
2336 acc_valuation = accounts.get('property_stock_valuation_account_id', False)
2337 journal_id = accounts['stock_journal']
2339 if acc_dest == acc_valuation:
2340 raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Output Account of this product and Valuation account on category of this product are same.'))
2342 if acc_src == acc_valuation:
2343 raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Input Account of this product and Valuation account on category of this product are same.'))
2346 raise osv.except_osv(_('Error!'), _('Please define stock input account for this product or its category: "%s" (id: %d)') % \
2347 (move.product_id.name, move.product_id.id,))
2349 raise osv.except_osv(_('Error!'), _('Please define stock output account for this product or its category: "%s" (id: %d)') % \
2350 (move.product_id.name, move.product_id.id,))
2352 raise osv.except_osv(_('Error!'), _('Please define journal on the product category: "%s" (id: %d)') % \
2353 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
2354 if not acc_valuation:
2355 raise osv.except_osv(_('Error!'), _('Please define inventory valuation account on the product category: "%s" (id: %d)') % \
2356 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
2357 return journal_id, acc_src, acc_dest, acc_valuation
2359 def _get_reference_accounting_values_for_valuation(self, cr, uid, move, context=None):
2361 Return the reference amount and reference currency representing the inventory valuation for this move.
2362 These reference values should possibly be converted before being posted in Journals to adapt to the primary
2363 and secondary currencies of the relevant accounts.
2365 product_uom_obj = self.pool.get('product.uom')
2367 # by default the reference currency is that of the move's company
2368 reference_currency_id = move.company_id.currency_id.id
2370 default_uom = move.product_id.uom_id.id
2371 qty = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
2373 # if product is set to average price and a specific value was entered in the picking wizard,
2375 if move.location_dest_id.usage != 'internal' and move.product_id.cost_method == 'average':
2376 reference_amount = qty * move.product_id.standard_price
2377 elif move.product_id.cost_method == 'average' and move.price_unit:
2378 reference_amount = qty * move.price_unit
2379 reference_currency_id = move.price_currency_id.id or reference_currency_id
2381 # Otherwise we default to the company's valuation price type, considering that the values of the
2382 # valuation field are expressed in the default currency of the move's company.
2386 currency_ctx = dict(context, currency_id = move.company_id.currency_id.id)
2387 amount_unit = move.product_id.price_get('standard_price', context=currency_ctx)[move.product_id.id]
2388 reference_amount = amount_unit * qty
2390 return reference_amount, reference_currency_id
2393 def _create_product_valuation_moves(self, cr, uid, move, context=None):
2395 Generate the appropriate accounting moves if the product being moves is subject
2396 to real_time valuation tracking, and the source or destination location is
2397 a transit location or is outside of the company.
2399 if move.product_id.valuation == 'real_time': # FIXME: product valuation should perhaps be a property?
2402 src_company_ctx = dict(context,force_company=move.location_id.company_id.id)
2403 dest_company_ctx = dict(context,force_company=move.location_dest_id.company_id.id)
2405 # Outgoing moves (or cross-company output part)
2406 if move.location_id.company_id \
2407 and (move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal'\
2408 or move.location_id.company_id != move.location_dest_id.company_id):
2409 journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, src_company_ctx)
2410 reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx)
2411 #returning goods to supplier
2412 if move.location_dest_id.usage == 'supplier':
2413 account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_src, reference_amount, reference_currency_id, context))]
2415 account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_valuation, acc_dest, reference_amount, reference_currency_id, context))]
2417 # Incoming moves (or cross-company input part)
2418 if move.location_dest_id.company_id \
2419 and (move.location_id.usage != 'internal' and move.location_dest_id.usage == 'internal'\
2420 or move.location_id.company_id != move.location_dest_id.company_id):
2421 journal_id, acc_src, acc_dest, acc_valuation = self._get_accounting_data_for_valuation(cr, uid, move, dest_company_ctx)
2422 reference_amount, reference_currency_id = self._get_reference_accounting_values_for_valuation(cr, uid, move, src_company_ctx)
2423 #goods return from customer
2424 if move.location_id.usage == 'customer':
2425 account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_dest, acc_valuation, reference_amount, reference_currency_id, context))]
2427 account_moves += [(journal_id, self._create_account_move_line(cr, uid, move, acc_src, acc_valuation, reference_amount, reference_currency_id, context))]
2429 move_obj = self.pool.get('account.move')
2430 for j_id, move_lines in account_moves:
2431 move_obj.create(cr, uid,
2434 'line_id': move_lines,
2435 'ref': move.picking_id and move.picking_id.name}, context=context)
2437 def action_done(self, cr, uid, ids, context=None):
2438 """ Makes the move done and if all moves are done, it will finish the picking.
2443 wf_service = netsvc.LocalService("workflow")
2448 for move in self.browse(cr, uid, ids, context=context):
2449 if move.state=="draft":
2450 todo.append(move.id)
2452 self.action_confirm(cr, uid, todo, context=context)
2454 for move in self.browse(cr, uid, ids, context=context):
2455 if move.state in ['done','cancel']:
2457 move_ids.append(move.id)
2460 picking_ids.append(move.picking_id.id)
2461 if move.move_dest_id.id and (move.state != 'done'):
2462 # Downstream move should only be triggered if this move is the last pending upstream move
2463 other_upstream_move_ids = self.search(cr, uid, [('id','not in',move_ids),('state','not in',['done','cancel']),
2464 ('move_dest_id','=',move.move_dest_id.id)], context=context)
2465 if not other_upstream_move_ids:
2466 self.write(cr, uid, [move.id], {'move_history_ids': [(4, move.move_dest_id.id)]})
2467 if move.move_dest_id.state in ('waiting', 'confirmed'):
2468 self.force_assign(cr, uid, [move.move_dest_id.id], context=context)
2469 if move.move_dest_id.picking_id:
2470 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
2471 if move.move_dest_id.auto_validate:
2472 self.action_done(cr, uid, [move.move_dest_id.id], context=context)
2474 self._create_product_valuation_moves(cr, uid, move, context=context)
2475 if move.state not in ('confirmed','done','assigned'):
2476 self.action_confirm(cr, uid, [move.id], context=context)
2477 self.write(cr, uid, [move.id],
2479 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)},
2481 for pick_id in picking_ids:
2482 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
2486 def _create_account_move_line(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=None):
2488 Generate the account.move.line values to post to track the stock valuation difference due to the
2489 processing of the given stock move.
2491 # prepare default values considering that the destination accounts have the reference_currency_id as their main currency
2492 partner_id = (move.picking_id.partner_id and self.pool.get('res.partner')._find_accounting_partner(move.picking_id.partner_id).id) or False
2495 'product_id': move.product_id and move.product_id.id or False,
2496 'product_uom_id': move.product_uom and move.product_uom.id or False,
2497 'quantity': move.product_qty,
2498 'ref': move.picking_id and move.picking_id.name or False,
2499 'date': time.strftime('%Y-%m-%d'),
2500 'partner_id': partner_id,
2501 'debit': reference_amount,
2502 'account_id': dest_account_id,
2504 credit_line_vals = {
2506 'product_id': move.product_id and move.product_id.id or False,
2507 'product_uom_id': move.product_uom and move.product_uom.id or False,
2508 'quantity': move.product_qty,
2509 'ref': move.picking_id and move.picking_id.name or False,
2510 'date': time.strftime('%Y-%m-%d'),
2511 'partner_id': partner_id,
2512 'credit': reference_amount,
2513 'account_id': src_account_id,
2516 # if we are posting to accounts in a different currency, provide correct values in both currencies correctly
2517 # when compatible with the optional secondary currency on the account.
2518 # Financial Accounts only accept amounts in secondary currencies if there's no secondary currency on the account
2519 # or if it's the same as that of the secondary amount being posted.
2520 account_obj = self.pool.get('account.account')
2521 src_acct, dest_acct = account_obj.browse(cr, uid, [src_account_id, dest_account_id], context=context)
2522 src_main_currency_id = src_acct.company_id.currency_id.id
2523 dest_main_currency_id = dest_acct.company_id.currency_id.id
2524 cur_obj = self.pool.get('res.currency')
2525 if reference_currency_id != src_main_currency_id:
2527 credit_line_vals['credit'] = cur_obj.compute(cr, uid, reference_currency_id, src_main_currency_id, reference_amount, context=context)
2528 if (not src_acct.currency_id) or src_acct.currency_id.id == reference_currency_id:
2529 credit_line_vals.update(currency_id=reference_currency_id, amount_currency=-reference_amount)
2530 if reference_currency_id != dest_main_currency_id:
2532 debit_line_vals['debit'] = cur_obj.compute(cr, uid, reference_currency_id, dest_main_currency_id, reference_amount, context=context)
2533 if (not dest_acct.currency_id) or dest_acct.currency_id.id == reference_currency_id:
2534 debit_line_vals.update(currency_id=reference_currency_id, amount_currency=reference_amount)
2536 return [(0, 0, debit_line_vals), (0, 0, credit_line_vals)]
2538 def unlink(self, cr, uid, ids, context=None):
2541 ctx = context.copy()
2542 for move in self.browse(cr, uid, ids, context=context):
2543 if move.state != 'draft' and not ctx.get('call_unlink', False):
2544 raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
2545 return super(stock_move, self).unlink(
2546 cr, uid, ids, context=ctx)
2548 # _create_lot function is not used anywhere
2549 def _create_lot(self, cr, uid, ids, product_id, prefix=False):
2550 """ Creates production lot
2551 @return: Production lot id
2553 prodlot_obj = self.pool.get('stock.production.lot')
2554 prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
2557 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
2558 """ Move the scrap/damaged product into scrap location
2559 @param cr: the database cursor
2560 @param uid: the user id
2561 @param ids: ids of stock move object to be scrapped
2562 @param quantity : specify scrap qty
2563 @param location_id : specify scrap location
2564 @param context: context arguments
2565 @return: Scraped lines
2567 #quantity should in MOVE UOM
2569 raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
2571 for move in self.browse(cr, uid, ids, context=context):
2572 source_location = move.location_id
2573 if move.state == 'done':
2574 source_location = move.location_dest_id
2575 if source_location.usage != 'internal':
2576 #restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
2577 raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
2578 move_qty = move.product_qty
2579 uos_qty = quantity / move_qty * move.product_uos_qty
2581 'location_id': source_location.id,
2582 'product_qty': quantity,
2583 'product_uos_qty': uos_qty,
2584 'state': move.state,
2586 'location_dest_id': location_id,
2587 'tracking_id': move.tracking_id.id,
2588 'prodlot_id': move.prodlot_id.id,
2590 new_move = self.copy(cr, uid, move.id, default_val)
2593 product_obj = self.pool.get('product.product')
2594 for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
2596 uom = product.uom_id.name if product.uom_id else ''
2597 message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
2598 move.picking_id.message_post(body=message)
2600 self.action_done(cr, uid, res, context=context)
2603 # action_split function is not used anywhere
2604 # FIXME: deprecate this method
2605 def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
2606 """ Split Stock Move lines into production lot which specified split by quantity.
2607 @param cr: the database cursor
2608 @param uid: the user id
2609 @param ids: ids of stock move object to be splited
2610 @param split_by_qty : specify split by qty
2611 @param prefix : specify prefix of production lot
2612 @param with_lot : if true, prodcution lot will assign for split line otherwise not.
2613 @param context: context arguments
2614 @return: Splited move lines
2620 raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
2624 for move in self.browse(cr, uid, ids, context=context):
2625 if split_by_qty <= 0 or quantity == 0:
2628 uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
2630 quantity_rest = quantity % split_by_qty
2631 uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
2634 'product_qty': split_by_qty,
2635 'product_uos_qty': uos_qty,
2637 for idx in range(int(quantity//split_by_qty)):
2638 if not idx and move.product_qty<=quantity:
2639 current_move = move.id
2641 current_move = self.copy(cr, uid, move.id, {'state': move.state})
2642 res.append(current_move)
2644 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
2646 self.write(cr, uid, [current_move], update_val)
2649 if quantity_rest > 0:
2650 idx = int(quantity//split_by_qty)
2651 update_val['product_qty'] = quantity_rest
2652 update_val['product_uos_qty'] = uos_qty_rest
2653 if not idx and move.product_qty<=quantity:
2654 current_move = move.id
2656 current_move = self.copy(cr, uid, move.id, {'state': move.state})
2658 res.append(current_move)
2662 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
2664 self.write(cr, uid, [current_move], update_val)
2667 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
2668 """ Consumed product with specific quatity from specific source location
2669 @param cr: the database cursor
2670 @param uid: the user id
2671 @param ids: ids of stock move object to be consumed
2672 @param quantity : specify consume quantity
2673 @param location_id : specify source location
2674 @param context: context arguments
2675 @return: Consumed lines
2677 #quantity should in MOVE UOM
2681 raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
2683 for move in self.browse(cr, uid, ids, context=context):
2684 move_qty = move.product_qty
2686 raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
2687 quantity_rest = move.product_qty
2688 quantity_rest -= quantity
2689 uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
2690 if quantity_rest <= 0:
2693 quantity = move.product_qty
2695 uos_qty = quantity / move_qty * move.product_uos_qty
2696 if float_compare(quantity_rest, 0, precision_rounding=move.product_id.uom_id.rounding):
2698 'product_qty': quantity,
2699 'product_uos_qty': uos_qty,
2700 'state': move.state,
2701 'location_id': location_id or move.location_id.id,
2703 current_move = self.copy(cr, uid, move.id, default_val)
2704 res += [current_move]
2706 update_val['product_qty'] = quantity_rest
2707 update_val['product_uos_qty'] = uos_qty_rest
2708 self.write(cr, uid, [move.id], update_val)
2711 quantity_rest = quantity
2712 uos_qty_rest = uos_qty
2715 'product_qty' : quantity_rest,
2716 'product_uos_qty' : uos_qty_rest,
2717 'location_id': location_id or move.location_id.id,
2719 self.write(cr, uid, [move.id], update_val)
2721 self.action_done(cr, uid, res, context=context)
2725 # FIXME: needs refactoring, this code is partially duplicated in stock_picking.do_partial()!
2726 def do_partial(self, cr, uid, ids, partial_datas, context=None):
2727 """ Makes partial pickings and moves done.
2728 @param partial_datas: Dictionary containing details of partial picking
2729 like partner_id, delivery_date, delivery
2730 moves with product_id, product_qty, uom
2733 picking_obj = self.pool.get('stock.picking')
2734 product_obj = self.pool.get('product.product')
2735 currency_obj = self.pool.get('res.currency')
2736 uom_obj = self.pool.get('product.uom')
2737 wf_service = netsvc.LocalService("workflow")
2742 complete, too_many, too_few = [], [], []
2743 move_product_qty = {}
2745 for move in self.browse(cr, uid, ids, context=context):
2746 if move.state in ('done', 'cancel'):
2748 partial_data = partial_datas.get('move%s'%(move.id), False)
2749 assert partial_data, _('Missing partial picking data for move #%s.') % (move.id)
2750 product_qty = partial_data.get('product_qty',0.0)
2751 move_product_qty[move.id] = product_qty
2752 product_uom = partial_data.get('product_uom',False)
2753 product_price = partial_data.get('product_price',0.0)
2754 product_currency = partial_data.get('product_currency',False)
2755 prodlot_ids[move.id] = partial_data.get('prodlot_id')
2756 if move.product_qty == product_qty:
2757 complete.append(move)
2758 elif move.product_qty > product_qty:
2759 too_few.append(move)
2761 too_many.append(move)
2763 # Average price computation
2764 if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
2765 product = product_obj.browse(cr, uid, move.product_id.id)
2766 move_currency_id = move.company_id.currency_id.id
2767 context['currency_id'] = move_currency_id
2768 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
2770 new_price = currency_obj.compute(cr, uid, product_currency,
2771 move_currency_id, product_price, round=False)
2772 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
2774 if product.qty_available <= 0:
2775 new_std_price = new_price
2777 # Get the standard price
2778 amount_unit = product.price_get('standard_price', context=context)[product.id]
2779 new_std_price = ((amount_unit * product.qty_available)\
2780 + (new_price * qty))/(product.qty_available + qty)
2782 product_obj.write(cr, uid, [product.id],{'standard_price': new_std_price})
2784 # Record the values that were chosen in the wizard, so they can be
2785 # used for inventory valuation if real-time valuation is enabled.
2786 self.write(cr, uid, [move.id],
2787 {'price_unit': product_price,
2788 'price_currency_id': product_currency,
2791 for move in too_few:
2792 product_qty = move_product_qty[move.id]
2793 if product_qty != 0:
2795 'product_qty' : product_qty,
2796 'product_uos_qty': product_qty,
2797 'picking_id' : move.picking_id.id,
2798 'state': 'assigned',
2799 'move_dest_id': move.move_dest_id.id,
2800 'price_unit': move.price_unit,
2802 prodlot_id = prodlot_ids[move.id]
2804 defaults.update(prodlot_id=prodlot_id)
2805 new_move = self.copy(cr, uid, move.id, defaults)
2806 complete.append(self.browse(cr, uid, new_move))
2807 self.write(cr, uid, [move.id],
2809 'product_qty': move.product_qty - product_qty,
2810 'product_uos_qty': move.product_qty - product_qty,
2811 'prodlot_id': False,
2812 'tracking_id': False,
2816 for move in too_many:
2817 self.write(cr, uid, [move.id],
2819 'product_qty': move.product_qty,
2820 'product_uos_qty': move.product_qty,
2822 complete.append(move)
2824 for move in complete:
2825 if prodlot_ids.get(move.id):
2826 self.write(cr, uid, [move.id],{'prodlot_id': prodlot_ids.get(move.id)})
2827 self.action_done(cr, uid, [move.id], context=context)
2828 if move.picking_id.id :
2829 # TOCHECK : Done picking if all moves are done
2831 SELECT move.id FROM stock_picking pick
2832 RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
2833 WHERE pick.id = %s""",
2834 ('done', move.picking_id.id))
2836 if len(res) == len(move.picking_id.move_lines):
2837 picking_obj.action_move(cr, uid, [move.picking_id.id])
2838 wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
2840 return [move.id for move in complete]
2844 class stock_inventory(osv.osv):
2845 _name = "stock.inventory"
2846 _description = "Inventory"
2848 'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
2849 'date': fields.datetime('Creation Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2850 'date_done': fields.datetime('Date done'),
2851 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
2852 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
2853 'state': fields.selection( (('draft', 'Draft'), ('cancel','Cancelled'), ('confirm','Confirmed'), ('done', 'Done')), 'Status', readonly=True, select=True),
2854 'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft':[('readonly',False)]}),
2858 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
2860 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
2863 def copy(self, cr, uid, id, default=None, context=None):
2866 default = default.copy()
2867 default.update({'move_ids': [], 'date_done': False})
2868 return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
2870 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2871 """ Creates a stock move from an inventory line
2872 @param inventory_line:
2876 return self.pool.get('stock.move').create(cr, uid, move_vals)
2878 def action_done(self, cr, uid, ids, context=None):
2879 """ Finish the inventory
2884 move_obj = self.pool.get('stock.move')
2885 for inv in self.browse(cr, uid, ids, context=context):
2886 move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
2887 self.write(cr, uid, [inv.id], {'state':'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
2890 def action_confirm(self, cr, uid, ids, context=None):
2891 """ Confirm the inventory and writes its finished date
2896 # to perform the correct inventory corrections we need analyze stock location by
2897 # location, never recursively, so we use a special context
2898 product_context = dict(context, compute_child=False)
2900 location_obj = self.pool.get('stock.location')
2901 for inv in self.browse(cr, uid, ids, context=context):
2903 for line in inv.inventory_line_id:
2904 pid = line.product_id.id
2905 product_context.update(uom=line.product_uom.id, to_date=inv.date, date=inv.date, prodlot_id=line.prod_lot_id.id)
2906 amount = location_obj._product_get(cr, uid, line.location_id.id, [pid], product_context)[pid]
2907 change = line.product_qty - amount
2908 lot_id = line.prod_lot_id.id
2910 location_id = line.product_id.property_stock_inventory.id
2912 'name': _('INV:') + (line.inventory_id.name or ''),
2913 'product_id': line.product_id.id,
2914 'product_uom': line.product_uom.id,
2915 'prodlot_id': lot_id,
2921 'product_qty': change,
2922 'location_id': location_id,
2923 'location_dest_id': line.location_id.id,
2927 'product_qty': -change,
2928 'location_id': line.location_id.id,
2929 'location_dest_id': location_id,
2931 move_ids.append(self._inventory_line_hook(cr, uid, line, value))
2932 self.write(cr, uid, [inv.id], {'state': 'confirm', 'move_ids': [(6, 0, move_ids)]})
2933 self.pool.get('stock.move').action_confirm(cr, uid, move_ids, context=context)
2936 def action_cancel_draft(self, cr, uid, ids, context=None):
2937 """ Cancels the stock move and change inventory state to draft.
2940 for inv in self.browse(cr, uid, ids, context=context):
2941 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2942 self.write(cr, uid, [inv.id], {'state':'draft'}, context=context)
2945 def action_cancel_inventory(self, cr, uid, ids, context=None):
2946 """ Cancels both stock move and inventory
2949 move_obj = self.pool.get('stock.move')
2950 account_move_obj = self.pool.get('account.move')
2951 for inv in self.browse(cr, uid, ids, context=context):
2952 move_obj.action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
2953 for move in inv.move_ids:
2954 account_move_ids = account_move_obj.search(cr, uid, [('name', '=', move.name)])
2955 if account_move_ids:
2956 account_move_data_l = account_move_obj.read(cr, uid, account_move_ids, ['state'], context=context)
2957 for account_move in account_move_data_l:
2958 if account_move['state'] == 'posted':
2959 raise osv.except_osv(_('User Error!'),
2960 _('In order to cancel this inventory, you must first unpost related journal entries.'))
2961 account_move_obj.unlink(cr, uid, [account_move['id']], context=context)
2962 self.write(cr, uid, [inv.id], {'state': 'cancel'}, context=context)
2967 class stock_inventory_line(osv.osv):
2968 _name = "stock.inventory.line"
2969 _description = "Inventory Line"
2970 _rec_name = "inventory_id"
2971 _order = "inventory_id, location_name, product_code, product_name, prodlot_name"
2973 def _get_product_name_change(self, cr, uid, ids, context=None):
2974 return self.pool.get('stock.inventory.line').search(cr, uid, [('product_id', 'in', ids)], context=context)
2976 def _get_location_change(self, cr, uid, ids, context=None):
2977 return self.pool.get('stock.inventory.line').search(cr, uid, [('location_id', 'in', ids)], context=context)
2979 def _get_prodlot_change(self, cr, uid, ids, context=None):
2980 return self.pool.get('stock.inventory.line').search(cr, uid, [('prod_lot_id', 'in', ids)], context=context)
2983 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2984 'location_id': fields.many2one('stock.location', 'Location', required=True),
2985 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
2986 'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
2987 'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
2988 'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True, select=True, readonly=True),
2989 'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
2990 'state': fields.related('inventory_id','state',type='char',string='Status',readonly=True),
2991 'product_name': fields.related('product_id', 'name', type='char', string='Product name', store={
2992 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2993 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2994 'product_code': fields.related('product_id', 'default_code', type='char', string='Product code', store={
2995 'product.product': (_get_product_name_change, ['name', 'default_code'], 20),
2996 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['product_id'], 20),}),
2997 'location_name': fields.related('location_id', 'complete_name', type='char', string='Location name', store={
2998 'stock.location': (_get_location_change, ['name', 'location_id', 'active'], 20),
2999 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['location_id'], 20),}),
3000 'prodlot_name': fields.related('prod_lot_id', 'name', type='char', string='Serial Number name', store={
3001 'stock.production.lot': (_get_prodlot_change, ['name'], 20),
3002 'stock.inventory.line': (lambda self, cr, uid, ids, c={}: ids, ['prod_lot_id'], 20),}),
3005 def _default_stock_location(self, cr, uid, context=None):
3007 location_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock')
3008 with tools.mute_logger('openerp.osv.orm'):
3009 self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
3010 except (orm.except_orm, ValueError):
3015 'location_id': _default_stock_location
3018 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, to_date=False):
3019 """ Changes UoM and name if product_id changes.
3020 @param location_id: Location id
3021 @param product: Changed product_id
3022 @param uom: UoM product
3023 @return: Dictionary of changed values
3026 return {'value': {'product_qty': 0.0, 'product_uom': False, 'prod_lot_id': False}}
3027 obj_product = self.pool.get('product.product').browse(cr, uid, product)
3028 uom = uom or obj_product.uom_id.id
3029 amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date, 'compute_child': False})[product]
3030 result = {'product_qty': amount, 'product_uom': uom, 'prod_lot_id': False}
3031 return {'value': result}
3033 stock_inventory_line()
3035 #----------------------------------------------------------
3037 #----------------------------------------------------------
3038 class stock_warehouse(osv.osv):
3039 _name = "stock.warehouse"
3040 _description = "Warehouse"
3042 'name': fields.char('Name', size=128, required=True, select=True),
3043 'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
3044 'partner_id': fields.many2one('res.partner', 'Owner Address'),
3045 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
3046 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','=','internal')]),
3047 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
3050 def _default_lot_input_stock_id(self, cr, uid, context=None):
3052 lot_input_stock_model, lot_input_stock_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock')
3053 with tools.mute_logger('openerp.osv.orm'):
3054 self.pool.get('stock.location').check_access_rule(cr, uid, [lot_input_stock_id], 'read', context=context)
3055 except (ValueError, orm.except_orm):
3056 # the user does not have read access on the location or it does not exists
3057 lot_input_stock_id = False
3058 return lot_input_stock_id
3060 def _default_lot_output_id(self, cr, uid, context=None):
3062 lot_output_model, lot_output_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_output')
3063 with tools.mute_logger('openerp.osv.orm'):
3064 self.pool.get('stock.location').check_access_rule(cr, uid, [lot_output_id], 'read', context=context)
3065 except (ValueError, orm.except_orm):
3066 # the user does not have read access on the location or it does not exists
3067 lot_output_id = False
3068 return lot_output_id
3071 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
3072 'lot_input_id': _default_lot_input_stock_id,
3073 'lot_stock_id': _default_lot_input_stock_id,
3074 'lot_output_id': _default_lot_output_id,
3079 #----------------------------------------------------------
3080 # "Empty" Classes that are used to vary from the original stock.picking (that are dedicated to the internal pickings)
3081 # in order to offer a different usability with different views, labels, available reports/wizards...
3082 #----------------------------------------------------------
3083 class stock_picking_in(osv.osv):
3084 _name = "stock.picking.in"
3085 _inherit = "stock.picking"
3086 _table = "stock_picking"
3087 _description = "Incoming Shipments"
3089 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
3090 return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
3092 def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
3093 return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
3095 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
3096 return self.pool['stock.picking'].read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
3098 def check_access_rights(self, cr, uid, operation, raise_exception=True):
3099 #override in order to redirect the check of acces rights on the stock.picking object
3100 return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
3102 def check_access_rule(self, cr, uid, ids, operation, context=None):
3103 #override in order to redirect the check of acces rules on the stock.picking object
3104 return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
3106 def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
3107 #override in order to trigger the workflow of stock.picking at the end of create, write and unlink operation
3108 #instead of it's own workflow (which is not existing)
3109 return self.pool.get('stock.picking')._workflow_trigger(cr, uid, ids, trigger, context=context)
3111 def _workflow_signal(self, cr, uid, ids, signal, context=None):
3112 #override in order to fire the workflow signal on given stock.picking workflow instance
3113 #instead of it's own workflow (which is not existing)
3114 return self.pool.get('stock.picking')._workflow_signal(cr, uid, ids, signal, context=context)
3116 def message_post(self, *args, **kwargs):
3117 """Post the message on stock.picking to be able to see it in the form view when using the chatter"""
3118 return self.pool.get('stock.picking').message_post(*args, **kwargs)
3120 def message_subscribe(self, *args, **kwargs):
3121 """Send the subscribe action on stock.picking model as it uses _name in request"""
3122 return self.pool.get('stock.picking').message_subscribe(*args, **kwargs)
3124 def message_unsubscribe(self, *args, **kwargs):
3125 """Send the unsubscribe action on stock.picking model to match with subscribe"""
3126 return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs)
3128 def default_get(self, cr, uid, fields_list, context=None):
3129 # merge defaults from stock.picking with possible defaults defined on stock.picking.in
3130 defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context)
3131 in_defaults = super(stock_picking_in, self).default_get(cr, uid, fields_list, context=context)
3132 defaults.update(in_defaults)
3136 'backorder_id': fields.many2one('stock.picking.in', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
3137 'state': fields.selection(
3138 [('draft', 'Draft'),
3139 ('auto', 'Waiting Another Operation'),
3140 ('confirmed', 'Waiting Availability'),
3141 ('assigned', 'Ready to Receive'),
3142 ('done', 'Received'),
3143 ('cancel', 'Cancelled'),],
3144 'Status', readonly=True, select=True,
3145 help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
3146 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
3147 * Waiting Availability: still waiting for the availability of products\n
3148 * Ready to Receive: products reserved, simply waiting for confirmation.\n
3149 * Received: has been processed, can't be modified or cancelled anymore\n
3150 * Cancelled: has been cancelled, can't be confirmed anymore"""),
3156 class stock_picking_out(osv.osv):
3157 _name = "stock.picking.out"
3158 _inherit = "stock.picking"
3159 _table = "stock_picking"
3160 _description = "Delivery Orders"
3162 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
3163 return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
3165 def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
3166 return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
3168 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
3169 return self.pool['stock.picking'].read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)
3171 def check_access_rights(self, cr, uid, operation, raise_exception=True):
3172 #override in order to redirect the check of acces rights on the stock.picking object
3173 return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
3175 def check_access_rule(self, cr, uid, ids, operation, context=None):
3176 #override in order to redirect the check of acces rules on the stock.picking object
3177 return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
3179 def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
3180 #override in order to trigger the workflow of stock.picking at the end of create, write and unlink operation
3181 #instead of it's own workflow (which is not existing)
3182 return self.pool.get('stock.picking')._workflow_trigger(cr, uid, ids, trigger, context=context)
3184 def _workflow_signal(self, cr, uid, ids, signal, context=None):
3185 #override in order to fire the workflow signal on given stock.picking workflow instance
3186 #instead of it's own workflow (which is not existing)
3187 return self.pool.get('stock.picking')._workflow_signal(cr, uid, ids, signal, context=context)
3189 def message_post(self, *args, **kwargs):
3190 """Post the message on stock.picking to be able to see it in the form view when using the chatter"""
3191 return self.pool.get('stock.picking').message_post(*args, **kwargs)
3193 def message_subscribe(self, *args, **kwargs):
3194 """Send the subscribe action on stock.picking model as it uses _name in request"""
3195 return self.pool.get('stock.picking').message_subscribe(*args, **kwargs)
3197 def message_unsubscribe(self, *args, **kwargs):
3198 """Send the unsubscribe action on stock.picking model to match with subscribe"""
3199 return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs)
3201 def default_get(self, cr, uid, fields_list, context=None):
3202 # merge defaults from stock.picking with possible defaults defined on stock.picking.out
3203 defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context)
3204 out_defaults = super(stock_picking_out, self).default_get(cr, uid, fields_list, context=context)
3205 defaults.update(out_defaults)
3209 'backorder_id': fields.many2one('stock.picking.out', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
3210 'state': fields.selection(
3211 [('draft', 'Draft'),
3212 ('auto', 'Waiting Another Operation'),
3213 ('confirmed', 'Waiting Availability'),
3214 ('assigned', 'Ready to Deliver'),
3215 ('done', 'Delivered'),
3216 ('cancel', 'Cancelled'),],
3217 'Status', readonly=True, select=True,
3218 help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
3219 * Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
3220 * Waiting Availability: still waiting for the availability of products\n
3221 * Ready to Deliver: products reserved, simply waiting for confirmation.\n
3222 * Delivered: has been processed, can't be modified or cancelled anymore\n
3223 * Cancelled: has been cancelled, can't be confirmed anymore"""),
3229 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: