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'),
1380 'You must assign a production lot for this product',
1382 (_check_product_lot,
1383 'You try to assign a lot which is not from the same product',
1386 def _default_location_destination(self, cr, uid, context=None):
1387 """ Gets default address of partner for destination location
1388 @return: Address id or False
1390 if context.get('move_line', []):
1391 if context['move_line'][0]:
1392 if isinstance(context['move_line'][0], (tuple, list)):
1393 return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
1395 move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1396 return move_list and move_list['location_dest_id'][0] or False
1397 if context.get('address_out_id', False):
1398 property_out = self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer
1399 return property_out and property_out.id or False
1402 def _default_location_source(self, cr, uid, context=None):
1403 """ Gets default address of partner for source location
1404 @return: Address id or False
1406 if context.get('move_line', []):
1408 return context['move_line'][0][2]['location_id']
1411 if context.get('address_in_id', False):
1412 return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1416 'location_id': _default_location_source,
1417 'location_dest_id': _default_location_destination,
1422 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S'),
1423 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
1424 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1425 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
1428 def copy(self, cr, uid, id, default=None, context=None):
1431 default = default.copy()
1432 return super(stock_move, self).copy(cr, uid, id, default, context=context)
1434 def _auto_init(self, cursor, context=None):
1435 res = super(stock_move, self)._auto_init(cursor, context=context)
1436 cursor.execute('SELECT indexname \
1438 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1439 if not cursor.fetchone():
1440 cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1441 ON stock_move (location_id, location_dest_id, product_id, state)')
1444 def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
1445 loc_id=False, product_id=False, context=None):
1446 """ On change of production lot gives a warning message.
1447 @param prodlot_id: Changed production lot id
1448 @param product_qty: Quantity of product
1449 @param loc_id: Location id
1450 @param product_id: Product id
1451 @return: Warning message
1453 if not prodlot_id or not loc_id:
1455 ctx = context and context.copy() or {}
1456 ctx['location_id'] = loc_id
1457 prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1458 location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1460 if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1462 'title': 'Bad Lot Assignation !',
1463 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1465 return {'warning': warning}
1467 def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
1468 product_uom, product_uos):
1469 """ On change of product quantity finds UoM and UoS quantities
1470 @param product_id: Product id
1471 @param product_qty: Changed Quantity of product
1472 @param product_uom: Unit of measure of product
1473 @param product_uos: Unit of sale of product
1474 @return: Dictionary of values
1477 'product_uos_qty': 0.00
1480 if (not product_id) or (product_qty <=0.0):
1481 return {'value': result}
1483 product_obj = self.pool.get('product.product')
1484 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1486 if product_uos and product_uom and (product_uom != product_uos):
1487 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1489 result['product_uos_qty'] = product_qty
1491 return {'value': result}
1493 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
1494 loc_dest_id=False, address_id=False):
1495 """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1496 @param prod_id: Changed Product id
1497 @param loc_id: Source location id
1498 @param loc_id: Destination location id
1499 @param address_id: Address id of partner
1500 @return: Dictionary of values
1506 addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1508 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1509 ctx = {'lang': lang}
1511 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1512 uos_id = product.uos_id and product.uos_id.id or False
1514 'product_uom': product.uom_id.id,
1515 'product_uos': uos_id,
1516 'product_qty': 1.00,
1517 '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']
1520 result['name'] = product.partner_ref
1522 result['location_id'] = loc_id
1524 result['location_dest_id'] = loc_dest_id
1525 return {'value': result}
1527 def _chain_compute(self, cr, uid, moves, context=None):
1528 """ Finds whether the location has chained location type or not.
1529 @param moves: Stock moves
1530 @return: Dictionary containing destination location with chained location type.
1534 dest = self.pool.get('stock.location').chained_location_get(
1538 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1543 if dest[1] == 'transparent':
1544 self.write(cr, uid, [m.id], {
1545 'date_planned': (datetime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1546 relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1547 'location_dest_id': dest[0].id})
1549 result.setdefault(m.picking_id, [])
1550 result[m.picking_id].append( (m, dest) )
1553 def action_confirm(self, cr, uid, ids, context=None):
1554 """ Confirms stock move.
1555 @return: List of ids.
1557 moves = self.browse(cr, uid, ids)
1558 self.write(cr, uid, ids, {'state': 'confirmed'})
1561 def create_chained_picking(self, cr, uid, moves, context=None):
1563 res_obj = self.pool.get('res.company')
1564 picking_obj = self.pool.get('stock.picking')
1565 move_obj = self.pool.get('stock.move')
1568 for picking, todo in self._chain_compute(cr, uid, moves, context=context).items():
1569 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])
1570 pick_name = picking.name
1571 if ptype == 'delivery':
1572 pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.delivery')
1574 pickid = picking_obj.create(cr, uid, {
1576 'origin': str(picking.origin or ''),
1578 'note': picking.note,
1579 'move_type': picking.move_type,
1580 'auto_picking': todo[0][1][1] == 'auto',
1581 'stock_journal_id': todo[0][1][3],
1582 'company_id': todo[0][1][4] or res_obj._company_default_get(cr, uid, 'stock.company', context),
1583 'address_id': picking.address_id.id,
1584 'invoice_state': 'none',
1585 'date': picking.date,
1586 'sale_id':' sale_id' in picking._columns.keys() and picking.sale_id.id or False
1588 for move, (loc, auto, delay, journal, company_id, ptype) in todo:
1589 new_id = move_obj.copy(cr, uid, move.id, {
1590 'location_id': move.location_dest_id.id,
1591 'location_dest_id': loc.id,
1592 'date_moved': time.strftime('%Y-%m-%d'),
1593 'picking_id': pickid,
1595 'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context) ,
1596 'move_history_ids': [],
1597 'date_planned': (datetime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
1598 'move_history_ids2': []}
1600 move_obj.write(cr, uid, [move.id], {
1601 'move_dest_id': new_id,
1602 'move_history_ids': [(4, new_id)]
1604 new_moves.append(self.browse(cr, uid, [new_id])[0])
1605 wf_service = netsvc.LocalService("workflow")
1606 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1608 create_chained_picking(self, cr, uid, new_moves, context)
1609 create_chained_picking(self, cr, uid, moves, context)
1612 def action_assign(self, cr, uid, ids, *args):
1613 """ Changes state to confirmed or waiting.
1614 @return: List of values
1617 for move in self.browse(cr, uid, ids):
1618 if move.state in ('confirmed', 'waiting'):
1619 todo.append(move.id)
1620 res = self.check_assign(cr, uid, todo)
1623 def force_assign(self, cr, uid, ids, context={}):
1624 """ Changes the state to assigned.
1627 self.write(cr, uid, ids, {'state': 'assigned'})
1630 def cancel_assign(self, cr, uid, ids, context={}):
1631 """ Changes the state to confirmed.
1634 self.write(cr, uid, ids, {'state': 'confirmed'})
1638 # Duplicate stock.move
1640 def check_assign(self, cr, uid, ids, context=None):
1641 """ Checks the product type and accordingly writes the state.
1642 @return: No. of moves done
1649 for move in self.browse(cr, uid, ids, context=context):
1650 if move.product_id.type == 'consu':
1651 if move.state in ('confirmed', 'waiting'):
1652 done.append(move.id)
1653 pickings[move.picking_id.id] = 1
1655 if move.state in ('confirmed', 'waiting'):
1656 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})
1658 #_product_available_test depends on the next status for correct functioning
1659 #the test does not work correctly if the same product occurs multiple times
1660 #in the same order. This is e.g. the case when using the button 'split in two' of
1661 #the stock outgoing form
1662 self.write(cr, uid, move.id, {'state':'assigned'})
1663 done.append(move.id)
1664 pickings[move.picking_id.id] = 1
1666 cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1670 move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1671 done.append(move_id)
1674 self.write(cr, uid, done, {'state': 'assigned'})
1677 for pick_id in pickings:
1678 wf_service = netsvc.LocalService("workflow")
1679 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1682 def setlast_tracking(self, cr, uid, ids, context=None):
1683 tracking_obj = self.pool.get('stock.tracking')
1684 tracking = context.get('tracking', False)
1685 last_track = [line.tracking_id.id for line in self.browse(cr, uid, ids)[0].picking_id.move_lines if line.tracking_id]
1687 last_track = tracking_obj.create(cr, uid, {}, context=context)
1690 last_track = last_track[-1]
1691 self.write(cr, uid, ids, {'tracking_id': last_track})
1695 # Cancel move => cancel others move and pickings
1697 def action_cancel(self, cr, uid, ids, context=None):
1698 """ Cancels the moves and if all moves are cancelled it cancels the picking.
1706 for move in self.browse(cr, uid, ids):
1707 if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1709 pickings[move.picking_id.id] = True
1710 if move.move_dest_id and move.move_dest_id.state == 'waiting':
1711 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1712 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1713 wf_service = netsvc.LocalService("workflow")
1714 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1715 self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1716 if not context.get('call_unlink',False):
1717 for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1718 if all(move.state == 'cancel' for move in pick.move_lines):
1719 self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1721 wf_service = netsvc.LocalService("workflow")
1723 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1726 def _get_accounting_values(self, cr, uid, move, context=None):
1727 product_obj=self.pool.get('product.product')
1728 product_uom_obj = self.pool.get('product.uom')
1729 price_type_obj = self.pool.get('product.price.type')
1730 accounts = product_obj.get_product_accounts(cr,uid,move.product_id.id,context)
1731 acc_src = accounts['stock_account_input']
1732 acc_dest = accounts['stock_account_output']
1733 acc_variation = accounts.get('property_stock_variation', False)
1734 journal_id = accounts['stock_journal']
1740 raise osv.except_osv(_('Error!'), _('There is no stock input account defined ' \
1741 'for this product: "%s" (id: %d)') % \
1742 (move.product_id.name, move.product_id.id,))
1744 raise osv.except_osv(_('Error!'), _('There is no stock output account defined ' \
1745 'for this product: "%s" (id: %d)') % \
1746 (move.product_id.name, move.product_id.id,))
1748 raise osv.except_osv(_('Error!'), _('There is no journal defined '\
1749 'on the product category: "%s" (id: %d)') % \
1750 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1751 if not acc_variation:
1752 raise osv.except_osv(_('Error!'), _('There is no variation account defined '\
1753 'on the product category: "%s" (id: %d)') % \
1754 (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1755 if acc_src != acc_dest:
1756 default_uom = move.product_id.uom_id.id
1757 q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1758 if move.product_id.cost_method == 'average' and move.price_unit:
1759 amount = q * move.price_unit
1760 # Base computation on valuation price type
1762 company_id = move.company_id.id
1763 context['currency_id'] = move.company_id.currency_id.id
1764 pricetype = price_type_obj.browse(cr,uid,move.company_id.property_valuation_price_type.id)
1765 amount_unit = move.product_id.price_get(pricetype.field, context)[move.product_id.id]
1766 amount = amount_unit * q or 1.0
1767 return journal_id, acc_src, acc_dest, acc_variation, amount
1769 def action_done(self, cr, uid, ids, context=None):
1770 """ Makes the move done and if all moves are done, it will finish the picking.
1775 product_uom_obj = self.pool.get('product.uom')
1776 price_type_obj = self.pool.get('product.price.type')
1777 product_obj = self.pool.get('product.product')
1778 move_obj = self.pool.get('account.move')
1781 for move in self.browse(cr, uid, ids):
1783 picking_ids.append(move.picking_id.id)
1784 if move.move_dest_id.id and (move.state != 'done'):
1785 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1786 if move.move_dest_id.state in ('waiting', 'confirmed'):
1787 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1788 if move.move_dest_id.picking_id:
1789 wf_service = netsvc.LocalService("workflow")
1790 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1793 if move.move_dest_id.auto_validate:
1794 self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1797 # Accounting Entries
1801 if move.product_id.valuation == 'real_time':
1803 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')):
1804 if move.location_id.company_id:
1805 context.update({'force_company': move.location_id.company_id.id})
1806 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1807 lines = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1809 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')):
1810 if move.location_dest_id.company_id:
1811 context.update({'force_company': move.location_dest_id.company_id.id})
1812 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1813 lines = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1814 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):
1815 if move.location_id.company_id:
1816 context.update({'force_company': move.location_id.company_id.id})
1817 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1818 line1 = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1819 if move.location_dest_id.company_id:
1820 context.update({'force_company': move.location_dest_id.company_id.id})
1821 journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1822 line2 = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1823 lines = line1 + line2
1824 for j_id, line in lines:
1825 move_obj.create(cr, uid, {
1828 'type':'cont_voucher',
1830 'ref': move.picking_id and move.picking_id.name,
1833 self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1834 wf_service = netsvc.LocalService("workflow")
1836 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1838 picking_obj = self.pool.get('stock.picking')
1839 wf_service = netsvc.LocalService("workflow")
1840 for pick_id in picking_ids:
1841 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1843 picking_obj.log_picking(cr, uid, picking_ids, context=context)
1846 def create_account_move(self, cr, uid, move,account_id, account_variation, amount, context=None):
1849 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
1852 'quantity': move.product_qty,
1853 'product_id': move.product_id and move.product_id.id or False,
1855 'account_id': account_id,
1856 'ref': move.picking_id and move.picking_id.name or False,
1857 'date': time.strftime('%Y-%m-%d') ,
1858 'partner_id': partner_id,
1862 'product_id': move.product_id and move.product_id.id or False,
1863 'quantity': move.product_qty,
1865 'account_id': account_variation,
1866 'ref': move.picking_id and move.picking_id.name or False,
1867 'date': time.strftime('%Y-%m-%d') ,
1868 'partner_id': partner_id,
1872 def unlink(self, cr, uid, ids, context=None):
1875 for move in self.browse(cr, uid, ids, context=context):
1876 if move.state != 'draft':
1877 raise osv.except_osv(_('UserError'),
1878 _('You can only delete draft moves.'))
1879 return super(stock_move, self).unlink(
1880 cr, uid, ids, context=context)
1882 def _create_lot(self, cr, uid, ids, product_id, prefix=False):
1883 """ Creates production lot
1884 @return: Production lot id
1886 prodlot_obj = self.pool.get('stock.production.lot')
1887 prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
1890 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1891 """ Move the scrap/damaged product into scrap location
1892 @param cr: the database cursor
1893 @param uid: the user id
1894 @param ids: ids of stock move object to be scraped
1895 @param quantity : specify scrap qty
1896 @param location_id : specify scrap location
1897 @param context: context arguments
1898 @return: Scraped lines
1901 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1903 for move in self.browse(cr, uid, ids, context=context):
1904 move_qty = move.product_qty
1905 uos_qty = quantity / move_qty * move.product_uos_qty
1907 'product_qty': quantity,
1908 'product_uos_qty': uos_qty,
1909 'state': move.state,
1911 'location_dest_id': location_id
1913 new_move = self.copy(cr, uid, move.id, default_val)
1915 product_obj = self.pool.get('product.product')
1916 for (id, name) in product_obj.name_get(cr, uid, [move.product_id.id]):
1917 message = _('Product ') + " '" + name + "' "+ _("is scraped with") + " '" + str(move.product_qty) + "' "+ _("quantity.")
1918 self.log(cr, uid, move.id, message)
1920 self.action_done(cr, uid, res)
1923 def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
1924 """ Split Stock Move lines into production lot which specified split by quantity.
1925 @param cr: the database cursor
1926 @param uid: the user id
1927 @param ids: ids of stock move object to be splited
1928 @param split_by_qty : specify split by qty
1929 @param prefix : specify prefix of production lot
1930 @param with_lot : if true, prodcution lot will assign for split line otherwise not.
1931 @param context: context arguments
1932 @return: Splited move lines
1938 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1942 for move in self.browse(cr, uid, ids):
1943 if split_by_qty <= 0 or quantity == 0:
1946 uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
1948 quantity_rest = quantity % split_by_qty
1949 uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
1952 'product_qty': split_by_qty,
1953 'product_uos_qty': uos_qty,
1955 for idx in range(int(quantity//split_by_qty)):
1956 if not idx and move.product_qty<=quantity:
1957 current_move = move.id
1959 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1960 res.append(current_move)
1962 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1964 self.write(cr, uid, [current_move], update_val)
1967 if quantity_rest > 0:
1968 idx = int(quantity//split_by_qty)
1969 update_val['product_qty'] = quantity_rest
1970 update_val['product_uos_qty'] = uos_qty_rest
1971 if not idx and move.product_qty<=quantity:
1972 current_move = move.id
1974 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1976 res.append(current_move)
1980 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1982 self.write(cr, uid, [current_move], update_val)
1985 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
1986 """ Consumed product with specific quatity from specific source location
1987 @param cr: the database cursor
1988 @param uid: the user id
1989 @param ids: ids of stock move object to be consumed
1990 @param quantity : specify consume quantity
1991 @param location_id : specify source location
1992 @param context: context arguments
1993 @return: Consumed lines
1998 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
2001 for move in self.browse(cr, uid, ids, context=context):
2002 move_qty = move.product_qty
2003 quantity_rest = move.product_qty
2005 quantity_rest -= quantity
2006 uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
2007 if quantity_rest <= 0:
2010 quantity = move.product_qty
2012 uos_qty = quantity / move_qty * move.product_uos_qty
2014 if quantity_rest > 0:
2016 'product_qty': quantity,
2017 'product_uos_qty': uos_qty,
2018 'state': move.state,
2019 'location_id': location_id
2021 if move.product_id.track_production and location_id:
2022 # IF product has checked track for production lot, move lines will be split by 1
2023 res += self.action_split(cr, uid, [move.id], quantity, split_by_qty=1, context=context)
2025 current_move = self.copy(cr, uid, move.id, default_val)
2026 res += [current_move]
2028 update_val['product_qty'] = quantity_rest
2029 update_val['product_uos_qty'] = uos_qty_rest
2030 self.write(cr, uid, [move.id], update_val)
2033 quantity_rest = quantity
2034 uos_qty_rest = uos_qty
2035 if move.product_id.track_production and location_id:
2036 res += self.split_lines(cr, uid, [move.id], quantity_rest, split_by_qty=1, context=context)
2040 'product_qty' : quantity_rest,
2041 'product_uos_qty' : uos_qty_rest,
2042 'location_id': location_id
2045 self.write(cr, uid, [move.id], update_val)
2047 product_obj = self.pool.get('product.product')
2048 for new_move in self.browse(cr, uid, res, context=context):
2049 for (id, name) in product_obj.name_get(cr, uid, [new_move.product_id.id]):
2050 message = _('Product ') + " '" + name + "' "+ _("is consumed with") + " '" + str(new_move.product_qty) + "' "+ _("quantity.")
2051 self.log(cr, uid, new_move.id, message)
2052 self.action_done(cr, uid, res)
2056 def do_partial(self, cr, uid, ids, partial_datas, context=None):
2057 """ Makes partial pickings and moves done.
2058 @param partial_datas: Dictionary containing details of partial picking
2059 like partner_id, address_id, delivery_date, delivery
2060 moves with product_id, product_qty, uom
2063 picking_obj = self.pool.get('stock.picking')
2064 product_obj = self.pool.get('product.product')
2065 currency_obj = self.pool.get('res.currency')
2066 users_obj = self.pool.get('res.users')
2067 uom_obj = self.pool.get('product.uom')
2068 price_type_obj = self.pool.get('product.price.type')
2069 sequence_obj = self.pool.get('ir.sequence')
2070 wf_service = netsvc.LocalService("workflow")
2071 partner_id = partial_datas.get('partner_id', False)
2072 address_id = partial_datas.get('address_id', False)
2073 delivery_date = partial_datas.get('delivery_date', False)
2079 complete, too_many, too_few = [], [], []
2080 move_product_qty = {}
2081 for move in self.browse(cr, uid, ids, context=context):
2082 if move.state in ('done', 'cancel'):
2084 partial_data = partial_datas.get('move%s'%(move.id), False)
2085 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
2086 product_qty = partial_data.get('product_qty',0.0)
2087 move_product_qty[move.id] = product_qty
2088 product_uom = partial_data.get('product_uom',False)
2089 product_price = partial_data.get('product_price',0.0)
2090 product_currency = partial_data.get('product_currency',False)
2091 if move.product_qty == product_qty:
2092 complete.append(move)
2093 elif move.product_qty > product_qty:
2094 too_few.append(move)
2096 too_many.append(move)
2098 # Average price computation
2099 if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
2100 product = product_obj.browse(cr, uid, move.product_id.id)
2101 user = users_obj.browse(cr, uid, uid)
2102 context['currency_id'] = move.company_id.currency_id.id
2103 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
2105 if user.company_id.property_valuation_price_type:
2106 pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
2107 if pricetype and qty > 0:
2108 new_price = currency_obj.compute(cr, uid, product_currency,
2109 user.company_id.currency_id.id, product_price)
2110 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
2112 if product.qty_available <= 0:
2113 new_std_price = new_price
2115 # Get the standard price
2116 amount_unit = product.price_get(pricetype.field, context)[product.id]
2117 new_std_price = ((amount_unit * product.qty_available)\
2118 + (new_price * qty))/(product.qty_available + qty)
2120 # Write the field according to price type field
2121 product_obj.write(cr, uid, [product.id],
2122 {pricetype.field: new_std_price})
2123 self.write(cr, uid, [move.id], {'price_unit': new_price})
2125 for move in too_few:
2126 product_qty = move_product_qty[move.id]
2127 if product_qty != 0:
2128 new_move = self.copy(cr, uid, move.id,
2130 'product_qty' : product_qty,
2131 'product_uos_qty': product_qty,
2132 'picking_id' : move.picking_id.id,
2133 'state': 'assigned',
2134 'move_dest_id': False,
2135 'price_unit': move.price_unit,
2137 complete.append(self.browse(cr, uid, new_move))
2138 self.write(cr, uid, move.id,
2140 'product_qty' : move.product_qty - product_qty,
2141 'product_uos_qty':move.product_qty - product_qty,
2145 for move in too_many:
2146 self.write(cr, uid, move.id,
2148 'product_qty': move.product_qty,
2149 'product_uos_qty': move.product_qty,
2151 complete.append(move)
2153 for move in complete:
2154 self.action_done(cr, uid, [move.id], context=context)
2155 if move.picking_id.id :
2156 # TOCHECK : Done picking if all moves are done
2158 SELECT move.id FROM stock_picking pick
2159 RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
2160 WHERE pick.id = %s""",
2161 ('done', move.picking_id.id))
2163 if len(res) == len(move.picking_id.move_lines):
2164 picking_obj.action_move(cr, uid, [move.picking_id.id])
2165 wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
2169 for move in complete:
2170 done_move_ids.append(move.id)
2171 return done_move_ids
2175 class stock_inventory(osv.osv):
2176 _name = "stock.inventory"
2177 _description = "Inventory"
2179 'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
2180 'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2181 'date_done': fields.datetime('Date done'),
2182 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'done': [('readonly', True)]}),
2183 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
2184 'state': fields.selection( (('draft', 'Draft'), ('done', 'Done'), ('cancel','Cancelled')), 'State', readonly=True),
2185 'company_id': fields.many2one('res.company','Company',required=True,select=1),
2188 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
2190 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
2193 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2194 """ Creates a stock move from an inventory line
2195 @param inventory_line:
2199 return self.pool.get('stock.move').create(cr, uid, move_vals)
2201 def action_done(self, cr, uid, ids, context=None):
2202 """ Finishes the inventory and writes its finished date
2207 for inv in self.browse(cr, uid, ids):
2210 for line in inv.inventory_line_id:
2211 pid = line.product_id.id
2213 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
2214 #TOCHECK: Why put restriction like new inventory qty should greater available qty ?
2215 change = line.product_qty - amount
2216 lot_id = line.prod_lot_id.id
2218 location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
2220 'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
2221 'product_id': line.product_id.id,
2222 'product_uom': line.product_uom.id,
2223 'prodlot_id': lot_id,
2225 'date_planned': inv.date,
2230 'product_qty': change,
2231 'location_id': location_id,
2232 'location_dest_id': line.location_id.id,
2236 'product_qty': -change,
2237 'location_id': line.location_id.id,
2238 'location_dest_id': location_id,
2242 'prodlot_id': lot_id,
2243 'product_qty': line.product_qty
2245 move_ids.append(self._inventory_line_hook(cr, uid, line, value))
2246 message = _('Inventory') + " '" + inv.name + "' "+ _("is done.")
2247 self.log(cr, uid, inv.id, message)
2248 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
2251 def action_cancel(self, cr, uid, ids, context=None):
2252 """ Cancels the stock move and change inventory state to draft.
2255 for inv in self.browse(cr, uid, ids):
2256 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2257 self.write(cr, uid, [inv.id], {'state': 'draft'})
2260 def action_cancel_inventary(self, cr, uid, ids, context=None):
2261 """ Cancels both stock move and inventory
2264 for inv in self.browse(cr,uid,ids):
2265 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2266 self.write(cr, uid, [inv.id], {'state':'cancel'})
2271 class stock_inventory_line(osv.osv):
2272 _name = "stock.inventory.line"
2273 _description = "Inventory Line"
2275 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2276 'location_id': fields.many2one('stock.location', 'Location', required=True),
2277 'product_id': fields.many2one('product.product', 'Product', required=True),
2278 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
2279 'product_qty': fields.float('Quantity'),
2280 'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
2281 'prod_lot_id': fields.many2one('stock.production.lot', 'Production Lot', domain="[('product_id','=',product_id)]"),
2282 'state': fields.related('inventory_id','state',type='char',string='State',readonly=True),
2285 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
2286 """ Changes UoM and name if product_id changes.
2287 @param location_id: Location id
2288 @param product: Changed product_id
2289 @param uom: UoM product
2290 @return: Dictionary of changed values
2295 prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
2296 uom = prod.uom_id.id
2297 amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
2298 result = {'product_qty': amount, 'product_uom': uom}
2299 return {'value': result}
2301 stock_inventory_line()
2303 #----------------------------------------------------------
2305 #----------------------------------------------------------
2306 class stock_warehouse(osv.osv):
2307 _name = "stock.warehouse"
2308 _description = "Warehouse"
2310 'name': fields.char('Name', size=60, required=True),
2311 'company_id': fields.many2one('res.company','Company',required=True,select=1),
2312 'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
2313 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
2314 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','<>','view')]),
2315 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
2318 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2325 # get confirm or assign stock move lines of partner and put in current picking.
2326 class stock_picking_move_wizard(osv.osv_memory):
2327 _name = 'stock.picking.move.wizard'
2329 def _get_picking(self, cr, uid, ctx=None):
2332 if ctx.get('action_id', False):
2333 return ctx['action_id']
2336 def _get_picking_address(self, cr, uid, context=None):
2337 picking_obj = self.pool.get('stock.picking')
2340 if context.get('action_id', False):
2341 picking = picking_obj.browse(cr, uid, [context['action_id']])[0]
2342 return picking.address_id and picking.address_id.id or False
2346 'name': fields.char('Name', size=64, invisible=True),
2347 'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Entry lines', required=True),
2348 'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
2349 'picking_id': fields.many2one('stock.picking', 'Picking list', select=True, invisible=True),
2352 'picking_id': _get_picking,
2353 'address_id': _get_picking_address,
2356 def action_move(self, cr, uid, ids, context=None):
2357 move_obj = self.pool.get('stock.move')
2358 picking_obj = self.pool.get('stock.picking')
2359 account_move_obj = self.pool.get('account.move')
2360 for act in self.read(cr, uid, ids):
2361 move_lines = move_obj.browse(cr, uid, act['move_ids'])
2362 for line in move_lines:
2364 picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2365 picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2366 old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
2367 if not len(old_picking['move_lines']):
2368 picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
2370 raise osv.except_osv(_('UserError'),
2371 _('You can not create new moves.'))
2372 return {'type': 'ir.actions.act_window_close'}
2374 stock_picking_move_wizard()
2376 class report_products_to_received_planned(osv.osv):
2377 _name = "report.products.to.received.planned"
2378 _description = "Product to Received Vs Planned"
2381 'date':fields.date('Date'),
2382 'qty': fields.integer('Actual Qty'),
2383 'planned_qty': fields.integer('Planned Qty'),
2387 tools.drop_view_if_exists(cr, 'report_products_to_received_planned')
2389 create or replace view report_products_to_received_planned as (
2390 select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2391 from stock_picking picking
2392 inner join stock_move stock
2393 on picking.id = stock.picking_id and picking.type = 'in'
2394 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2399 select stock.date_planned, min(stock.id) as id, 0 as actual_qty, sum(stock.product_qty) as planned_qty
2400 from stock_picking picking
2401 inner join stock_move stock
2402 on picking.id = stock.picking_id and picking.type = 'in'
2403 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)
2404 group by stock.date_planned
2408 report_products_to_received_planned()
2410 class report_delivery_products_planned(osv.osv):
2411 _name = "report.delivery.products.planned"
2412 _description = "Number of Delivery products vs planned"
2415 'date':fields.date('Date'),
2416 'qty': fields.integer('Actual Qty'),
2417 'planned_qty': fields.integer('Planned Qty'),
2422 tools.drop_view_if_exists(cr, 'report_delivery_products_planned')
2424 create or replace view report_delivery_products_planned as (
2425 select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2426 from stock_picking picking
2427 inner join stock_move stock
2428 on picking.id = stock.picking_id and picking.type = 'out'
2429 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2434 select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2435 from stock_picking picking
2436 inner join stock_move stock
2437 on picking.id = stock.picking_id and picking.type = 'out'
2438 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)
2439 group by stock.date_planned
2445 report_delivery_products_planned()
2447 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: