1 ##############################################################################
3 # OpenERP, Open Source Management Solution
4 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as
8 # published by the Free Software Foundation, either version 3 of the
9 # License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Affero General Public License for more details.
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 ##############################################################################
21 from datetime import datetime
22 from dateutil.relativedelta import relativedelta
25 from osv import fields, osv
26 from tools import config
27 from tools.translate import _
30 import decimal_precision as dp
33 #----------------------------------------------------------
35 #----------------------------------------------------------
36 class stock_incoterms(osv.osv):
37 _name = "stock.incoterms"
38 _description = "Incoterms"
40 '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."),
41 'code': fields.char('Code', size=3, required=True, help="Code for Incoterms"),
42 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the incoterms without removing it."),
50 class stock_journal(osv.osv):
51 _name = "stock.journal"
52 _description = "Stock Journal"
54 'name': fields.char('Stock Journal', size=32, required=True),
55 'user_id': fields.many2one('res.users', 'Responsible'),
58 'user_id': lambda s, c, u, ctx: u
63 #----------------------------------------------------------
65 #----------------------------------------------------------
66 class stock_location(osv.osv):
67 _name = "stock.location"
68 _description = "Location"
69 _parent_name = "location_id"
72 _order = 'parent_left'
74 def name_get(self, cr, uid, ids, context=None):
80 reads = self.read(cr, uid, ids, ['name','location_id'], context=context)
83 if context.get('full',False):
84 if record['location_id']:
85 name = record['location_id'][1] + ' / ' + name
86 res.append((record['id'], name))
88 res.append((record['id'], name))
91 def _complete_name(self, cr, uid, ids, name, args, context=None):
92 """ Forms complete name of location from parent location to child location.
93 @return: Dictionary of values
95 def _get_one_full_name(location, level=4):
96 if location.location_id:
97 parent_path = _get_one_full_name(location.location_id, level-1) + "/"
100 return parent_path + location.name
102 for m in self.browse(cr, uid, ids, context=context):
103 res[m.id] = _get_one_full_name(m)
106 def _product_qty_available(self, cr, uid, ids, field_names, arg, context=None):
107 """ Finds real and virtual quantity for product available at particular location.
108 @return: Dictionary of values
112 res[id] = {}.fromkeys(field_names, 0.0)
113 if ('product_id' not in context) or not ids:
116 context['location'] = [loc]
117 prod = self.pool.get('product.product').browse(cr, uid, context['product_id'], context)
118 if 'stock_real' in field_names:
119 res[loc]['stock_real'] = prod.qty_available
120 if 'stock_virtual' in field_names:
121 res[loc]['stock_virtual'] = prod.virtual_available
124 def product_detail(self, cr, uid, id, field, context=None):
125 """ Finds detail of product like price type, currency and then calculates its price.
126 @param field: Field name
127 @return: Calculated price
132 field_to_read = 'virtual_available'
135 if field == 'stock_real_value':
136 field_to_read = 'qty_available'
137 cr.execute('select distinct product_id from stock_move where (location_id=%s) or (location_dest_id=%s)', (id, id))
138 result = cr.dictfetchall()
140 # Choose the right filed standard_price to read
141 # Take the user company
142 price_type_id = self.pool.get('res.users').browse(cr,uid,uid).company_id.property_valuation_price_type.id
143 pricetype = self.pool.get('product.price.type').browse(cr, uid, price_type_id, context=context)
145 c = (context or {}).copy()
147 product = self.pool.get('product.product').read(cr, uid, r['product_id'], [field_to_read], context=c)
148 # Compute the amount_unit in right currency
149 context['currency_id'] = self.pool.get('res.users').browse(cr,uid,uid).company_id.currency_id.id
150 amount_unit = self.pool.get('product.product').browse(cr,uid,r['product_id']).price_get(pricetype.field, context)[r['product_id']]
151 final_value += (product[field_to_read] * amount_unit)
154 def _product_value(self, cr, uid, ids, field_names, arg, context=None):
155 """ Calculates real and virtual stock value of a product.
156 @param field_names: Name of field
157 @return: Dictionary of values
161 result[id] = {}.fromkeys(field_names, 0.0)
162 for field_name in field_names:
164 ret_dict = self.product_detail(cr, uid, loc, field=field_name)
165 result[loc][field_name] = ret_dict
169 'name': fields.char('Location Name', size=64, required=True, translate=True),
170 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the stock location without removing it."),
171 '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),
172 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
173 'complete_name': fields.function(_complete_name, method=True, type='char', size=100, string="Location Name"),
175 'stock_real': fields.function(_product_qty_available, method=True, type='float', string='Real Stock', multi="stock"),
176 'stock_virtual': fields.function(_product_qty_available, method=True, type='float', string='Virtual Stock', multi="stock"),
178 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
179 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
181 'chained_journal_id': fields.many2one('stock.journal', 'Chained Journal'),
182 'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
183 'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
184 'Chained Location Type', required=True),
185 'chained_auto_packing': fields.selection(
186 [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
189 help="This is used only if you select a chained location type.\n" \
190 "The 'Automatic Move' value will create a stock move after the current one that will be "\
191 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
192 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
194 'chained_picking_type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('delivery', 'Delivery')], 'Shipping Type', help="Shipping type specify of the chained move, goods coming in or going out."),
195 'chained_company_id': fields.many2one('res.company', 'Chained Company', help='Set here the belonging company of the chained move'),
196 'chained_delay': fields.integer('Chained lead time (days)'),
197 'address_id': fields.many2one('res.partner.address', 'Location Address'),
198 'icon': fields.selection(tools.icons, 'Icon', size=64),
200 'comment': fields.text('Additional Information'),
201 'posx': fields.integer('Corridor (X)'),
202 'posy': fields.integer('Shelves (Y)'),
203 'posz': fields.integer('Height (Z)'),
205 'parent_left': fields.integer('Left Parent', select=1),
206 'parent_right': fields.integer('Right Parent', select=1),
207 'stock_real_value': fields.function(_product_value, method=True, type='float', string='Real Stock Value', multi="stock"),
208 'stock_virtual_value': fields.function(_product_value, method=True, type='float', string='Virtual Stock Value', multi="stock"),
209 'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared for every companies'),
210 'scrap_location': fields.boolean('Scrap Location', help='Check this box if the current location is a place for destroyed items'),
215 'allocation_method': 'fifo',
216 'chained_location_type': 'none',
217 'chained_auto_packing': 'manual',
218 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
223 'scrap_location': False,
226 def chained_location_get(self, cr, uid, location, partner=None, product=None, context=None):
227 """ Finds chained location
228 @param location: Location id
229 @param partner: Partner id
230 @param product: Product id
231 @return: List of values
234 if location.chained_location_type == 'customer':
236 result = partner.property_stock_customer
237 elif location.chained_location_type == 'fixed':
238 result = location.chained_location_id
240 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
243 def picking_type_get(self, cr, uid, from_location, to_location, context=None):
244 """ Gets type of picking.
245 @param from_location: Source location
246 @param to_location: Destination location
247 @return: Location type
250 if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
252 elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage == 'internal'):
256 def _product_get_all_report(self, cr, uid, ids, product_ids=False, context=None):
257 return self._product_get_report(cr, uid, ids, product_ids, context, recursive=True)
259 def _product_get_report(self, cr, uid, ids, product_ids=False,
260 context=None, recursive=False):
261 """ Finds the product quantity and price for particular location.
262 @param product_ids: Ids of product
263 @param recursive: True or False
264 @return: Dictionary of values
268 product_obj = self.pool.get('product.product')
269 # Take the user company and pricetype
270 price_type_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.property_valuation_price_type.id
271 pricetype = self.pool.get('product.price.type').browse(cr, uid, price_type_id)
272 context['currency_id'] = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id
275 product_ids = product_obj.search(cr, uid, [])
277 products = product_obj.browse(cr, uid, product_ids, context=context)
280 for product in products:
281 products_by_uom.setdefault(product.uom_id.id, [])
282 products_by_uom[product.uom_id.id].append(product)
283 products_by_id.setdefault(product.id, [])
284 products_by_id[product.id] = product
287 result['product'] = []
291 for uom_id in products_by_uom.keys():
292 fnc = self._product_get
294 fnc = self._product_all_get
297 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
299 for product_id in qty.keys():
300 if not qty[product_id]:
302 product = products_by_id[product_id]
303 quantity_total += qty[product_id]
305 # Compute based on pricetype
306 # Choose the right filed standard_price to read
307 amount_unit = product.price_get(pricetype.field, context)[product.id]
308 price = qty[product_id] * amount_unit
311 result['product'].append({
312 'price': amount_unit,
313 'prod_name': product.name,
314 'code': product.default_code, # used by lot_overview_all report!
315 'variants': product.variants or '',
316 'uom': product.uom_id.name,
317 'prod_qty': qty[product_id],
318 'price_value': price,
320 result['total'] = quantity_total
321 result['total_price'] = total_price
324 def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context=None,
325 states=['done'], what=('in', 'out')):
327 @param product_ids: Ids of product
328 @param states: List of states
329 @param what: Tuple of
332 product_obj = self.pool.get('product.product')
340 return product_obj.get_product_available(cr, uid, product_ids, context=context)
342 def _product_get(self, cr, uid, id, product_ids=False, context=None, states=['done']):
348 ids = id and [id] or []
349 return self._product_get_multi_location(cr, uid, ids, product_ids, context=context, states=states)
351 def _product_all_get(self, cr, uid, id, product_ids=False, context=None, states=['done']):
352 # build the list of ids of children of the location given by id
353 ids = id and [id] or []
354 location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
355 return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
357 def _product_virtual_get(self, cr, uid, id, product_ids=False, context=None, states=['done']):
358 return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
360 def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None):
362 @param product_id: Id of product
363 @param product_qty: Quantity of product
364 @return: List of Values or False
370 for id in self.search(cr, uid, [('location_id', 'child_of', ids)]):
371 cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id))
372 results = cr.dictfetchall()
373 cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id))
374 results += cr.dictfetchall()
379 amount = self.pool.get('product.uom')._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
388 if amount > min(total, product_qty):
389 amount = min(product_qty, total)
390 result.append((amount, id))
391 product_qty -= amount
393 if product_qty <= 0.0:
402 class stock_tracking(osv.osv):
403 _name = "stock.tracking"
404 _description = "Packs"
407 salt = '31' * 8 + '3'
409 for sscc_part, salt_part in zip(sscc, salt):
410 sum += int(sscc_part) * int(salt_part)
411 return (10 - (sum % 10)) % 10
412 checksum = staticmethod(checksum)
414 def make_sscc(self, cr, uid, context=None):
415 sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
416 return sequence + str(self.checksum(sequence))
419 'name': fields.char('Tracking ID', size=64, required=True),
420 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the pack without removing it."),
421 'serial': fields.char('Reference', size=64),
422 'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves Tracked'),
423 'date': fields.datetime('Created Date', required=True),
428 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
431 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
436 ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
437 ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
438 return self.name_get(cr, user, ids, context)
440 def name_get(self, cr, uid, ids, context=None):
443 res = [(r['id'], r['name']+' ['+(r['serial'] or '')+']') for r in self.read(cr, uid, ids, ['name', 'serial'], context)]
446 def unlink(self, cr, uid, ids, context=None):
447 raise osv.except_osv(_('Error'), _('You can not remove a lot line !'))
451 #----------------------------------------------------------
453 #----------------------------------------------------------
454 class stock_picking(osv.osv):
455 _name = "stock.picking"
456 _description = "Picking List"
458 def _set_maximum_date(self, cr, uid, ids, name, value, arg, context=None):
459 """ Calculates planned date if it is greater than 'value'.
460 @param name: Name of field
461 @param value: Value of field
462 @param arg: User defined argument
463 @return: True or False
467 if isinstance(ids, (int, long)):
469 for pick in self.browse(cr, uid, ids, context):
470 sql_str = """update stock_move set
473 picking_id=%d """ % (value, pick.id)
476 sql_str += " and (date_planned='" + pick.max_date + "' or date_planned>'" + value + "')"
480 def _set_minimum_date(self, cr, uid, ids, name, value, arg, context=None):
481 """ Calculates planned date if it is less than 'value'.
482 @param name: Name of field
483 @param value: Value of field
484 @param arg: User defined argument
485 @return: True or False
489 if isinstance(ids, (int, long)):
491 for pick in self.browse(cr, uid, ids, context=context):
492 sql_str = """update stock_move set
495 picking_id=%s """ % (value, pick.id)
497 sql_str += " and (date_planned='" + pick.min_date + "' or date_planned<'" + value + "')"
501 def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
502 """ Finds minimum and maximum dates for picking.
503 @return: Dictionary of values
507 res[id] = {'min_date': False, 'max_date': False}
519 picking_id""",(tuple(ids),))
520 for pick, dt1, dt2 in cr.fetchall():
521 res[pick]['min_date'] = dt1
522 res[pick]['max_date'] = dt2
525 def create(self, cr, user, vals, context=None):
526 if ('name' not in vals) or (vals.get('name')=='/'):
527 seq_obj_name = 'stock.picking.' + vals['type']
528 vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
529 new_id = super(stock_picking, self).create(cr, user, vals, context)
533 'name': fields.char('Reference', size=64, select=True),
534 'origin': fields.char('Origin', size=64, help="Reference of the document that produced this picking."),
535 'backorder_id': fields.many2one('stock.picking', 'Back Order', help="If the picking is splitted then the picking id in available state of move for this picking is stored in Backorder."),
536 'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('delivery', 'Delivery')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."),
537 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the picking without removing it."),
538 'note': fields.text('Notes'),
539 'stock_journal_id': fields.many2one('stock.journal','Stock Journal'),
540 'location_id': fields.many2one('stock.location', 'Location', help="Keep empty if you produce at the location where the finished products are needed." \
541 "Set a location if you produce at a fixed location. This can be a partner location " \
542 "if you subcontract the manufacturing operations."),
543 'location_dest_id': fields.many2one('stock.location', 'Dest. Location',help="Location where the system will stock the finished products."),
544 'move_type': fields.selection([('direct', 'Direct Delivery'), ('one', 'All at once')], 'Delivery Method', required=True, help="It specifies goods to be delivered all at once or by direct delivery"),
545 'state': fields.selection([
548 ('confirmed', 'Confirmed'),
549 ('assigned', 'Available'),
551 ('cancel', 'Cancelled'),
552 ], 'State', readonly=True, select=True,
553 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed picking. \
554 \n* The \'Confirmed\' state is used for stock movement to do with unavailable products. \
555 \n* The \'Available\' state is set automatically when the products are ready to be moved.\
556 \n* The \'Waiting\' state is used in MTO moves when a movement is waiting for another one.'),
557 'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
558 method=True, store=True, type='datetime', string='Expected Date', select=1, help="Expected date for Picking. Default it takes current date"),
559 'date': fields.datetime('Order Date', help="Date of Order"),
560 'date_done': fields.datetime('Date Done', help="Date of Completion"),
561 'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
562 method=True, store=True, type='datetime', string='Max. Expected Date', select=2),
563 'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
564 'auto_picking': fields.boolean('Auto-Picking'),
565 'address_id': fields.many2one('res.partner.address', 'Partner', help="Address of partner"),
566 'invoice_state': fields.selection([
567 ("invoiced", "Invoiced"),
568 ("2binvoiced", "To Be Invoiced"),
569 ("none", "Not from Picking")], "Invoice Status",
570 select=True, required=True, readonly=True, states={'draft': [('readonly', False)]}),
571 'company_id': fields.many2one('res.company', 'Company', required=True, select=1),
574 'name': lambda self, cr, uid, context: '/',
577 'move_type': 'direct',
579 'invoice_state': 'none',
580 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
581 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.picking', context=c)
584 def copy(self, cr, uid, id, default=None, context=None):
587 default = default.copy()
588 picking_obj = self.browse(cr, uid, [id], context)[0]
589 if ('name' not in default) or (picking_obj.name=='/'):
590 seq_obj_name = 'stock.picking.' + picking_obj.type
591 default['name'] = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
592 return super(stock_picking, self).copy(cr, uid, id, default, context)
594 def onchange_partner_in(self, cr, uid, context=None, partner_id=None):
597 def action_explode(self, cr, uid, moves, context=None):
600 def action_confirm(self, cr, uid, ids, context=None):
601 """ Confirms picking.
604 self.write(cr, uid, ids, {'state': 'confirmed'})
606 for picking in self.browse(cr, uid, ids, context=context):
607 for r in picking.move_lines:
608 if r.state == 'draft':
611 self.log_picking(cr, uid, ids, context=context)
613 todo = self.action_explode(cr, uid, todo, context)
615 self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
618 def test_auto_picking(self, cr, uid, ids):
619 # TODO: Check locations to see if in the same location ?
622 def action_assign(self, cr, uid, ids, *args):
623 """ Changes state of picking to available if all moves are confirmed.
626 for pick in self.browse(cr, uid, ids):
627 move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
629 raise osv.except_osv(_('Warning !'),_('Not Available. Moves are not confirmed.'))
630 self.pool.get('stock.move').action_assign(cr, uid, move_ids)
633 def force_assign(self, cr, uid, ids, *args):
634 """ Changes state of picking to available if moves are confirmed or waiting.
637 wf_service = netsvc.LocalService("workflow")
638 for pick in self.browse(cr, uid, ids):
639 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
640 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
641 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
644 def draft_force_assign(self, cr, uid, ids, *args):
645 """ Confirms picking directly from draft state.
648 wf_service = netsvc.LocalService("workflow")
649 for pick in self.browse(cr, uid, ids):
650 if not pick.move_lines:
651 raise osv.except_osv(_('Error !'),_('You can not process picking without stock moves'))
652 wf_service.trg_validate(uid, 'stock.picking', pick.id,
653 'button_confirm', cr)
656 def draft_validate(self, cr, uid, ids, *args):
657 """ Validates picking directly from draft state.
660 wf_service = netsvc.LocalService("workflow")
661 self.draft_force_assign(cr, uid, ids)
662 for pick in self.browse(cr, uid, ids):
663 move_ids = [x.id for x in pick.move_lines]
664 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
665 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
667 self.action_move(cr, uid, [pick.id])
668 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
671 def cancel_assign(self, cr, uid, ids, *args):
672 """ Cancels picking and moves.
675 wf_service = netsvc.LocalService("workflow")
676 for pick in self.browse(cr, uid, ids):
677 move_ids = [x.id for x in pick.move_lines]
678 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
679 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
682 def action_assign_wkf(self, cr, uid, ids, context=None):
683 """ Changes picking state to assigned.
686 self.write(cr, uid, ids, {'state': 'assigned'})
687 self.log_picking(cr, uid, ids, context=context)
690 def test_finnished(self, cr, uid, ids):
691 """ Tests whether the move is in done or cancel state or not.
692 @return: True or False
694 move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
695 for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
696 if move.state not in ('done', 'cancel'):
697 if move.product_qty != 0.0:
700 move.write(cr, uid, [move.id], {'state': 'done'})
703 def test_assigned(self, cr, uid, ids):
704 """ Tests whether the move is in assigned state or not.
705 @return: True or False
708 for pick in self.browse(cr, uid, ids):
710 for move in pick.move_lines:
711 if (move.state in ('confirmed', 'draft')) and (mt == 'one'):
713 if (mt == 'direct') and (move.state == 'assigned') and (move.product_qty):
715 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
718 def action_cancel(self, cr, uid, ids, context=None):
719 """ Changes picking state to cancel.
722 for pick in self.browse(cr, uid, ids):
723 ids2 = [move.id for move in pick.move_lines]
724 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
725 self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
726 self.log_picking(cr, uid, ids, context=context)
730 # TODO: change and create a move if not parents
732 def action_done(self, cr, uid, ids, context=None):
733 """ Changes picking state to done.
736 self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
739 def action_move(self, cr, uid, ids, context=None):
740 """ Changes move state to assigned.
743 for pick in self.browse(cr, uid, ids):
745 for move in pick.move_lines:
746 if move.state == 'assigned':
749 self.pool.get('stock.move').action_done(cr, uid, todo,
753 def get_currency_id(self, cr, uid, picking):
756 def _get_payment_term(self, cr, uid, picking):
757 """ Gets payment term from partner.
758 @return: Payment term
760 partner_obj = self.pool.get('res.partner')
761 partner = picking.address_id.partner_id
762 return partner.property_payment_term and partner.property_payment_term.id or False
764 def _get_address_invoice(self, cr, uid, picking):
765 """ Gets invoice address of a partner
766 @return {'contact': address, 'invoice': address} for invoice
768 partner_obj = self.pool.get('res.partner')
769 partner = picking.address_id.partner_id
771 return partner_obj.address_get(cr, uid, [partner.id],
772 ['contact', 'invoice'])
774 def _get_comment_invoice(self, cr, uid, picking):
776 @return: comment string for invoice
778 return picking.note or ''
780 def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None):
781 """ Gets price unit for invoice
782 @param move_line: Stock move lines
783 @param type: Type of invoice
784 @return: The price unit for the move line
789 if type in ('in_invoice', 'in_refund'):
790 # Take the user company and pricetype
791 price_type_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.property_valuation_price_type.id
792 pricetype = self.pool.get('product.price.type').browse(cr, uid, price_type_id)
793 context['currency_id'] = move_line.company_id.currency_id.id
795 amount_unit = move_line.product_id.price_get(pricetype.field, context)[move_line.product_id.id]
798 return move_line.product_id.list_price
800 def _get_discount_invoice(self, cr, uid, move_line):
801 '''Return the discount for the move line'''
804 def _get_taxes_invoice(self, cr, uid, move_line, type):
805 """ Gets taxes on invoice
806 @param move_line: Stock move lines
807 @param type: Type of invoice
808 @return: Taxes Ids for the move line
810 if type in ('in_invoice', 'in_refund'):
811 taxes = move_line.product_id.supplier_taxes_id
813 taxes = move_line.product_id.taxes_id
815 if move_line.picking_id and move_line.picking_id.address_id and move_line.picking_id.address_id.partner_id:
816 return self.pool.get('account.fiscal.position').map_tax(
819 move_line.picking_id.address_id.partner_id.property_account_position,
823 return map(lambda x: x.id, taxes)
825 def _get_account_analytic_invoice(self, cr, uid, picking, move_line):
828 def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
829 '''Call after the creation of the invoice line'''
832 def _invoice_hook(self, cr, uid, picking, invoice_id):
833 '''Call after the creation of the invoice'''
836 def action_invoice_create(self, cr, uid, ids, journal_id=False,
837 group=False, type='out_invoice', context=None):
838 """ Creates invoice based on the invoice state selected for picking.
839 @param journal_id: Id of journal
840 @param group: Whether to create a group invoice or not
841 @param type: Type invoice to be created
842 @return: Ids of created invoices for the pickings
847 invoice_obj = self.pool.get('account.invoice')
848 invoice_line_obj = self.pool.get('account.invoice.line')
852 for picking in self.browse(cr, uid, ids, context=context):
853 if picking.invoice_state != '2binvoiced':
855 payment_term_id = False
856 partner = picking.address_id and picking.address_id.partner_id
858 raise osv.except_osv(_('Error, no partner !'),
859 _('Please put a partner on the picking list if you want to generate invoice.'))
861 if type in ('out_invoice', 'out_refund'):
862 account_id = partner.property_account_receivable.id
863 payment_term_id = self._get_payment_term(cr, uid, picking)
865 account_id = partner.property_account_payable.id
867 address_contact_id, address_invoice_id = \
868 self._get_address_invoice(cr, uid, picking).values()
870 comment = self._get_comment_invoice(cr, uid, picking)
871 if group and partner.id in invoices_group:
872 invoice_id = invoices_group[partner.id]
873 invoice = invoice_obj.browse(cr, uid, invoice_id)
875 'name': (invoice.name or '') + ', ' + (picking.name or ''),
876 'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
877 'comment': (comment and (invoice.comment and invoice.comment+"\n"+comment or comment)) or (invoice.comment and invoice.comment or ''),
878 'date_invoice':context.get('date_inv',False),
881 invoice_obj.write(cr, uid, [invoice_id], invoice_vals, context=context)
884 'name': picking.name,
885 'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
887 'account_id': account_id,
888 'partner_id': partner.id,
889 'address_invoice_id': address_invoice_id,
890 'address_contact_id': address_contact_id,
892 'payment_term': payment_term_id,
893 'fiscal_position': partner.property_account_position.id,
894 'date_invoice': context.get('date_inv',False),
895 'company_id': picking.company_id.id,
898 cur_id = self.get_currency_id(cr, uid, picking)
900 invoice_vals['currency_id'] = cur_id
902 invoice_vals['journal_id'] = journal_id
903 invoice_id = invoice_obj.create(cr, uid, invoice_vals,
905 invoices_group[partner.id] = invoice_id
906 res[picking.id] = invoice_id
907 for move_line in picking.move_lines:
908 origin = move_line.picking_id.name or ''
909 if move_line.picking_id.origin:
910 origin += ':' + move_line.picking_id.origin
912 name = (picking.name or '') + '-' + move_line.name
914 name = move_line.name
916 if type in ('out_invoice', 'out_refund'):
917 account_id = move_line.product_id.product_tmpl_id.\
918 property_account_income.id
920 account_id = move_line.product_id.categ_id.\
921 property_account_income_categ.id
923 account_id = move_line.product_id.product_tmpl_id.\
924 property_account_expense.id
926 account_id = move_line.product_id.categ_id.\
927 property_account_expense_categ.id
929 price_unit = self._get_price_unit_invoice(cr, uid,
931 discount = self._get_discount_invoice(cr, uid, move_line)
932 tax_ids = self._get_taxes_invoice(cr, uid, move_line, type)
933 account_analytic_id = self._get_account_analytic_invoice(cr, uid, picking, move_line)
935 #set UoS if it's a sale and the picking doesn't have one
936 uos_id = move_line.product_uos and move_line.product_uos.id or False
937 if not uos_id and type in ('out_invoice', 'out_refund'):
938 uos_id = move_line.product_uom.id
940 account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, partner.property_account_position, account_id)
942 if ('sale_line_id' in move_line._columns.keys()) and move_line.sale_line_id:
943 notes = move_line.sale_line_id.notes
944 elif ('purchase_line_id' in move_line._columns.keys()) and move_line.purchase_line_id:
945 notes = move_line.purchase_line_id.notes
947 invoice_line_id = invoice_line_obj.create(cr, uid, {
950 'invoice_id': invoice_id,
952 'product_id': move_line.product_id.id,
953 'account_id': account_id,
954 'price_unit': price_unit,
955 'discount': discount,
956 'quantity': move_line.product_uos_qty or move_line.product_qty,
957 'invoice_line_tax_id': [(6, 0, tax_ids)],
958 'account_analytic_id': account_analytic_id,
961 self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
963 invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
964 set_total=(type in ('in_invoice', 'in_refund')))
965 self.write(cr, uid, [picking.id], {
966 'invoice_state': 'invoiced',
968 self._invoice_hook(cr, uid, picking, invoice_id)
969 self.write(cr, uid, res.keys(), {
970 'invoice_state': 'invoiced',
974 def test_done(self, cr, uid, ids, context=None):
975 """ Test whether the move lines are done or not.
976 @return: True or False
979 for pick in self.browse(cr, uid, ids, context=context):
980 if not pick.move_lines:
982 for move in pick.move_lines:
983 if move.state not in ('cancel','done'):
985 if move.state=='done':
989 def test_cancel(self, cr, uid, ids, context=None):
990 """ Test whether the move lines are canceled or not.
991 @return: True or False
993 for pick in self.browse(cr, uid, ids, context=context):
994 if not pick.move_lines:
996 for move in pick.move_lines:
997 if move.state not in ('cancel',):
1001 def unlink(self, cr, uid, ids, context=None):
1002 move_obj = self.pool.get('stock.move')
1005 for pick in self.browse(cr, uid, ids, context=context):
1006 if pick.state in ['done','cancel']:
1007 raise osv.except_osv(_('Error'), _('You cannot remove the picking which is in %s state !')%(pick.state,))
1008 elif pick.state in ['confirmed','assigned', 'draft']:
1009 ids2 = [move.id for move in pick.move_lines]
1010 ctx = context.copy()
1011 ctx.update({'call_unlink':True})
1012 if pick.state != 'draft':
1013 #Cancelling the move in order to affect Virtual stock of product
1014 move_obj.action_cancel(cr, uid, ids2, ctx)
1016 move_obj.unlink(cr, uid, ids2, ctx)
1018 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
1020 def do_partial(self, cr, uid, ids, partial_datas, context=None):
1021 """ Makes partial picking and moves done.
1022 @param partial_datas : Dictionary containing details of partial picking
1023 like partner_id, address_id, delivery_date,
1024 delivery moves with product_id, product_qty, uom
1025 @return: Dictionary of values
1028 move_obj = self.pool.get('stock.move')
1029 product_obj = self.pool.get('product.product')
1030 currency_obj = self.pool.get('res.currency')
1031 users_obj = self.pool.get('res.users')
1032 uom_obj = self.pool.get('product.uom')
1033 price_type_obj = self.pool.get('product.price.type')
1034 sequence_obj = self.pool.get('ir.sequence')
1035 wf_service = netsvc.LocalService("workflow")
1036 partner_id = partial_datas.get('partner_id', False)
1037 address_id = partial_datas.get('address_id', False)
1038 delivery_date = partial_datas.get('delivery_date', False)
1039 for pick in self.browse(cr, uid, ids, context=context):
1042 complete, too_many, too_few = [], [], []
1043 move_product_qty = {}
1044 for move in pick.move_lines:
1045 if move.state in ('done', 'cancel'):
1047 partial_data = partial_datas.get('move%s'%(move.id), False)
1048 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
1049 product_qty = partial_data.get('product_qty',0.0)
1050 move_product_qty[move.id] = product_qty
1051 product_uom = partial_data.get('product_uom',False)
1052 product_price = partial_data.get('product_price',0.0)
1053 product_currency = partial_data.get('product_currency',False)
1054 if move.product_qty == product_qty:
1055 complete.append(move)
1056 elif move.product_qty > product_qty:
1057 too_few.append(move)
1059 too_many.append(move)
1061 # Average price computation
1062 if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
1063 product = product_obj.browse(cr, uid, move.product_id.id)
1064 user = users_obj.browse(cr, uid, uid)
1065 context['currency_id'] = move.company_id.currency_id.id
1066 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
1068 if user.company_id.property_valuation_price_type:
1069 pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
1070 if pricetype and qty > 0:
1071 new_price = currency_obj.compute(cr, uid, product_currency,
1072 user.company_id.currency_id.id, product_price)
1073 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
1075 if product.qty_available <= 0:
1076 new_std_price = new_price
1078 # Get the standard price
1079 amount_unit = product.price_get(pricetype.field, context)[product.id]
1080 new_std_price = ((amount_unit * product.qty_available)\
1081 + (new_price * qty))/(product.qty_available + qty)
1083 # Write the field according to price type field
1084 product_obj.write(cr, uid, [product.id],
1085 {pricetype.field: new_std_price})
1086 move_obj.write(cr, uid, [move.id], {'price_unit': new_price})
1089 for move in too_few:
1090 product_qty = move_product_qty[move.id]
1093 new_picking = self.copy(cr, uid, pick.id,
1095 'name': sequence_obj.get(cr, uid, 'stock.picking.%s'%(pick.type)),
1099 if product_qty != 0:
1101 new_obj = move_obj.copy(cr, uid, move.id,
1103 'product_qty' : product_qty,
1104 'product_uos_qty': product_qty, #TODO: put correct uos_qty
1105 'picking_id' : new_picking,
1106 'state': 'assigned',
1107 'move_dest_id': False,
1108 'price_unit': move.price_unit,
1111 move_obj.write(cr, uid, [move.id],
1113 'product_qty' : move.product_qty - product_qty,
1114 'product_uos_qty':move.product_qty - product_qty, #TODO: put correct uos_qty
1119 move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
1120 for move in too_many:
1121 product_qty = move_product_qty[move.id]
1122 move_obj.write(cr, uid, [move.id],
1124 'product_qty' : product_qty,
1125 'product_uos_qty': product_qty, #TODO: put correct uos_qty
1126 'picking_id': new_picking,
1129 for move in too_many:
1130 product_qty = move_product_qty[move.id]
1131 move_obj.write(cr, uid, [move.id],
1133 'product_qty': product_qty,
1134 'product_uos_qty': product_qty #TODO: put correct uos_qty
1137 # At first we confirm the new picking (if necessary)
1139 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
1140 # Then we finish the good picking
1142 self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
1143 self.action_move(cr, uid, [new_picking])
1144 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr)
1145 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
1146 delivered_pack_id = new_picking
1148 self.action_move(cr, uid, [pick.id])
1149 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
1150 delivered_pack_id = pick.id
1152 delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
1153 res[pick.id] = {'delivered_picking': delivered_pack.id or False}
1157 def log_picking(self, cr, uid, ids, context=None):
1158 """ This function will create log messages for picking.
1159 @param cr: the database cursor
1160 @param uid: the current user's ID for security checks,
1161 @param ids: List of Picking Ids
1162 @param context: A standard dictionary for contextual values
1164 for pick in self.browse(cr, uid, ids, context=context):
1166 'out':'Picking List',
1168 'internal': 'Internal picking',
1169 'delivery': 'Delivery order'
1171 message = type_list.get(pick.type, _('Document')) + " '" + (pick.name or 'n/a') + "' "
1173 'confirmed': "is scheduled for the '" + datetime.strptime(pick.min_date, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d') + "'.",
1174 'assigned': 'is ready to process.',
1175 'cancel': 'is Cancelled.',
1176 'done': 'is processed.',
1178 message += state_list[pick.state]
1179 self.log(cr, uid, pick.id, message)
1184 class stock_production_lot(osv.osv):
1186 def name_get(self, cr, uid, ids, context=None):
1189 reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
1191 for record in reads:
1192 name = record['name']
1193 prefix = record['prefix']
1195 name = prefix + '/' + name
1197 name = '%s [%s]' % (name, record['ref'])
1198 res.append((record['id'], name))
1201 _name = 'stock.production.lot'
1202 _description = 'Production lot'
1204 def _get_stock(self, cr, uid, ids, field_name, arg, context=None):
1205 """ Gets stock of products for locations
1206 @return: Dictionary of values
1208 if 'location_id' not in context:
1209 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
1211 locations = context['location_id'] and [context['location_id']] or []
1213 if isinstance(ids, (int, long)):
1216 res = {}.fromkeys(ids, 0.0)
1218 cr.execute('''select
1222 stock_report_prodlots
1224 location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),))
1225 res.update(dict(cr.fetchall()))
1229 def _stock_search(self, cr, uid, obj, name, args, context=None):
1230 """ Searches Ids of products
1231 @return: Ids of locations
1233 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
1234 cr.execute('''select
1238 stock_report_prodlots
1240 location_id IN %s group by prodlot_id
1241 having sum(name) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),))
1243 ids = [('id', 'in', map(lambda x: x[0], res))]
1247 'name': fields.char('Serial', size=64, required=True),
1248 'ref': fields.char('Internal Reference', size=256),
1249 'prefix': fields.char('Prefix', size=64),
1250 'product_id': fields.many2one('product.product', 'Product', required=True),
1251 'date': fields.datetime('Created Date', required=True),
1252 'stock_available': fields.function(_get_stock, fnct_search=_stock_search, method=True, type="float", string="Available", select="2"),
1253 'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
1254 'company_id': fields.many2one('res.company','Company',select=1),
1257 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
1258 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1259 'product_id': lambda x, y, z, c: c.get('product_id', False),
1261 _sql_constraints = [
1262 ('name_ref_uniq', 'unique (name, ref)', 'The serial/ref must be unique !'),
1265 stock_production_lot()
1267 class stock_production_lot_revision(osv.osv):
1268 _name = 'stock.production.lot.revision'
1269 _description = 'Production lot revisions'
1272 'name': fields.char('Revision Name', size=64, required=True),
1273 'description': fields.text('Description'),
1274 'date': fields.date('Revision Date'),
1275 'indice': fields.char('Revision', size=16),
1276 'author_id': fields.many2one('res.users', 'Author'),
1277 'lot_id': fields.many2one('stock.production.lot', 'Production lot', select=True, ondelete='cascade'),
1278 'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
1282 'author_id': lambda x, y, z, c: z,
1283 'date': time.strftime('%Y-%m-%d'),
1286 stock_production_lot_revision()
1288 # ----------------------------------------------------
1290 # ----------------------------------------------------
1294 # location_dest_id is only used for predicting futur stocks
1296 class stock_move(osv.osv):
1298 def _getSSCC(self, cr, uid, context=None):
1299 cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
1301 return (res and res[0]) or False
1302 _name = "stock.move"
1303 _description = "Stock Move"
1304 _order = 'date_expected desc, id'
1307 def name_get(self, cr, uid, ids, context=None):
1309 for line in self.browse(cr, uid, ids, context):
1310 res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))
1313 def _check_tracking(self, cr, uid, ids):
1314 """ Checks if production lot is assigned to stock move or not.
1315 @return: True or False
1317 for move in self.browse(cr, uid, ids):
1318 if not move.prodlot_id and \
1319 (move.state == 'done' and \
1321 (move.product_id.track_production and move.location_id.usage=='production') or \
1322 (move.product_id.track_production and move.location_dest_id.usage=='production') or \
1323 (move.product_id.track_incoming and move.location_id.usage in ('supplier','internal')) or \
1324 (move.product_id.track_outgoing and move.location_dest_id.usage in ('customer','internal')) \
1329 def _check_product_lot(self, cr, uid, ids):
1330 """ Checks whether move is done or not and production lot is assigned to that move.
1331 @return: True or False
1333 for move in self.browse(cr, uid, ids):
1334 if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id):
1339 'name': fields.char('Name', size=64, required=True, select=True),
1340 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1342 'date': fields.datetime('Created Date'),
1343 'date_planned': fields.datetime('Date', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
1344 'date_expected': fields.datetime('Date Expected', readonly=True,required=True, help="Scheduled date for the movement of the products"),
1345 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
1347 'product_qty': fields.float('Quantity', required=True),
1348 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True),
1349 'product_uos_qty': fields.float('Quantity (UOS)'),
1350 'product_uos': fields.many2one('product.uom', 'Product UOS'),
1351 'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1353 'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."),
1354 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, select=True, help="Location where the system will stock the finished products."),
1355 'address_id': fields.many2one('res.partner.address', 'Dest. Address', help="Address where goods are to be delivered"),
1357 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="Production lot is used to put a serial number on the production"),
1358 'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, help="This is the code that will be put on the logistical unit: pallet, box, pack."),
1360 'auto_validate': fields.boolean('Auto Validate'),
1362 'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),
1363 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
1364 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
1365 'picking_id': fields.many2one('stock.picking', 'Picking List', select=True),
1366 'note': fields.text('Notes'),
1367 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'State', readonly=True, select=True,
1368 help='When the stock move is created it is in the \'Draft\' state.\n After that it is set to \'Confirmed\' state.\n If stock is available state is set to \'Available\'.\n When the picking is done the state is \'Done\'.\
1369 \nThe state is \'Waiting\' if the move is waiting for another one.'),
1370 'price_unit': fields.float('Unit Price',
1371 digits_compute= dp.get_precision('Account')),
1372 'company_id': fields.many2one('res.company', 'Company', required=True, select=1),
1373 'partner_id': fields.related('picking_id','address_id','partner_id',type='many2one', relation="res.partner", string="Partner", store=True),
1374 'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Order"),
1375 'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Origin",store=True),
1376 'scraped': fields.related('location_dest_id','scrap_location',type='boolean',relation='stock.location',string='Scraped'),
1377 'move_stock_return_history': fields.many2many('stock.move', 'stock_move_return_history', 'move_id', 'return_move_id', 'Move Return History',readonly=True),
1381 'You must assign a production lot for this product',
1383 (_check_product_lot,
1384 'You try to assign a lot which is not from the same product',
1387 def _default_location_destination(self, cr, uid, context=None):
1388 """ Gets default address of partner for destination location
1389 @return: Address id or False
1391 if context.get('move_line', []):
1392 if context['move_line'][0]:
1393 if isinstance(context['move_line'][0], (tuple, list)):
1394 return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
1396 move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1397 return move_list and move_list['location_dest_id'][0] or False
1398 if context.get('address_out_id', False):
1399 property_out = self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer
1400 return property_out and property_out.id or False
1403 def _default_location_source(self, cr, uid, context=None):
1404 """ Gets default address of partner for source location
1405 @return: Address id or False
1407 if context.get('move_line', []):
1409 return context['move_line'][0][2]['location_id']
1412 if context.get('address_in_id', False):
1413 return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1417 'location_id': _default_location_source,
1418 'location_dest_id': _default_location_destination,
1423 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S'),
1424 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
1425 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1426 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
1429 def copy(self, cr, uid, id, default=None, context=None):
1432 default = default.copy()
1433 default['move_stock_return_history'] = []
1434 return super(stock_move, self).copy(cr, uid, id, default, context=context)
1436 def _auto_init(self, cursor, context=None):
1437 res = super(stock_move, self)._auto_init(cursor, context=context)
1438 cursor.execute('SELECT indexname \
1440 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1441 if not cursor.fetchone():
1442 cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1443 ON stock_move (location_id, location_dest_id, product_id, state)')
1446 def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
1447 loc_id=False, product_id=False, context=None):
1448 """ On change of production lot gives a warning message.
1449 @param prodlot_id: Changed production lot id
1450 @param product_qty: Quantity of product
1451 @param loc_id: Location id
1452 @param product_id: Product id
1453 @return: Warning message
1455 if not prodlot_id or not loc_id:
1457 ctx = context and context.copy() or {}
1458 ctx['location_id'] = loc_id
1459 prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1460 location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1462 if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1464 'title': 'Bad Lot Assignation !',
1465 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1467 return {'warning': warning}
1469 def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
1470 product_uom, product_uos):
1471 """ On change of product quantity finds UoM and UoS quantities
1472 @param product_id: Product id
1473 @param product_qty: Changed Quantity of product
1474 @param product_uom: Unit of measure of product
1475 @param product_uos: Unit of sale of product
1476 @return: Dictionary of values
1479 'product_uos_qty': 0.00
1482 if (not product_id) or (product_qty <=0.0):
1483 return {'value': result}
1485 product_obj = self.pool.get('product.product')
1486 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1488 if product_uos and product_uom and (product_uom != product_uos):
1489 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1491 result['product_uos_qty'] = product_qty
1493 return {'value': result}
1495 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
1496 loc_dest_id=False, address_id=False):
1497 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1498 @param prod_id: Changed Product id
1499 @param loc_id: Source location id
1500 @param loc_id: Destination location id
1501 @param address_id: Address id of partner
1502 @return: Dictionary of values
1508 addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1510 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1511 ctx = {'lang': lang}
1513 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1514 uos_id = product.uos_id and product.uos_id.id or False
1516 'product_uom': product.uom_id.id,
1517 'product_uos': uos_id,
1518 'product_qty': 1.00,
1519 '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']
1522 result['name'] = product.partner_ref
1524 result['location_id'] = loc_id
1526 result['location_dest_id'] = loc_dest_id
1527 return {'value': result}
1529 def _chain_compute(self, cr, uid, moves, context=None):
1530 """ Finds whether the location has chained location type or not.
1531 @param moves: Stock moves
1532 @return: Dictionary containing destination location with chained location type.
1536 dest = self.pool.get('stock.location').chained_location_get(
1540 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1545 if dest[1] == 'transparent':
1546 self.write(cr, uid, [m.id], {
1547 'date_planned': (datetime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1548 relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1549 'location_dest_id': dest[0].id})
1551 result.setdefault(m.picking_id, [])
1552 result[m.picking_id].append( (m, dest) )
1555 def action_confirm(self, cr, uid, ids, context=None):
1556 """ Confirms stock move.
1557 @return: List of ids.
1559 moves = self.browse(cr, uid, ids)
1560 self.write(cr, uid, ids, {'state': 'confirmed'})
1563 def create_chained_picking(self, cr, uid, moves, context=None):
1565 res_obj = self.pool.get('res.company')
1566 picking_obj = self.pool.get('stock.picking')
1567 move_obj = self.pool.get('stock.move')
1570 for picking, todo in self._chain_compute(cr, uid, moves, context=context).items():
1571 ptype = todo[0][1][5] and todo[0][1][5] or self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
1572 pick_name = picking.name
1573 if ptype == 'delivery':
1574 pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.delivery')
1576 pickid = picking_obj.create(cr, uid, {
1578 'origin': str(picking.origin or ''),
1580 'note': picking.note,
1581 'move_type': picking.move_type,
1582 'auto_picking': todo[0][1][1] == 'auto',
1583 'stock_journal_id': todo[0][1][3],
1584 'company_id': todo[0][1][4] or res_obj._company_default_get(cr, uid, 'stock.company', context),
1585 'address_id': picking.address_id.id,
1586 'invoice_state': 'none',
1587 'date': picking.date,
1588 'sale_id':' sale_id' in picking._columns.keys() and picking.sale_id.id or False
1590 for move, (loc, auto, delay, journal, company_id, ptype) in todo:
1591 new_id = move_obj.copy(cr, uid, move.id, {
1592 'location_id': move.location_dest_id.id,
1593 'location_dest_id': loc.id,
1594 'date_moved': time.strftime('%Y-%m-%d'),
1595 'picking_id': pickid,
1597 'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context) ,
1598 'move_history_ids': [],
1599 'date_planned': (datetime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
1600 'move_history_ids2': []}
1602 move_obj.write(cr, uid, [move.id], {
1603 'move_dest_id': new_id,
1604 'move_history_ids': [(4, new_id)]
1606 new_moves.append(self.browse(cr, uid, [new_id])[0])
1607 wf_service = netsvc.LocalService("workflow")
1608 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1610 create_chained_picking(self, cr, uid, new_moves, context)
1611 create_chained_picking(self, cr, uid, moves, context)
1614 def action_assign(self, cr, uid, ids, *args):
1615 """ Changes state to confirmed or waiting.
1616 @return: List of values
1619 for move in self.browse(cr, uid, ids):
1620 if move.state in ('confirmed', 'waiting'):
1621 todo.append(move.id)
1622 res = self.check_assign(cr, uid, todo)
1625 def force_assign(self, cr, uid, ids, context={}):
1626 """ Changes the state to assigned.
1629 self.write(cr, uid, ids, {'state': 'assigned'})
1632 def cancel_assign(self, cr, uid, ids, context={}):
1633 """ Changes the state to confirmed.
1636 self.write(cr, uid, ids, {'state': 'confirmed'})
1640 # Duplicate stock.move
1642 def check_assign(self, cr, uid, ids, context=None):
1643 """ Checks the product type and accordingly writes the state.
1644 @return: No. of moves done
1651 for move in self.browse(cr, uid, ids, context=context):
1652 if move.product_id.type == 'consu':
1653 if move.state in ('confirmed', 'waiting'):
1654 done.append(move.id)
1655 pickings[move.picking_id.id] = 1
1657 if move.state in ('confirmed', 'waiting'):
1658 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})
1660 #_product_available_test depends on the next status for correct functioning
1661 #the test does not work correctly if the same product occurs multiple times
1662 #in the same order. This is e.g. the case when using the button 'split in two' of
1663 #the stock outgoing form
1664 self.write(cr, uid, move.id, {'state':'assigned'})
1665 done.append(move.id)
1666 pickings[move.picking_id.id] = 1
1668 cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1672 move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1673 done.append(move_id)
1676 self.write(cr, uid, done, {'state': 'assigned'})
1679 for pick_id in pickings:
1680 wf_service = netsvc.LocalService("workflow")
1681 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1684 def setlast_tracking(self, cr, uid, ids, context=None):
1685 tracking_obj = self.pool.get('stock.tracking')
1686 tracking = context.get('tracking', False)
1687 last_track = [line.tracking_id.id for line in self.browse(cr, uid, ids)[0].picking_id.move_lines if line.tracking_id]
1689 last_track = tracking_obj.create(cr, uid, {}, context=context)
1692 last_track = last_track[-1]
1693 self.write(cr, uid, ids, {'tracking_id': last_track})
1697 # Cancel move => cancel others move and pickings
1699 def action_cancel(self, cr, uid, ids, context=None):
1700 """ Cancels the moves and if all moves are cancelled it cancels the picking.
1708 for move in self.browse(cr, uid, ids):
1709 if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1711 pickings[move.picking_id.id] = True
1712 if move.move_dest_id and move.move_dest_id.state == 'waiting':
1713 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1714 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1715 wf_service = netsvc.LocalService("workflow")
1716 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1717 self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1718 if not context.get('call_unlink',False):
1719 for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1720 if all(move.state == 'cancel' for move in pick.move_lines):
1721 self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1723 wf_service = netsvc.LocalService("workflow")
1725 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1728 def _get_accounting_values(self, cr, uid, move, context=None):
1729 product_obj=self.pool.get('product.product')
1730 product_uom_obj = self.pool.get('product.uom')
1731 price_type_obj = self.pool.get('product.price.type')
1732 accounts = product_obj.get_product_accounts(cr,uid,move.product_id.id,context)
1733 acc_src = accounts['stock_account_input']
1734 acc_dest = accounts['stock_account_output']
1735 acc_variation = accounts.get('property_stock_variation', False)
1736 journal_id = accounts['stock_journal']
1742 raise osv.except_osv(_('Error!'), _('There is no stock input account defined ' \
1743 'for this product: "%s" (id: %d)') % \
1744 (move.product_id.name, move.product_id.id,))
1746 raise osv.except_osv(_('Error!'), _('There is no stock output account defined ' \
1747 'for this product: "%s" (id: %d)') % \
1748 (move.product_id.name, move.product_id.id,))
1750 raise osv.except_osv(_('Error!'), _('There is no journal defined '\
1751 'on the product category: "%s" (id: %d)') % \
1752 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1753 if not acc_variation:
1754 raise osv.except_osv(_('Error!'), _('There is no variation account defined '\
1755 'on the product category: "%s" (id: %d)') % \
1756 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1757 if acc_src != acc_dest:
1758 default_uom = move.product_id.uom_id.id
1759 q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1760 if move.product_id.cost_method == 'average' and move.price_unit:
1761 amount = q * move.price_unit
1762 # Base computation on valuation price type
1764 company_id = move.company_id.id
1765 context['currency_id'] = move.company_id.currency_id.id
1766 pricetype = price_type_obj.browse(cr,uid,move.company_id.property_valuation_price_type.id)
1767 amount_unit = move.product_id.price_get(pricetype.field, context)[move.product_id.id]
1768 amount = amount_unit * q or 1.0
1769 return journal_id, acc_src, acc_dest, acc_variation, amount
1771 def action_done(self, cr, uid, ids, context=None):
1772 """ Makes the move done and if all moves are done, it will finish the picking.
1777 product_uom_obj = self.pool.get('product.uom')
1778 price_type_obj = self.pool.get('product.price.type')
1779 product_obj = self.pool.get('product.product')
1780 move_obj = self.pool.get('account.move')
1783 for move in self.browse(cr, uid, ids):
1785 picking_ids.append(move.picking_id.id)
1786 if move.move_dest_id.id and (move.state != 'done'):
1787 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1788 if move.move_dest_id.state in ('waiting', 'confirmed'):
1789 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1790 if move.move_dest_id.picking_id:
1791 wf_service = netsvc.LocalService("workflow")
1792 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1795 if move.move_dest_id.auto_validate:
1796 self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1799 # Accounting Entries
1803 if move.product_id.valuation == 'real_time':
1805 if ((move.location_id.usage == 'internal' and move.location_dest_id.usage == 'customer') or (move.location_id.usage == 'internal' and move.location_dest_id.usage == 'transit')):
1806 if move.location_id.company_id:
1807 context.update({'force_company': move.location_id.company_id.id})
1808 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1809 lines = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1811 elif ((move.location_id.usage == 'supplier' and move.location_dest_id.usage == 'internal') or (move.location_id.usage == 'transit' and move.location_dest_id.usage == 'internal')):
1812 if move.location_dest_id.company_id:
1813 context.update({'force_company': move.location_dest_id.company_id.id})
1814 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1815 lines = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1816 elif (move.location_id.usage == 'internal' and move.location_dest_id.usage == 'internal' and move.location_id.company_id != move.location_dest_id.company_id):
1817 if move.location_id.company_id:
1818 context.update({'force_company': move.location_id.company_id.id})
1819 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1820 line1 = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1821 if move.location_dest_id.company_id:
1822 context.update({'force_company': move.location_dest_id.company_id.id})
1823 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1824 line2 = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1825 lines = line1 + line2
1826 for j_id, line in lines:
1827 move_obj.create(cr, uid, {
1830 'type':'cont_voucher',
1832 'ref': move.picking_id and move.picking_id.name,
1835 self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1836 wf_service = netsvc.LocalService("workflow")
1838 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1840 picking_obj = self.pool.get('stock.picking')
1841 wf_service = netsvc.LocalService("workflow")
1842 for pick_id in picking_ids:
1843 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1845 picking_obj.log_picking(cr, uid, picking_ids, context=context)
1848 def create_account_move(self, cr, uid, move,account_id, account_variation, amount, context=None):
1851 partner_id = move.picking_id.address_id and (move.picking_id.address_id.partner_id and move.picking_id.address_id.partner_id.id or False) or False
1854 'quantity': move.product_qty,
1855 'product_id': move.product_id and move.product_id.id or False,
1857 'account_id': account_id,
1858 'ref': move.picking_id and move.picking_id.name or False,
1859 'date': time.strftime('%Y-%m-%d') ,
1860 'partner_id': partner_id,
1864 'product_id': move.product_id and move.product_id.id or False,
1865 'quantity': move.product_qty,
1867 'account_id': account_variation,
1868 'ref': move.picking_id and move.picking_id.name or False,
1869 'date': time.strftime('%Y-%m-%d') ,
1870 'partner_id': partner_id,
1874 def unlink(self, cr, uid, ids, context=None):
1877 for move in self.browse(cr, uid, ids, context=context):
1878 if move.state != 'draft':
1879 raise osv.except_osv(_('UserError'),
1880 _('You can only delete draft moves.'))
1881 return super(stock_move, self).unlink(
1882 cr, uid, ids, context=context)
1884 def _create_lot(self, cr, uid, ids, product_id, prefix=False):
1885 """ Creates production lot
1886 @return: Production lot id
1888 prodlot_obj = self.pool.get('stock.production.lot')
1889 prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
1892 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1893 """ Move the scrap/damaged product into scrap location
1894 @param cr: the database cursor
1895 @param uid: the user id
1896 @param ids: ids of stock move object to be scraped
1897 @param quantity : specify scrap qty
1898 @param location_id : specify scrap location
1899 @param context: context arguments
1900 @return: Scraped lines
1903 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1905 for move in self.browse(cr, uid, ids, context=context):
1906 move_qty = move.product_qty
1907 uos_qty = quantity / move_qty * move.product_uos_qty
1909 'product_qty': quantity,
1910 'product_uos_qty': uos_qty,
1911 'state': move.state,
1913 'location_dest_id': location_id
1915 new_move = self.copy(cr, uid, move.id, default_val)
1917 product_obj = self.pool.get('product.product')
1918 for (id, name) in product_obj.name_get(cr, uid, [move.product_id.id]):
1919 message = _('Product ') + " '" + name + "' "+ _("is scraped with") + " '" + str(move.product_qty) + "' "+ _("quantity.")
1920 self.log(cr, uid, move.id, message)
1922 self.action_done(cr, uid, res)
1925 def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
1926 """ Split Stock Move lines into production lot which specified split by quantity.
1927 @param cr: the database cursor
1928 @param uid: the user id
1929 @param ids: ids of stock move object to be splited
1930 @param split_by_qty : specify split by qty
1931 @param prefix : specify prefix of production lot
1932 @param with_lot : if true, prodcution lot will assign for split line otherwise not.
1933 @param context: context arguments
1934 @return: Splited move lines
1940 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1944 for move in self.browse(cr, uid, ids):
1945 if split_by_qty <= 0 or quantity == 0:
1948 uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
1950 quantity_rest = quantity % split_by_qty
1951 uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
1954 'product_qty': split_by_qty,
1955 'product_uos_qty': uos_qty,
1957 for idx in range(int(quantity//split_by_qty)):
1958 if not idx and move.product_qty<=quantity:
1959 current_move = move.id
1961 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1962 res.append(current_move)
1964 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1966 self.write(cr, uid, [current_move], update_val)
1969 if quantity_rest > 0:
1970 idx = int(quantity//split_by_qty)
1971 update_val['product_qty'] = quantity_rest
1972 update_val['product_uos_qty'] = uos_qty_rest
1973 if not idx and move.product_qty<=quantity:
1974 current_move = move.id
1976 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1978 res.append(current_move)
1982 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1984 self.write(cr, uid, [current_move], update_val)
1987 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
1988 """ Consumed product with specific quatity from specific source location
1989 @param cr: the database cursor
1990 @param uid: the user id
1991 @param ids: ids of stock move object to be consumed
1992 @param quantity : specify consume quantity
1993 @param location_id : specify source location
1994 @param context: context arguments
1995 @return: Consumed lines
2000 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
2003 for move in self.browse(cr, uid, ids, context=context):
2004 move_qty = move.product_qty
2005 quantity_rest = move.product_qty
2007 quantity_rest -= quantity
2008 uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
2009 if quantity_rest <= 0:
2012 quantity = move.product_qty
2014 uos_qty = quantity / move_qty * move.product_uos_qty
2016 if quantity_rest > 0:
2018 'product_qty': quantity,
2019 'product_uos_qty': uos_qty,
2020 'state': move.state,
2021 'location_id': location_id
2023 if move.product_id.track_production and location_id:
2024 # IF product has checked track for production lot, move lines will be split by 1
2025 res += self.action_split(cr, uid, [move.id], quantity, split_by_qty=1, context=context)
2027 current_move = self.copy(cr, uid, move.id, default_val)
2028 res += [current_move]
2030 update_val['product_qty'] = quantity_rest
2031 update_val['product_uos_qty'] = uos_qty_rest
2032 self.write(cr, uid, [move.id], update_val)
2035 quantity_rest = quantity
2036 uos_qty_rest = uos_qty
2037 if move.product_id.track_production and location_id:
2038 res += self.split_lines(cr, uid, [move.id], quantity_rest, split_by_qty=1, context=context)
2042 'product_qty' : quantity_rest,
2043 'product_uos_qty' : uos_qty_rest,
2044 'location_id': location_id
2047 self.write(cr, uid, [move.id], update_val)
2049 product_obj = self.pool.get('product.product')
2050 for new_move in self.browse(cr, uid, res, context=context):
2051 for (id, name) in product_obj.name_get(cr, uid, [new_move.product_id.id]):
2052 message = _('Product ') + " '" + name + "' "+ _("is consumed with") + " '" + str(new_move.product_qty) + "' "+ _("quantity.")
2053 self.log(cr, uid, new_move.id, message)
2054 self.action_done(cr, uid, res)
2058 def do_partial(self, cr, uid, ids, partial_datas, context=None):
2059 """ Makes partial pickings and moves done.
2060 @param partial_datas: Dictionary containing details of partial picking
2061 like partner_id, address_id, delivery_date, delivery
2062 moves with product_id, product_qty, uom
2065 picking_obj = self.pool.get('stock.picking')
2066 product_obj = self.pool.get('product.product')
2067 currency_obj = self.pool.get('res.currency')
2068 users_obj = self.pool.get('res.users')
2069 uom_obj = self.pool.get('product.uom')
2070 price_type_obj = self.pool.get('product.price.type')
2071 sequence_obj = self.pool.get('ir.sequence')
2072 wf_service = netsvc.LocalService("workflow")
2073 partner_id = partial_datas.get('partner_id', False)
2074 address_id = partial_datas.get('address_id', False)
2075 delivery_date = partial_datas.get('delivery_date', False)
2081 complete, too_many, too_few = [], [], []
2082 move_product_qty = {}
2083 for move in self.browse(cr, uid, ids, context=context):
2084 if move.state in ('done', 'cancel'):
2086 partial_data = partial_datas.get('move%s'%(move.id), False)
2087 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
2088 product_qty = partial_data.get('product_qty',0.0)
2089 move_product_qty[move.id] = product_qty
2090 product_uom = partial_data.get('product_uom',False)
2091 product_price = partial_data.get('product_price',0.0)
2092 product_currency = partial_data.get('product_currency',False)
2093 if move.product_qty == product_qty:
2094 complete.append(move)
2095 elif move.product_qty > product_qty:
2096 too_few.append(move)
2098 too_many.append(move)
2100 # Average price computation
2101 if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
2102 product = product_obj.browse(cr, uid, move.product_id.id)
2103 user = users_obj.browse(cr, uid, uid)
2104 context['currency_id'] = move.company_id.currency_id.id
2105 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
2107 if user.company_id.property_valuation_price_type:
2108 pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
2109 if pricetype and qty > 0:
2110 new_price = currency_obj.compute(cr, uid, product_currency,
2111 user.company_id.currency_id.id, product_price)
2112 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
2114 if product.qty_available <= 0:
2115 new_std_price = new_price
2117 # Get the standard price
2118 amount_unit = product.price_get(pricetype.field, context)[product.id]
2119 new_std_price = ((amount_unit * product.qty_available)\
2120 + (new_price * qty))/(product.qty_available + qty)
2122 # Write the field according to price type field
2123 product_obj.write(cr, uid, [product.id],
2124 {pricetype.field: new_std_price})
2125 self.write(cr, uid, [move.id], {'price_unit': new_price})
2127 for move in too_few:
2128 product_qty = move_product_qty[move.id]
2129 if product_qty != 0:
2130 new_move = self.copy(cr, uid, move.id,
2132 'product_qty' : product_qty,
2133 'product_uos_qty': product_qty,
2134 'picking_id' : move.picking_id.id,
2135 'state': 'assigned',
2136 'move_dest_id': False,
2137 'price_unit': move.price_unit,
2139 complete.append(self.browse(cr, uid, new_move))
2140 self.write(cr, uid, move.id,
2142 'product_qty' : move.product_qty - product_qty,
2143 'product_uos_qty':move.product_qty - product_qty,
2147 for move in too_many:
2148 self.write(cr, uid, move.id,
2150 'product_qty': move.product_qty,
2151 'product_uos_qty': move.product_qty,
2153 complete.append(move)
2155 for move in complete:
2156 self.action_done(cr, uid, [move.id], context=context)
2157 if move.picking_id.id :
2158 # TOCHECK : Done picking if all moves are done
2160 SELECT move.id FROM stock_picking pick
2161 RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
2162 WHERE pick.id = %s""",
2163 ('done', move.picking_id.id))
2165 if len(res) == len(move.picking_id.move_lines):
2166 picking_obj.action_move(cr, uid, [move.picking_id.id])
2167 wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
2171 for move in complete:
2172 done_move_ids.append(move.id)
2173 return done_move_ids
2177 class stock_inventory(osv.osv):
2178 _name = "stock.inventory"
2179 _description = "Inventory"
2181 'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
2182 'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2183 'date_done': fields.datetime('Date done'),
2184 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'done': [('readonly', True)]}),
2185 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
2186 'state': fields.selection( (('draft', 'Draft'), ('done', 'Done'), ('cancel','Cancelled')), 'State', readonly=True),
2187 'company_id': fields.many2one('res.company','Company',required=True,select=1),
2190 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
2192 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
2195 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2196 """ Creates a stock move from an inventory line
2197 @param inventory_line:
2201 return self.pool.get('stock.move').create(cr, uid, move_vals)
2203 def action_done(self, cr, uid, ids, context=None):
2204 """ Finishes the inventory and writes its finished date
2209 for inv in self.browse(cr, uid, ids):
2212 for line in inv.inventory_line_id:
2213 pid = line.product_id.id
2215 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
2216 #TOCHECK: Why put restriction like new inventory qty should greater available qty ?
2217 change = line.product_qty - amount
2218 lot_id = line.prod_lot_id.id
2220 location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
2222 'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
2223 'product_id': line.product_id.id,
2224 'product_uom': line.product_uom.id,
2225 'prodlot_id': lot_id,
2227 'date_planned': inv.date,
2232 'product_qty': change,
2233 'location_id': location_id,
2234 'location_dest_id': line.location_id.id,
2238 'product_qty': -change,
2239 'location_id': line.location_id.id,
2240 'location_dest_id': location_id,
2244 'prodlot_id': lot_id,
2245 'product_qty': line.product_qty
2247 move_ids.append(self._inventory_line_hook(cr, uid, line, value))
2248 message = _('Inventory') + " '" + inv.name + "' "+ _("is done.")
2249 self.log(cr, uid, inv.id, message)
2250 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
2253 def action_cancel(self, cr, uid, ids, context=None):
2254 """ Cancels the stock move and change inventory state to draft.
2257 for inv in self.browse(cr, uid, ids):
2258 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2259 self.write(cr, uid, [inv.id], {'state': 'draft'})
2262 def action_cancel_inventary(self, cr, uid, ids, context=None):
2263 """ Cancels both stock move and inventory
2266 for inv in self.browse(cr,uid,ids):
2267 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2268 self.write(cr, uid, [inv.id], {'state':'cancel'})
2273 class stock_inventory_line(osv.osv):
2274 _name = "stock.inventory.line"
2275 _description = "Inventory Line"
2277 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2278 'location_id': fields.many2one('stock.location', 'Location', required=True),
2279 'product_id': fields.many2one('product.product', 'Product', required=True),
2280 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
2281 'product_qty': fields.float('Quantity'),
2282 'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
2283 'prod_lot_id': fields.many2one('stock.production.lot', 'Production Lot', domain="[('product_id','=',product_id)]"),
2284 'state': fields.related('inventory_id','state',type='char',string='State',readonly=True),
2287 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
2288 """ Changes UoM and name if product_id changes.
2289 @param location_id: Location id
2290 @param product: Changed product_id
2291 @param uom: UoM product
2292 @return: Dictionary of changed values
2297 prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
2298 uom = prod.uom_id.id
2299 amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
2300 result = {'product_qty': amount, 'product_uom': uom}
2301 return {'value': result}
2303 stock_inventory_line()
2305 #----------------------------------------------------------
2307 #----------------------------------------------------------
2308 class stock_warehouse(osv.osv):
2309 _name = "stock.warehouse"
2310 _description = "Warehouse"
2312 'name': fields.char('Name', size=60, required=True),
2313 'company_id': fields.many2one('res.company','Company',required=True,select=1),
2314 'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
2315 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
2316 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','<>','view')]),
2317 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
2320 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2327 # get confirm or assign stock move lines of partner and put in current picking.
2328 class stock_picking_move_wizard(osv.osv_memory):
2329 _name = 'stock.picking.move.wizard'
2331 def _get_picking(self, cr, uid, ctx=None):
2334 if ctx.get('action_id', False):
2335 return ctx['action_id']
2338 def _get_picking_address(self, cr, uid, context=None):
2339 picking_obj = self.pool.get('stock.picking')
2342 if context.get('action_id', False):
2343 picking = picking_obj.browse(cr, uid, [context['action_id']])[0]
2344 return picking.address_id and picking.address_id.id or False
2348 'name': fields.char('Name', size=64, invisible=True),
2349 'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Entry lines', required=True),
2350 'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
2351 'picking_id': fields.many2one('stock.picking', 'Picking list', select=True, invisible=True),
2354 'picking_id': _get_picking,
2355 'address_id': _get_picking_address,
2358 def action_move(self, cr, uid, ids, context=None):
2359 move_obj = self.pool.get('stock.move')
2360 picking_obj = self.pool.get('stock.picking')
2361 account_move_obj = self.pool.get('account.move')
2362 for act in self.read(cr, uid, ids):
2363 move_lines = move_obj.browse(cr, uid, act['move_ids'])
2364 for line in move_lines:
2366 picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2367 picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2368 old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
2369 if not len(old_picking['move_lines']):
2370 picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
2372 raise osv.except_osv(_('UserError'),
2373 _('You can not create new moves.'))
2374 return {'type': 'ir.actions.act_window_close'}
2376 stock_picking_move_wizard()
2378 class report_products_to_received_planned(osv.osv):
2379 _name = "report.products.to.received.planned"
2380 _description = "Product to Received Vs Planned"
2383 'date':fields.date('Date'),
2384 'qty': fields.integer('Actual Qty'),
2385 'planned_qty': fields.integer('Planned Qty'),
2389 tools.drop_view_if_exists(cr, 'report_products_to_received_planned')
2391 create or replace view report_products_to_received_planned as (
2392 select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2393 from stock_picking picking
2394 inner join stock_move stock
2395 on picking.id = stock.picking_id and picking.type = 'in'
2396 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2401 select stock.date_planned, min(stock.id) as id, 0 as actual_qty, sum(stock.product_qty) as planned_qty
2402 from stock_picking picking
2403 inner join stock_move stock
2404 on picking.id = stock.picking_id and picking.type = 'in'
2405 where stock.date_planned between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2406 group by stock.date_planned
2410 report_products_to_received_planned()
2412 class report_delivery_products_planned(osv.osv):
2413 _name = "report.delivery.products.planned"
2414 _description = "Number of Delivery products vs planned"
2417 'date':fields.date('Date'),
2418 'qty': fields.integer('Actual Qty'),
2419 'planned_qty': fields.integer('Planned Qty'),
2424 tools.drop_view_if_exists(cr, 'report_delivery_products_planned')
2426 create or replace view report_delivery_products_planned as (
2427 select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2428 from stock_picking picking
2429 inner join stock_move stock
2430 on picking.id = stock.picking_id and picking.type = 'out'
2431 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2436 select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2437 from stock_picking picking
2438 inner join stock_move stock
2439 on picking.id = stock.picking_id and picking.type = 'out'
2440 where stock.date_planned between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2441 group by stock.date_planned
2447 report_delivery_products_planned()
2449 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: