1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import datetime
23 from dateutil.relativedelta import relativedelta
25 from osv import fields, osv
26 from tools import config
27 from tools.translate import _
33 import decimal_precision as dp
36 #----------------------------------------------------------
38 #----------------------------------------------------------
39 class stock_incoterms(osv.osv):
40 _name = "stock.incoterms"
41 _description = "Incoterms"
43 '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."),
44 'code': fields.char('Code', size=3, required=True,help="Code for Incoterms"),
45 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the incoterms without removing it."),
48 'active': lambda *a: True,
54 #----------------------------------------------------------
56 #----------------------------------------------------------
57 class stock_location(osv.osv):
58 _name = "stock.location"
59 _description = "Location"
60 _parent_name = "location_id"
63 _order = 'parent_left'
65 def name_get(self, cr, uid, ids, context={}):
68 reads = self.read(cr, uid, ids, ['name','location_id'], context)
72 if context.get('full',False):
73 if record['location_id']:
74 name = record['location_id'][1]+' / '+name
75 res.append((record['id'], name))
77 res.append((record['id'], name))
80 def _complete_name(self, cr, uid, ids, name, args, context):
81 def _get_one_full_name(location, level=4):
82 if location.location_id:
83 parent_path = _get_one_full_name(location.location_id, level-1) + "/"
86 return parent_path + location.name
88 for m in self.browse(cr, uid, ids, context=context):
89 res[m.id] = _get_one_full_name(m)
92 def _product_qty_available(self, cr, uid, ids, field_names, arg, context={}):
95 res[id] = {}.fromkeys(field_names, 0.0)
96 if ('product_id' not in context) or not ids:
98 #location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
100 context['location'] = [loc]
101 prod = self.pool.get('product.product').browse(cr, uid, context['product_id'], context)
102 if 'stock_real' in field_names:
103 res[loc]['stock_real'] = prod.qty_available
104 if 'stock_virtual' in field_names:
105 res[loc]['stock_virtual'] = prod.virtual_available
108 def product_detail(self, cr, uid, id, field, context={}):
112 field_to_read = 'virtual_available'
113 if field == 'stock_real_value':
114 field_to_read = 'qty_available'
115 cr.execute('select distinct product_id from stock_move where (location_id=%s) or (location_dest_id=%s)', (id, id))
116 result = cr.dictfetchall()
118 # Choose the right filed standard_price to read
119 # Take the user company
120 price_type_id=self.pool.get('res.users').browse(cr,uid,uid).company_id.property_valuation_price_type.id
121 pricetype=self.pool.get('product.price.type').browse(cr,uid,price_type_id)
123 c = (context or {}).copy()
125 product = self.pool.get('product.product').read(cr, uid, r['product_id'], [field_to_read], context=c)
126 # Compute the amount_unit in right currency
128 context['currency_id']=self.pool.get('res.users').browse(cr,uid,uid).company_id.currency_id.id
129 amount_unit=self.pool.get('product.product').browse(cr,uid,r['product_id']).price_get(pricetype.field, context)[r['product_id']]
131 final_value += (product[field_to_read] * amount_unit)
134 def _product_value(self, cr, uid, ids, field_names, arg, context={}):
137 result[id] = {}.fromkeys(field_names, 0.0)
138 for field_name in field_names:
140 ret_dict = self.product_detail(cr, uid, loc, field=field_name)
141 result[loc][field_name] = ret_dict
145 'name': fields.char('Location Name', size=64, required=True, translate=True),
146 '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."),
147 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production')], 'Location Type', required=True),
148 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
150 'complete_name': fields.function(_complete_name, method=True, type='char', size=100, string="Location Name"),
152 'stock_real': fields.function(_product_qty_available, method=True, type='float', string='Real Stock', multi="stock"),
153 'stock_virtual': fields.function(_product_qty_available, method=True, type='float', string='Virtual Stock', multi="stock"),
155 'account_id': fields.many2one('account.account', string='Inventory Account', domain=[('type', '!=', 'view')]),
156 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
157 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
159 'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
160 'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
161 'Chained Location Type', required=True),
162 'chained_auto_packing': fields.selection(
163 [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
166 help="This is used only if you select a chained location type.\n" \
167 "The 'Automatic Move' value will create a stock move after the current one that will be "\
168 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
169 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
171 'chained_delay': fields.integer('Chained lead time (days)'),
172 'address_id': fields.many2one('res.partner.address', 'Location Address'),
173 'icon': fields.selection(tools.icons, 'Icon', size=64),
175 'comment': fields.text('Additional Information'),
176 'posx': fields.integer('Corridor (X)'),
177 'posy': fields.integer('Shelves (Y)'),
178 'posz': fields.integer('Height (Z)'),
180 'parent_left': fields.integer('Left Parent', select=1),
181 'parent_right': fields.integer('Right Parent', select=1),
182 'stock_real_value': fields.function(_product_value, method=True, type='float', string='Real Stock Value', multi="stock"),
183 'stock_virtual_value': fields.function(_product_value, method=True, type='float', string='Virtual Stock Value', multi="stock"),
184 'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
187 'active': lambda *a: 1,
188 'usage': lambda *a: 'internal',
189 'allocation_method': lambda *a: 'fifo',
190 'chained_location_type': lambda *a: 'none',
191 'chained_auto_packing': lambda *a: 'manual',
192 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
193 'posx': lambda *a: 0,
194 'posy': lambda *a: 0,
195 'posz': lambda *a: 0,
196 'icon': lambda *a: False,
199 def chained_location_get(self, cr, uid, location, partner=None, product=None, context={}):
201 if location.chained_location_type == 'customer':
203 result = partner.property_stock_customer
204 elif location.chained_location_type == 'fixed':
205 result = location.chained_location_id
207 return result, location.chained_auto_packing, location.chained_delay
210 def picking_type_get(self, cr, uid, from_location, to_location, context={}):
212 if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
214 elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage=='internal'):
218 def _product_get_all_report(self, cr, uid, ids, product_ids=False,
220 return self._product_get_report(cr, uid, ids, product_ids, context,
223 def _product_get_report(self, cr, uid, ids, product_ids=False,
224 context=None, recursive=False):
227 product_obj = self.pool.get('product.product')
228 # Take the user company and pricetype
229 price_type_id=self.pool.get('res.users').browse(cr,uid,uid).company_id.property_valuation_price_type.id
230 pricetype=self.pool.get('product.price.type').browse(cr,uid,price_type_id)
231 context['currency_id']=self.pool.get('res.users').browse(cr,uid,uid).company_id.currency_id.id
234 product_ids = product_obj.search(cr, uid, [])
236 products = product_obj.browse(cr, uid, product_ids, context=context)
239 for product in products:
240 products_by_uom.setdefault(product.uom_id.id, [])
241 products_by_uom[product.uom_id.id].append(product)
242 products_by_id.setdefault(product.id, [])
243 products_by_id[product.id] = product
246 result['product'] = []
250 for uom_id in products_by_uom.keys():
251 fnc = self._product_get
253 fnc = self._product_all_get
256 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
258 for product_id in qty.keys():
259 if not qty[product_id]:
261 product = products_by_id[product_id]
262 quantity_total += qty[product_id]
264 # Compute based on pricetype
265 # Choose the right filed standard_price to read
266 amount_unit=product.price_get(pricetype.field, context)[product.id]
267 price = qty[product_id] * amount_unit
268 # price = qty[product_id] * product.standard_price
271 result['product'].append({
272 'price': amount_unit,
273 'prod_name': product.name,
274 'code': product.default_code, # used by lot_overview_all report!
275 'variants': product.variants or '',
276 'uom': product.uom_id.name,
277 'prod_qty': qty[product_id],
278 'price_value': price,
280 result['total'] = quantity_total
281 result['total_price'] = total_price
284 def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context={}, states=['done'], what=('in', 'out')):
285 product_obj = self.pool.get('product.product')
291 return product_obj.get_product_available(cr, uid, product_ids, context=context)
293 def _product_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
294 ids = id and [id] or []
295 return self._product_get_multi_location(cr, uid, ids, product_ids, context, states)
297 def _product_all_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
298 # build the list of ids of children of the location given by id
299 ids = id and [id] or []
300 location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
301 return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
303 def _product_virtual_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
304 return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
308 # Improve this function
311 # [ (tracking_id, product_qty, location_id) ]
313 def _product_reserve(self, cr, uid, ids, product_id, product_qty, context={}):
316 for id in self.search(cr, uid, [('location_id', 'child_of', ids)]):
317 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))
318 results = cr.dictfetchall()
319 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))
320 results += cr.dictfetchall()
325 amount = self.pool.get('product.uom')._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
334 if amount > min(total, product_qty):
335 amount = min(product_qty, total)
336 result.append((amount, id))
337 product_qty -= amount
339 if product_qty <= 0.0:
348 class stock_tracking(osv.osv):
349 _name = "stock.tracking"
350 _description = "Stock Tracking Lots"
353 salt = '31' * 8 + '3'
355 for sscc_part, salt_part in zip(sscc, salt):
356 sum += int(sscc_part) * int(salt_part)
357 return (10 - (sum % 10)) % 10
358 checksum = staticmethod(checksum)
360 def make_sscc(self, cr, uid, context={}):
361 sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
362 return sequence + str(self.checksum(sequence))
365 'name': fields.char('Tracking ID', size=64, required=True),
366 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the tracking lots without removing it."),
367 'serial': fields.char('Reference', size=64),
368 'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves Tracked'),
369 'date': fields.datetime('Created Date', required=True),
372 'active': lambda *a: 1,
374 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
377 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
382 ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
383 ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
384 return self.name_get(cr, user, ids, context)
386 def name_get(self, cr, uid, ids, context={}):
389 res = [(r['id'], r['name']+' ['+(r['serial'] or '')+']') for r in self.read(cr, uid, ids, ['name', 'serial'], context)]
392 def unlink(self, cr, uid, ids, context=None):
393 raise osv.except_osv(_('Error'), _('You can not remove a lot line !'))
398 #----------------------------------------------------------
400 #----------------------------------------------------------
401 class stock_picking(osv.osv):
402 _name = "stock.picking"
403 _description = "Picking List"
405 def _set_maximum_date(self, cr, uid, ids, name, value, arg, context):
408 if isinstance(ids, (int, long)):
410 for pick in self.browse(cr, uid, ids, context):
411 sql_str = """update stock_move set
414 picking_id=%d """ % (value, pick.id)
417 sql_str += " and (date_planned='" + pick.max_date + "' or date_planned>'" + value + "')"
421 def _set_minimum_date(self, cr, uid, ids, name, value, arg, context):
424 if isinstance(ids, (int, long)):
426 for pick in self.browse(cr, uid, ids, context):
427 sql_str = """update stock_move set
430 picking_id=%s """ % (value, pick.id)
432 sql_str += " and (date_planned='" + pick.min_date + "' or date_planned<'" + value + "')"
436 def get_min_max_date(self, cr, uid, ids, field_name, arg, context={}):
439 res[id] = {'min_date': False, 'max_date': False}
451 picking_id""",(ids,))
452 for pick, dt1, dt2 in cr.fetchall():
453 res[pick]['min_date'] = dt1
454 res[pick]['max_date'] = dt2
457 def create(self, cr, user, vals, context=None):
458 if ('name' not in vals) or (vals.get('name')=='/'):
459 vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking')
461 return super(stock_picking, self).create(cr, user, vals, context)
464 'name': fields.char('Reference', size=64, select=True),
465 'origin': fields.char('Origin', size=64, help="Reference of the document that produced this picking."),
466 '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."),
467 '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."),
468 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the picking without removing it."),
469 'note': fields.text('Notes'),
471 'location_id': fields.many2one('stock.location', 'Location', help="Keep empty if you produce at the location where the finished products are needed." \
472 "Set a location if you produce at a fixed location. This can be a partner location " \
473 "if you subcontract the manufacturing operations."),
474 'location_dest_id': fields.many2one('stock.location', 'Dest. Location',help="Location where the system will stock the finished products."),
475 '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"),
476 'state': fields.selection([
479 ('confirmed', 'Confirmed'),
480 ('assigned', 'Available'),
482 ('cancel', 'Cancelled'),
483 ], 'State', readonly=True, select=True,
484 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed picking. \
485 \n* The \'Confirmed\' state is used for stock movement to do with unavailable products. \
486 \n* The \'Available\' state is set automatically when the products are ready to be moved.\
487 \n* The \'Waiting\' state is used in MTO moves when a movement is waiting for another one.'),
488 'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
489 method=True, store=True, type='datetime', string='Expected Date', select=1, help="Expected date for Picking. Default it takes current date"),
490 'date': fields.datetime('Order Date', help="Date of Order"),
491 'date_done': fields.datetime('Date Done', help="Date of completion"),
492 'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
493 method=True, store=True, type='datetime', string='Max. Expected Date', select=2),
494 'move_lines': fields.one2many('stock.move', 'picking_id', 'Entry lines', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
495 'delivery_line':fields.one2many('stock.delivery', 'picking_id', 'Delivery lines', readonly=True),
496 'auto_picking': fields.boolean('Auto-Picking'),
497 'address_id': fields.many2one('res.partner.address', 'Partner', help="Address of partner"),
498 'invoice_state': fields.selection([
499 ("invoiced", "Invoiced"),
500 ("2binvoiced", "To Be Invoiced"),
501 ("none", "Not from Picking")], "Invoice Status",
502 select=True, required=True, readonly=True, states={'draft': [('readonly', False)]}),
503 'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
506 'name': lambda self, cr, uid, context: '/',
507 'active': lambda *a: 1,
508 'state': lambda *a: 'draft',
509 'move_type': lambda *a: 'direct',
510 'type': lambda *a: 'in',
511 'invoice_state': lambda *a: 'none',
512 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
513 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock_picking', context=c)
516 def copy(self, cr, uid, id, default=None, context={}):
519 default = default.copy()
520 if not default.get('name',False):
521 default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking')
522 return super(stock_picking, self).copy(cr, uid, id, default, context)
524 def onchange_partner_in(self, cr, uid, context, partner_id=None):
527 def action_explode(self, cr, uid, moves, context={}):
530 def action_confirm(self, cr, uid, ids, context={}):
531 self.write(cr, uid, ids, {'state': 'confirmed'})
533 for picking in self.browse(cr, uid, ids):
534 for r in picking.move_lines:
535 if r.state == 'draft':
537 todo = self.action_explode(cr, uid, todo, context)
539 self.pool.get('stock.move').action_confirm(cr, uid, todo, context)
542 def test_auto_picking(self, cr, uid, ids):
543 # TODO: Check locations to see if in the same location ?
546 # def button_confirm(self, cr, uid, ids, *args):
548 # wf_service = netsvc.LocalService("workflow")
549 # wf_service.trg_validate(uid, 'stock.picking', id, 'button_confirm', cr)
550 # self.force_assign(cr, uid, ids, *args)
553 def action_assign(self, cr, uid, ids, *args):
554 for pick in self.browse(cr, uid, ids):
555 move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
557 raise osv.except_osv(_('Warning !'),_('Not Available. Moves are not confirmed.'))
558 self.pool.get('stock.move').action_assign(cr, uid, move_ids)
561 def force_assign(self, cr, uid, ids, *args):
562 wf_service = netsvc.LocalService("workflow")
563 for pick in self.browse(cr, uid, ids):
564 move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
565 # move_ids = [x.id for x in pick.move_lines]
566 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
567 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
570 def draft_force_assign(self, cr, uid, ids, *args):
571 wf_service = netsvc.LocalService("workflow")
572 for pick in self.browse(cr, uid, ids):
573 wf_service.trg_validate(uid, 'stock.picking', pick.id,
574 'button_confirm', cr)
575 #move_ids = [x.id for x in pick.move_lines]
576 #self.pool.get('stock.move').force_assign(cr, uid, move_ids)
577 #wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
580 def draft_validate(self, cr, uid, ids, *args):
581 wf_service = netsvc.LocalService("workflow")
582 self.draft_force_assign(cr, uid, ids)
583 for pick in self.browse(cr, uid, ids):
584 move_ids = [x.id for x in pick.move_lines]
585 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
586 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
588 self.action_move(cr, uid, [pick.id])
589 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
592 def cancel_assign(self, cr, uid, ids, *args):
593 wf_service = netsvc.LocalService("workflow")
594 for pick in self.browse(cr, uid, ids):
595 move_ids = [x.id for x in pick.move_lines]
596 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
597 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
600 def action_assign_wkf(self, cr, uid, ids):
601 self.write(cr, uid, ids, {'state': 'assigned'})
604 def test_finnished(self, cr, uid, ids):
605 move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
606 for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
607 if move.state not in ('done', 'cancel'):
608 if move.product_qty != 0.0:
611 move.write(cr, uid, [move.id], {'state': 'done'})
614 def test_assigned(self, cr, uid, ids):
616 for pick in self.browse(cr, uid, ids):
618 for move in pick.move_lines:
619 if (move.state in ('confirmed', 'draft')) and (mt=='one'):
621 if (mt=='direct') and (move.state=='assigned') and (move.product_qty):
623 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
626 def action_cancel(self, cr, uid, ids, context={}):
627 for pick in self.browse(cr, uid, ids):
628 ids2 = [move.id for move in pick.move_lines]
629 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
630 self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
634 # TODO: change and create a move if not parents
636 def action_done(self, cr, uid, ids, context=None):
637 self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
640 def action_move(self, cr, uid, ids, context={}):
641 for pick in self.browse(cr, uid, ids):
643 for move in pick.move_lines:
644 if move.state == 'assigned':
648 self.pool.get('stock.move').action_done(cr, uid, todo,
652 def get_currency_id(self, cr, uid, picking):
655 def _get_payment_term(self, cr, uid, picking):
656 '''Return {'contact': address, 'invoice': address} for invoice'''
657 partner_obj = self.pool.get('res.partner')
658 partner = picking.address_id.partner_id
659 return partner.property_payment_term and partner.property_payment_term.id or False
661 def _get_address_invoice(self, cr, uid, picking):
662 '''Return {'contact': address, 'invoice': address} for invoice'''
663 partner_obj = self.pool.get('res.partner')
664 partner = picking.address_id.partner_id
666 return partner_obj.address_get(cr, uid, [partner.id],
667 ['contact', 'invoice'])
669 def _get_comment_invoice(self, cr, uid, picking):
670 '''Return comment string for invoice'''
671 return picking.note or ''
673 def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None):
674 '''Return the price unit for the move line'''
678 if type in ('in_invoice', 'in_refund'):
679 # Take the user company and pricetype
680 price_type_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.property_valuation_price_type.id
681 pricetype = self.pool.get('product.price.type').browse(cr, uid, price_type_id)
682 context['currency_id'] = move_line.company_id.currency_id.id
684 amount_unit = move_line.product_id.price_get(pricetype.field, context)[move_line.product_id.id]
687 return move_line.product_id.list_price
689 def _get_discount_invoice(self, cr, uid, move_line):
690 '''Return the discount for the move line'''
693 def _get_taxes_invoice(self, cr, uid, move_line, type):
694 '''Return taxes ids for the move line'''
695 if type in ('in_invoice', 'in_refund'):
696 taxes = move_line.product_id.supplier_taxes_id
698 taxes = move_line.product_id.taxes_id
700 if move_line.picking_id and move_line.picking_id.address_id and move_line.picking_id.address_id.partner_id:
701 return self.pool.get('account.fiscal.position').map_tax(
704 move_line.picking_id.address_id.partner_id.property_account_position,
708 return map(lambda x: x.id, taxes)
710 def _get_account_analytic_invoice(self, cr, uid, picking, move_line):
713 def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
714 '''Call after the creation of the invoice line'''
717 def _invoice_hook(self, cr, uid, picking, invoice_id):
718 '''Call after the creation of the invoice'''
721 def action_invoice_create(self, cr, uid, ids, journal_id=False,
722 group=False, type='out_invoice', context=None):
723 '''Return ids of created invoices for the pickings'''
727 invoice_obj = self.pool.get('account.invoice')
728 invoice_line_obj = self.pool.get('account.invoice.line')
732 for picking in self.browse(cr, uid, ids, context=context):
733 if picking.invoice_state != '2binvoiced':
735 payment_term_id = False
736 partner = picking.address_id and picking.address_id.partner_id
738 raise osv.except_osv(_('Error, no partner !'),
739 _('Please put a partner on the picking list if you want to generate invoice.'))
741 if type in ('out_invoice', 'out_refund'):
742 account_id = partner.property_account_receivable.id
743 payment_term_id = self._get_payment_term(cr, uid, picking)
745 account_id = partner.property_account_payable.id
747 address_contact_id, address_invoice_id = \
748 self._get_address_invoice(cr, uid, picking).values()
750 comment = self._get_comment_invoice(cr, uid, picking)
751 if group and partner.id in invoices_group:
752 invoice_id = invoices_group[partner.id]
753 invoice = invoice_obj.browse(cr, uid, invoice_id)
755 'name': (invoice.name or '') + ', ' + (picking.name or ''),
756 'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
757 'comment': (comment and (invoice.comment and invoice.comment+"\n"+comment or comment)) or (invoice.comment and invoice.comment or ''),
758 'date_invoice':context.get('date_inv',False)
760 invoice_obj.write(cr, uid, [invoice_id], invoice_vals, context=context)
763 'name': picking.name,
764 'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
766 'account_id': account_id,
767 'partner_id': partner.id,
768 'address_invoice_id': address_invoice_id,
769 'address_contact_id': address_contact_id,
771 'payment_term': payment_term_id,
772 'fiscal_position': partner.property_account_position.id,
773 'date_invoice': context.get('date_inv',False),
774 'company_id': picking.company_id.id,
776 cur_id = self.get_currency_id(cr, uid, picking)
778 invoice_vals['currency_id'] = cur_id
780 invoice_vals['journal_id'] = journal_id
781 invoice_id = invoice_obj.create(cr, uid, invoice_vals,
783 invoices_group[partner.id] = invoice_id
784 res[picking.id] = invoice_id
785 for move_line in picking.move_lines:
786 origin = move_line.picking_id.name
787 if move_line.picking_id.origin:
788 origin += ':' + move_line.picking_id.origin
790 name = (picking.name or '') + '-' + move_line.name
792 name = move_line.name
794 if type in ('out_invoice', 'out_refund'):
795 account_id = move_line.product_id.product_tmpl_id.\
796 property_account_income.id
798 account_id = move_line.product_id.categ_id.\
799 property_account_income_categ.id
801 account_id = move_line.product_id.product_tmpl_id.\
802 property_account_expense.id
804 account_id = move_line.product_id.categ_id.\
805 property_account_expense_categ.id
807 price_unit = self._get_price_unit_invoice(cr, uid,
809 discount = self._get_discount_invoice(cr, uid, move_line)
810 tax_ids = self._get_taxes_invoice(cr, uid, move_line, type)
811 account_analytic_id = self._get_account_analytic_invoice(cr, uid, picking, move_line)
813 #set UoS if it's a sale and the picking doesn't have one
814 uos_id = move_line.product_uos and move_line.product_uos.id or False
815 if not uos_id and type in ('out_invoice', 'out_refund'):
816 uos_id = move_line.product_uom.id
818 account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, partner.property_account_position, account_id)
820 if move_line.sale_line_id:
821 notes = move_line.sale_line_id.notes
822 elif move_line.purchase_line_id:
823 notes = move_line.purchase_line_id.notes
825 invoice_line_id = invoice_line_obj.create(cr, uid, {
828 'invoice_id': invoice_id,
830 'product_id': move_line.product_id.id,
831 'account_id': account_id,
832 'price_unit': price_unit,
833 'discount': discount,
834 'quantity': move_line.product_uos_qty or move_line.product_qty,
835 'invoice_line_tax_id': [(6, 0, tax_ids)],
836 'account_analytic_id': account_analytic_id,
839 self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
841 invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
842 set_total=(type in ('in_invoice', 'in_refund')))
843 self.write(cr, uid, [picking.id], {
844 'invoice_state': 'invoiced',
846 self._invoice_hook(cr, uid, picking, invoice_id)
847 self.write(cr, uid, res.keys(), {
848 'invoice_state': 'invoiced',
852 def test_cancel(self, cr, uid, ids, context={}):
853 for pick in self.browse(cr, uid, ids, context=context):
854 if not pick.move_lines:
856 for move in pick.move_lines:
857 if move.state not in ('cancel',):
861 def unlink(self, cr, uid, ids, context=None):
862 for pick in self.browse(cr, uid, ids, context=context):
863 if pick.state in ['done','cancel']:
864 raise osv.except_osv(_('Error'), _('You cannot remove the picking which is in %s state !')%(pick.state,))
865 elif pick.state in ['confirmed','assigned']:
866 ids2 = [move.id for move in pick.move_lines]
867 context.update({'call_unlink':True})
868 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
871 return super(stock_picking, self).unlink(cr, uid, ids, context=context)
873 def do_partial(self, cr, uid, ids, partial_datas, context={}):
875 @ partial_datas : dict. contain details of partial picking
876 like partner_id, address_id, delivery_date, delivery moves with product_id, product_qty, uom
879 move_obj = self.pool.get('stock.move')
880 delivery_obj = self.pool.get('stock.delivery')
881 product_obj = self.pool.get('product.product')
882 currency_obj = self.pool.get('res.currency')
883 users_obj = self.pool.get('res.users')
884 uom_obj = self.pool.get('product.uom')
885 price_type_obj = self.pool.get('product.price.type')
886 sequence_obj = self.pool.get('ir.sequence')
887 wf_service = netsvc.LocalService("workflow")
888 partner_id = partial_datas.get('partner_id', False)
889 address_id = partial_datas.get('address_id', False)
890 delivery_date = partial_datas.get('delivery_date', False)
891 for pick in self.browse(cr, uid, ids, context=context):
895 complete, too_many, too_few = [], [], []
896 move_product_qty = {}
897 for move in pick.move_lines:
898 if move.state in ('done', 'cancel'):
900 partial_data = partial_datas.get('move%s'%(move.id), False)
901 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
902 product_qty = partial_data.get('product_qty',0.0)
903 move_product_qty[move.id] = product_qty
904 product_uom = partial_data.get('product_uom',False)
905 product_price = partial_data.get('product_price',0.0)
906 product_currency = partial_data.get('product_currency',False)
907 if move.product_qty == product_qty:
908 complete.append(move)
909 elif move.product_qty > product_qty:
912 too_many.append(move)
914 # Average price computation
915 if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
916 product = product_obj.browse(cr, uid, move.product_id.id)
917 user = users_obj.browse(cr, uid, uid)
918 context['currency_id'] = move.company_id.currency_id.id
919 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
921 if user.company_id.property_valuation_price_type:
922 pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
923 if pricetype and qty > 0:
924 new_price = currency_obj.compute(cr, uid, product_currency,
925 user.company_id.currency_id.id, product_price)
926 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
928 if product.qty_available <= 0:
929 new_std_price = new_price
931 # Get the standard price
932 amount_unit = product.price_get(pricetype.field, context)[product.id]
933 new_std_price = ((amount_unit * product.qty_available)\
934 + (new_price * qty))/(product.qty_available + qty)
936 # Write the field according to price type field
937 product_obj.write(cr, uid, [product.id],
938 {pricetype.field: new_std_price})
939 move_obj.write(cr, uid, [move.id], {'price_unit': new_price})
943 product_qty = move_product_qty[move.id]
946 new_picking = self.copy(cr, uid, pick.id,
948 'name': sequence_obj.get(cr, uid, 'stock.picking.%s'%(pick.type)),
954 new_obj = move_obj.copy(cr, uid, move.id,
956 'product_qty' : product_qty,
957 'product_uos_qty': product_qty, #TODO: put correct uos_qty
958 'picking_id' : new_picking,
960 'move_dest_id': False,
961 'price_unit': move.price_unit,
964 move_obj.write(cr, uid, [move.id],
966 'product_qty' : move.product_qty - product_qty,
967 'product_uos_qty':move.product_qty - product_qty, #TODO: put correct uos_qty
972 move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
973 for move in too_many:
974 product_qty = move_product_qty[move.id]
975 move_obj.write(cr, uid, [move.id],
977 'product_qty' : product_qty,
978 'product_uos_qty': product_qty, #TODO: put correct uos_qty
979 'picking_id': new_picking,
982 for move in too_many:
983 product_qty = move_product_qty[move.id]
984 move_obj.write(cr, uid, [move.id],
986 'product_qty': product_qty,
987 'product_uos_qty': product_qty #TODO: put correct uos_qty
990 # At first we confirm the new picking (if necessary)
992 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
993 # Then we finish the good picking
995 self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
996 self.action_move(cr, uid, [new_picking])
997 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr)
998 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
999 delivered_pack_id = new_picking
1001 self.action_move(cr, uid, [pick.id])
1002 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
1003 delivered_pack_id = pick.id
1005 delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
1006 delivery_id = delivery_obj.create(cr, uid, {
1007 'name': delivered_pack.name,
1008 'partner_id': partner_id,
1009 'address_id': address_id,
1010 'date': delivery_date,
1011 'picking_id' : pick.id,
1012 'move_delivered' : [(6,0, map(lambda x:x.id, delivered_pack.move_lines))]
1014 res[pick.id] = {'delivered_picking': delivered_pack.id or False}
1020 class stock_production_lot(osv.osv):
1021 def name_get(self, cr, uid, ids, context={}):
1024 reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
1026 for record in reads:
1027 name = record['name']
1028 prefix = record['prefix']
1030 name = prefix + '/' + name
1032 name = '%s [%s]' % (name, record['ref'])
1033 res.append((record['id'], name))
1036 _name = 'stock.production.lot'
1037 _description = 'Production lot'
1039 def _get_stock(self, cr, uid, ids, field_name, arg, context={}):
1040 if 'location_id' not in context:
1041 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
1043 locations = context['location_id'] and [context['location_id']] or []
1045 if isinstance(ids, (int, long)):
1048 res = {}.fromkeys(ids, 0.0)
1050 cr.execute('''select
1054 stock_report_prodlots
1056 location_id =ANY(%s) and prodlot_id =ANY(%s) group by prodlot_id''',(locations,ids,))
1057 res.update(dict(cr.fetchall()))
1060 def _stock_search(self, cr, uid, obj, name, args, context):
1061 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
1062 cr.execute('''select
1066 stock_report_prodlots
1068 location_id =ANY(%s) group by prodlot_id
1069 having sum(name) '''+ str(args[0][1]) + str(args[0][2]),(locations,))
1071 ids = [('id', 'in', map(lambda x: x[0], res))]
1075 'name': fields.char('Serial', size=64, required=True),
1076 'ref': fields.char('Internal Reference', size=256),
1077 'prefix': fields.char('Prefix', size=64),
1078 'product_id': fields.many2one('product.product', 'Product', required=True),
1079 'date': fields.datetime('Created Date', required=True),
1080 'stock_available': fields.function(_get_stock, fnct_search=_stock_search, method=True, type="float", string="Available", select="2"),
1081 'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
1082 'company_id': fields.many2one('res.company','Company',select=1),
1085 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1086 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1087 'product_id': lambda x, y, z, c: c.get('product_id', False),
1089 _sql_constraints = [
1090 ('name_ref_uniq', 'unique (name, ref)', 'The serial/ref must be unique !'),
1093 stock_production_lot()
1095 class stock_production_lot_revision(osv.osv):
1096 _name = 'stock.production.lot.revision'
1097 _description = 'Production lot revisions'
1099 'name': fields.char('Revision Name', size=64, required=True),
1100 'description': fields.text('Description'),
1101 'date': fields.date('Revision Date'),
1102 'indice': fields.char('Revision', size=16),
1103 'author_id': fields.many2one('res.users', 'Author'),
1104 'lot_id': fields.many2one('stock.production.lot', 'Production lot', select=True, ondelete='cascade'),
1105 'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
1109 'author_id': lambda x, y, z, c: z,
1110 'date': lambda *a: time.strftime('%Y-%m-%d'),
1113 stock_production_lot_revision()
1115 class stock_delivery(osv.osv):
1117 """ Tracability of partialdeliveries """
1119 _name = "stock.delivery"
1120 _description = "Delivery"
1122 'name': fields.char('Name', size=60, required=True),
1123 'date': fields.datetime('Date', required=True),
1124 'partner_id': fields.many2one('res.partner', 'Partner', required=True),
1125 'address_id': fields.many2one('res.partner.address', 'Address', required=True),
1126 'move_delivered':fields.one2many('stock.move', 'delivered_id', 'Move Delivered'),
1127 'picking_id': fields.many2one('stock.picking', 'Picking list'),
1131 # ----------------------------------------------------
1133 # ----------------------------------------------------
1137 # location_dest_id is only used for predicting futur stocks
1139 class stock_move(osv.osv):
1140 def _getSSCC(self, cr, uid, context={}):
1141 cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
1143 return (res and res[0]) or False
1144 _name = "stock.move"
1145 _description = "Stock Move"
1147 def name_get(self, cr, uid, ids, context={}):
1149 for line in self.browse(cr, uid, ids, context):
1150 res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))
1153 def _check_tracking(self, cr, uid, ids):
1154 for move in self.browse(cr, uid, ids):
1155 if not move.prodlot_id and \
1156 (move.state == 'done' and \
1158 (move.product_id.track_production and move.location_id.usage=='production') or \
1159 (move.product_id.track_production and move.location_dest_id.usage=='production') or \
1160 (move.product_id.track_incoming and move.location_id.usage in ('supplier','internal')) or \
1161 (move.product_id.track_outgoing and move.location_dest_id.usage in ('customer','internal')) \
1166 def _check_product_lot(self, cr, uid, ids):
1167 for move in self.browse(cr, uid, ids):
1168 if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):
1173 'name': fields.char('Name', size=64, required=True, select=True),
1174 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1176 'date': fields.datetime('Created Date'),
1177 'date_planned': fields.datetime('Date', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
1179 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
1181 'product_qty': fields.float('Quantity', required=True),
1182 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
1183 'product_uos_qty': fields.float('Quantity (UOS)'),
1184 'product_uos': fields.many2one('product.uom', 'Product UOS'),
1185 'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1187 '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."),
1188 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, select=True, help="Location where the system will stock the finished products."),
1189 'address_id': fields.many2one('res.partner.address', 'Dest. Address', help="Address where goods are to be delivered"),
1191 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="Production lot is used to put a serial number on the production"),
1192 'tracking_id': fields.many2one('stock.tracking', 'Tracking Lot', select=True, help="Tracking lot is the code that will be put on the logistical unit/pallet"),
1193 # 'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),
1195 'auto_validate': fields.boolean('Auto Validate'),
1197 'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),
1198 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
1199 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
1200 'picking_id': fields.many2one('stock.picking', 'Picking List', select=True),
1202 'note': fields.text('Notes'),
1204 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'State', readonly=True, select=True,
1205 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 \'Avaiable\'.\n When the picking it done the state is \'Done\'.\
1206 \nThe state is \'Waiting\' if the move is waiting for another one.'),
1207 'price_unit': fields.float('Unit Price',
1208 digits_compute= dp.get_precision('Account')),
1209 'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
1210 'partner_id': fields.related('picking_id','address_id','partner_id',type='many2one', relation="res.partner", string="Partner"),
1211 'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Orders"),
1212 'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Origin"),
1213 'move_stock_return_history': fields.many2many('stock.move', 'stock_move_return_history', 'move_id', 'return_move_id', 'Move Return History',readonly=True),
1214 'delivered_id': fields.many2one('stock.delivery', 'Product delivered'),
1215 'scraped': fields.boolean('Scraped'),
1219 'You must assign a production lot for this product',
1221 (_check_product_lot,
1222 'You try to assign a lot which is not from the same product',
1225 def _default_location_destination(self, cr, uid, context={}):
1226 if context.get('move_line', []):
1227 if context['move_line'][0]:
1228 if isinstance(context['move_line'][0], (tuple, list)):
1229 return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
1231 move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1232 return move_list and move_list['location_dest_id'][0] or False
1233 if context.get('address_out_id', False):
1234 return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id
1237 def _default_location_source(self, cr, uid, context={}):
1238 if context.get('move_line', []):
1240 return context['move_line'][0][2]['location_id']
1243 if context.get('address_in_id', False):
1244 return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1248 'location_id': _default_location_source,
1249 'location_dest_id': _default_location_destination,
1250 'state': lambda *a: 'draft',
1251 'priority': lambda *a: '1',
1252 'scraped' : lambda *a:False,
1253 'product_qty': lambda *a: 1.0,
1254 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1255 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1256 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c)
1259 def copy(self, cr, uid, id, default=None, context={}):
1262 default = default.copy()
1263 default['move_stock_return_history'] = []
1264 return super(stock_move, self).copy(cr, uid, id, default, context)
1266 def create(self, cr, user, vals, context=None):
1267 if vals.get('move_stock_return_history',False):
1268 vals['move_stock_return_history'] = []
1269 return super(stock_move, self).create(cr, user, vals, context)
1271 def _auto_init(self, cursor, context):
1272 res = super(stock_move, self)._auto_init(cursor, context)
1273 cursor.execute('SELECT indexname \
1275 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1276 if not cursor.fetchone():
1277 cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1278 ON stock_move (location_id, location_dest_id, product_id, state)')
1282 def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_id=False, context=None):
1283 if not prodlot_id or not loc_id:
1285 ctx = context and context.copy() or {}
1286 ctx['location_id'] = loc_id
1287 prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1288 location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1290 if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1292 'title': 'Bad Lot Assignation !',
1293 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1295 return {'warning': warning}
1297 def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1299 'product_uos_qty': 0.00
1302 if (not product_id) or (product_qty <=0.0):
1303 return {'value': result}
1305 product_obj = self.pool.get('product.product')
1306 uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1308 if product_uos and product_uom and (product_uom != product_uos):
1309 result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1311 result['product_uos_qty'] = product_qty
1313 return {'value': result}
1315 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, address_id=False):
1320 addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1322 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1323 ctx = {'lang': lang}
1325 product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1326 uos_id = product.uos_id and product.uos_id.id or False
1328 'product_uom': product.uom_id.id,
1329 'product_uos': uos_id,
1330 'product_qty': 1.00,
1331 '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']
1334 result['name'] = product.partner_ref
1336 result['location_id'] = loc_id
1338 result['location_dest_id'] = loc_dest_id
1339 return {'value': result}
1341 def _chain_compute(self, cr, uid, moves, context={}):
1344 dest = self.pool.get('stock.location').chained_location_get(
1348 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1353 if dest[1] == 'transparent':
1354 self.write(cr, uid, [m.id], {
1355 'date_planned': (datetime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1356 relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1357 'location_dest_id': dest[0].id})
1359 result.setdefault(m.picking_id, [])
1360 result[m.picking_id].append( (m, dest) )
1363 def action_confirm(self, cr, uid, ids, context={}):
1364 # ids = map(lambda m: m.id, moves)
1365 moves = self.browse(cr, uid, ids)
1366 self.write(cr, uid, ids, {'state': 'confirmed'})
1369 def create_chained_picking(self, cr, uid, moves, context):
1371 for picking, todo in self._chain_compute(cr, uid, moves, context).items():
1372 ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
1373 pickid = self.pool.get('stock.picking').create(cr, uid, {
1374 'name': picking.name,
1375 'origin': str(picking.origin or ''),
1377 'note': picking.note,
1378 'move_type': picking.move_type,
1379 'auto_picking': todo[0][1][1] == 'auto',
1380 'address_id': picking.address_id.id,
1381 'invoice_state': 'none'
1383 for move, (loc, auto, delay) in todo:
1384 # Is it smart to copy ? May be it's better to recreate ?
1385 new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {
1386 'location_id': move.location_dest_id.id,
1387 'location_dest_id': loc.id,
1388 'date_moved': time.strftime('%Y-%m-%d'),
1389 'picking_id': pickid,
1391 'move_history_ids': [],
1392 'date_planned': (datetime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
1393 'move_history_ids2': []}
1395 self.pool.get('stock.move').write(cr, uid, [move.id], {
1396 'move_dest_id': new_id,
1397 'move_history_ids': [(4, new_id)]
1399 new_moves.append(self.browse(cr, uid, [new_id])[0])
1400 wf_service = netsvc.LocalService("workflow")
1401 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1403 create_chained_picking(self, cr, uid, new_moves, context)
1404 create_chained_picking(self, cr, uid, moves, context)
1407 def action_assign(self, cr, uid, ids, *args):
1409 for move in self.browse(cr, uid, ids):
1410 if move.state in ('confirmed', 'waiting'):
1411 todo.append(move.id)
1412 res = self.check_assign(cr, uid, todo)
1415 def force_assign(self, cr, uid, ids, context={}):
1416 self.write(cr, uid, ids, {'state': 'assigned'})
1419 def cancel_assign(self, cr, uid, ids, context={}):
1420 self.write(cr, uid, ids, {'state': 'confirmed'})
1424 # Duplicate stock.move
1426 def check_assign(self, cr, uid, ids, context={}):
1430 for move in self.browse(cr, uid, ids):
1431 if move.product_id.type == 'consu':
1432 if move.state in ('confirmed', 'waiting'):
1433 done.append(move.id)
1434 pickings[move.picking_id.id] = 1
1436 if move.state in ('confirmed', 'waiting'):
1437 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})
1439 #_product_available_test depends on the next status for correct functioning
1440 #the test does not work correctly if the same product occurs multiple times
1441 #in the same order. This is e.g. the case when using the button 'split in two' of
1442 #the stock outgoing form
1443 self.write(cr, uid, move.id, {'state':'assigned'})
1444 done.append(move.id)
1445 pickings[move.picking_id.id] = 1
1447 cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1451 move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1452 done.append(move_id)
1453 #cr.execute('insert into stock_move_history_ids values (%s,%s)', (move.id,move_id))
1456 self.write(cr, uid, done, {'state': 'assigned'})
1459 for pick_id in pickings:
1460 wf_service = netsvc.LocalService("workflow")
1461 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1465 # Cancel move => cancel others move and pickings
1467 def action_cancel(self, cr, uid, ids, context={}):
1471 for move in self.browse(cr, uid, ids):
1472 if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1474 pickings[move.picking_id.id] = True
1475 if move.move_dest_id and move.move_dest_id.state == 'waiting':
1476 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1477 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1478 wf_service = netsvc.LocalService("workflow")
1479 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1480 self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1481 if not context.get('call_unlink',False):
1482 for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1483 if all(move.state == 'cancel' for move in pick.move_lines):
1484 self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1486 wf_service = netsvc.LocalService("workflow")
1488 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1489 #self.action_cancel(cr,uid, ids2, context)
1492 def action_done(self, cr, uid, ids, context=None):
1495 for move in self.browse(cr, uid, ids):
1496 if move.picking_id: picking_ids.append(move.picking_id.id)
1497 if move.move_dest_id.id and (move.state != 'done'):
1498 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1499 if move.move_dest_id.state in ('waiting', 'confirmed'):
1500 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1501 if move.move_dest_id.picking_id:
1502 wf_service = netsvc.LocalService("workflow")
1503 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1506 # self.action_done(cr, uid, [move.move_dest_id.id])
1507 if move.move_dest_id.auto_validate:
1508 self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1511 # Accounting Entries
1515 if move.location_id.account_id:
1516 acc_src = move.location_id.account_id.id
1517 if move.location_dest_id.account_id:
1518 acc_dest = move.location_dest_id.account_id.id
1519 if acc_src or acc_dest:
1520 test = [('product.product', move.product_id.id)]
1521 if move.product_id.categ_id:
1522 test.append( ('product.category', move.product_id.categ_id.id) )
1524 acc_src = move.product_id.product_tmpl_id.\
1525 property_stock_account_input.id
1527 acc_src = move.product_id.categ_id.\
1528 property_stock_account_input_categ.id
1530 raise osv.except_osv(_('Error!'),
1531 _('There is no stock input account defined ' \
1532 'for this product: "%s" (id: %d)') % \
1533 (move.product_id.name,
1534 move.product_id.id,))
1536 acc_dest = move.product_id.product_tmpl_id.\
1537 property_stock_account_output.id
1539 acc_dest = move.product_id.categ_id.\
1540 property_stock_account_output_categ.id
1542 raise osv.except_osv(_('Error!'),
1543 _('There is no stock output account defined ' \
1544 'for this product: "%s" (id: %d)') % \
1545 (move.product_id.name,
1546 move.product_id.id,))
1547 if not move.product_id.categ_id.property_stock_journal.id:
1548 raise osv.except_osv(_('Error!'),
1549 _('There is no journal defined '\
1550 'on the product category: "%s" (id: %d)') % \
1551 (move.product_id.categ_id.name,
1552 move.product_id.categ_id.id,))
1553 journal_id = move.product_id.categ_id.property_stock_journal.id
1554 if acc_src != acc_dest:
1555 ref = move.picking_id and move.picking_id.name or False
1556 product_uom_obj = self.pool.get('product.uom')
1557 default_uom = move.product_id.uom_id.id
1558 date = time.strftime('%Y-%m-%d')
1559 q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1560 if move.product_id.cost_method == 'average' and move.price_unit:
1561 amount = q * move.price_unit
1562 # Base computation on valuation price type
1564 company_id=move.company_id.id
1565 context['currency_id']=move.company_id.currency_id.id
1566 pricetype=self.pool.get('product.price.type').browse(cr,uid,move.company_id.property_valuation_price_type.id)
1567 amount_unit=move.product_id.price_get(pricetype.field, context)[move.product_id.id]
1568 amount=amount_unit * q or 1.0
1569 # amount = q * move.product_id.standard_price
1573 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
1577 'quantity': move.product_qty,
1578 'product_id': move.product_id and move.product_id.id or False,
1580 'account_id': acc_src,
1583 'partner_id': partner_id}),
1586 'product_id': move.product_id and move.product_id.id or False,
1587 'quantity': move.product_qty,
1589 'account_id': acc_dest,
1592 'partner_id': partner_id})
1594 self.pool.get('account.move').create(cr, uid, {
1596 'journal_id': journal_id,
1600 self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1601 for pick in self.pool.get('stock.picking').browse(cr, uid, picking_ids):
1602 if all(move.state == 'done' for move in pick.move_lines):
1603 self.pool.get('stock.picking').action_done(cr, uid, [pick.id])
1605 wf_service = netsvc.LocalService("workflow")
1607 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1610 def unlink(self, cr, uid, ids, context=None):
1611 for move in self.browse(cr, uid, ids, context=context):
1612 if move.state != 'draft':
1613 raise osv.except_osv(_('UserError'),
1614 _('You can only delete draft moves.'))
1615 return super(stock_move, self).unlink(
1616 cr, uid, ids, context=context)
1618 def _create_lot(self, cr, uid, ids, product_id, prefix=False):
1619 prodlot_obj = self.pool.get('stock.production.lot')
1620 ir_sequence_obj = self.pool.get('ir.sequence')
1621 sequence = ir_sequence_obj.get(cr, uid, 'stock.lot.serial')
1623 raise osv.except_osv(_('Error!'), _('No production sequence defined'))
1624 prodlot_id = prodlot_obj.create(cr, uid, {'name': sequence, 'prefix': prefix}, {'product_id': product_id})
1625 prodlot = prodlot_obj.browse(cr, uid, prodlot_id)
1626 ref = ','.join(map(lambda x:str(x),ids))
1628 ref = '%s, %s' % (prodlot.ref, ref)
1629 prodlot_obj.write(cr, uid, [prodlot_id], {'ref': ref})
1633 def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1635 Move the scrap/damaged product into scrap location
1637 @ param cr: the database cursor
1638 @ param uid: the user id
1639 @ param ids: ids of stock move object to be scraped
1640 @ param quantity : specify scrap qty
1641 @ param location_id : specify scrap location
1642 @ param context: context arguments
1644 @ return: Scraped lines
1647 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1649 for move in self.browse(cr, uid, ids, context=context):
1650 move_qty = move.product_qty
1651 uos_qty = quantity / move_qty * move.product_uos_qty
1653 'product_qty': quantity,
1654 'product_uos_qty': uos_qty,
1655 'state': move.state,
1657 'location_dest_id': location_id
1659 new_move = self.copy(cr, uid, move.id, default_val)
1660 #self.write(cr, uid, [new_move], {'move_history_ids':[(4,move.id)]}) #TODO : to track scrap moves
1662 self.action_done(cr, uid, res)
1665 def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
1667 Split Stock Move lines into production lot which specified split by quantity.
1669 @ param cr: the database cursor
1670 @ param uid: the user id
1671 @ param ids: ids of stock move object to be splited
1672 @ param split_by_qty : specify split by qty
1673 @ param prefix : specify prefix of production lot
1674 @ param with_lot : if true, prodcution lot will assign for split line otherwise not.
1675 @ param context: context arguments
1677 @ return: splited move lines
1681 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1685 for move in self.browse(cr, uid, ids):
1686 if split_by_qty <= 0 or quantity == 0:
1689 uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
1691 quantity_rest = quantity % split_by_qty
1692 uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
1695 'product_qty': split_by_qty,
1696 'product_uos_qty': uos_qty,
1698 for idx in range(int(quantity//split_by_qty)):
1699 if not idx and move.product_qty<=quantity:
1700 current_move = move.id
1702 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1703 res.append(current_move)
1705 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1707 self.write(cr, uid, [current_move], update_val)
1710 if quantity_rest > 0:
1711 idx = int(quantity//split_by_qty)
1712 update_val['product_qty'] = quantity_rest
1713 update_val['product_uos_qty'] = uos_qty_rest
1714 if not idx and move.product_qty<=quantity:
1715 current_move = move.id
1717 current_move = self.copy(cr, uid, move.id, {'state': move.state})
1719 res.append(current_move)
1723 update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1725 self.write(cr, uid, [current_move], update_val)
1728 def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
1730 Consumed product with specific quatity from specific source location
1732 @ param cr: the database cursor
1733 @ param uid: the user id
1734 @ param ids: ids of stock move object to be consumed
1735 @ param quantity : specify consume quantity
1736 @ param location_id : specify source location
1737 @ param context: context arguments
1739 @ return: Consumed lines
1745 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1748 for move in self.browse(cr, uid, ids, context=context):
1749 move_qty = move.product_qty
1750 quantity_rest = move.product_qty
1752 quantity_rest -= quantity
1753 uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
1754 if quantity_rest <= 0:
1757 quantity = move.product_qty
1759 uos_qty = quantity / move_qty * move.product_uos_qty
1761 if quantity_rest > 0:
1763 'product_qty': quantity,
1764 'product_uos_qty': uos_qty,
1765 'state': move.state,
1766 'location_id': location_id
1768 if move.product_id.track_production and location_id:
1769 # IF product has checked track for production lot, move lines will be split by 1
1770 res += self.action_split(cr, uid, [move.id], quantity, split_by_qty=1, context=context)
1772 current_move = self.copy(cr, uid, move.id, default_val)
1773 res += [current_move]
1776 update_val['product_qty'] = quantity_rest
1777 update_val['product_uos_qty'] = uos_qty_rest
1778 self.write(cr, uid, [move.id], update_val)
1781 quantity_rest = quantity
1782 uos_qty_rest = uos_qty
1784 if move.product_id.track_production and location_id:
1785 res += self.split_lines(cr, uid, [move.id], quantity_rest, split_by_qty=1, context=context)
1789 'product_qty' : quantity_rest,
1790 'product_uos_qty' : uos_qty_rest,
1791 'location_id': location_id
1794 self.write(cr, uid, [move.id], update_val)
1796 self.action_done(cr, uid, res)
1799 def do_partial(self, cr, uid, ids, partial_datas, context={}):
1801 @ partial_datas : dict. contain details of partial picking
1802 like partner_id, address_id, delivery_date, delivery moves with product_id, product_qty, uom
1805 picking_obj = self.pool.get('stock.picking')
1806 delivery_obj = self.pool.get('stock.delivery')
1807 product_obj = self.pool.get('product.product')
1808 currency_obj = self.pool.get('res.currency')
1809 users_obj = self.pool.get('res.users')
1810 uom_obj = self.pool.get('product.uom')
1811 price_type_obj = self.pool.get('product.price.type')
1812 sequence_obj = self.pool.get('ir.sequence')
1813 wf_service = netsvc.LocalService("workflow")
1814 partner_id = partial_datas.get('partner_id', False)
1815 address_id = partial_datas.get('address_id', False)
1816 delivery_date = partial_datas.get('delivery_date', False)
1820 complete, too_many, too_few = [], [], []
1821 move_product_qty = {}
1822 for move in self.browse(cr, uid, ids, context=context):
1823 if move.state in ('done', 'cancel'):
1825 partial_data = partial_datas.get('move%s'%(move.id), False)
1826 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
1827 product_qty = partial_data.get('product_qty',0.0)
1828 move_product_qty[move.id] = product_qty
1829 product_uom = partial_data.get('product_uom',False)
1830 product_price = partial_data.get('product_price',0.0)
1831 product_currency = partial_data.get('product_currency',False)
1832 if move.product_qty == product_qty:
1833 complete.append(move)
1834 elif move.product_qty > product_qty:
1835 too_few.append(move)
1837 too_many.append(move)
1839 # Average price computation
1840 if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
1841 product = product_obj.browse(cr, uid, move.product_id.id)
1842 user = users_obj.browse(cr, uid, uid)
1843 context['currency_id'] = move.company_id.currency_id.id
1844 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
1846 if user.company_id.property_valuation_price_type:
1847 pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
1848 if pricetype and qty > 0:
1849 new_price = currency_obj.compute(cr, uid, product_currency,
1850 user.company_id.currency_id.id, product_price)
1851 new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
1853 if product.qty_available <= 0:
1854 new_std_price = new_price
1856 # Get the standard price
1857 amount_unit = product.price_get(pricetype.field, context)[product.id]
1858 new_std_price = ((amount_unit * product.qty_available)\
1859 + (new_price * qty))/(product.qty_available + qty)
1861 # Write the field according to price type field
1862 product_obj.write(cr, uid, [product.id],
1863 {pricetype.field: new_std_price})
1864 self.write(cr, uid, [move.id], {'price_unit': new_price})
1866 for move in too_few:
1867 product_qty = move_product_qty[move.id]
1868 if product_qty != 0:
1869 new_move = self.copy(cr, uid, move.id,
1871 'product_qty' : product_qty,
1872 'product_uos_qty': product_qty,
1873 'picking_id' : move.picking_id.id,
1874 'state': 'assigned',
1875 'move_dest_id': False,
1876 'price_unit': move.price_unit,
1878 complete.append(self.browse(cr, uid, new_move))
1879 self.write(cr, uid, move.id,
1881 'product_qty' : move.product_qty - product_qty,
1882 'product_uos_qty':move.product_qty - product_qty,
1886 for move in too_many:
1887 self.write(cr, uid, move.id,
1889 'product_qty': product_qty,
1890 'product_uos_qty': product_qty
1892 complete.append(move)
1894 for move in complete:
1895 self.action_done(cr, uid, [move.id])
1897 # TOCHECK : Done picking if all moves are done
1899 SELECT move.id FROM stock_picking pick
1900 RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
1901 WHERE pick.id = %s""",
1902 ('done', move.picking_id.id))
1904 if len(res) == len(move.picking_id.move_lines):
1905 picking_obj.action_move(cr, uid, [move.picking_id.id])
1906 wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
1910 for move in complete:
1911 done_move_ids.append(move.id)
1912 if move.picking_id.id not in ref:
1913 delivery_id = delivery_obj.create(cr, uid, {
1914 'partner_id': partner_id,
1915 'address_id': address_id,
1916 'date': delivery_date,
1917 'name' : move.picking_id.name,
1918 'picking_id': move.picking_id.id
1920 ref[move.picking_id.id] = delivery_id
1921 delivery_obj.write(cr, uid, ref[move.picking_id.id], {
1922 'move_delivered' : [(4,move.id)]
1924 return done_move_ids
1929 class stock_inventory(osv.osv):
1930 _name = "stock.inventory"
1931 _description = "Inventory"
1933 'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
1934 'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
1935 'date_done': fields.datetime('Date done'),
1936 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'done': [('readonly', True)]}),
1937 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
1938 'state': fields.selection( (('draft', 'Draft'), ('done', 'Done'), ('cancel','Cancelled')), 'State', readonly=True),
1939 'company_id': fields.many2one('res.company','Company',required=True,select=1),
1942 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1943 'state': lambda *a: 'draft',
1944 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
1948 def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
1949 '''Creates a stock move from an inventory line'''
1950 return self.pool.get('stock.move').create(cr, uid, move_vals)
1952 def action_done(self, cr, uid, ids, context=None):
1953 for inv in self.browse(cr, uid, ids):
1956 for line in inv.inventory_line_id:
1957 pid = line.product_id.id
1959 # price = line.product_id.standard_price or 0.0
1960 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
1961 change = line.product_qty - amount
1962 lot_id = line.prod_lot_id.id
1964 location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
1966 'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
1967 'product_id': line.product_id.id,
1968 'product_uom': line.product_uom.id,
1969 'prodlot_id': lot_id,
1971 'date_planned': inv.date,
1976 'product_qty': change,
1977 'location_id': location_id,
1978 'location_dest_id': line.location_id.id,
1982 'product_qty': -change,
1983 'location_id': line.location_id.id,
1984 'location_dest_id': location_id,
1988 'prodlot_id': lot_id,
1989 'product_qty': line.product_qty
1991 move_ids.append(self._inventory_line_hook(cr, uid, line, value))
1993 self.pool.get('stock.move').action_done(cr, uid, move_ids,
1995 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
1998 def action_cancel(self, cr, uid, ids, context={}):
1999 for inv in self.browse(cr, uid, ids):
2000 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2001 self.write(cr, uid, [inv.id], {'state': 'draft'})
2004 def action_cancel_inventary(self, cr, uid, ids, context={}):
2005 for inv in self.browse(cr,uid,ids):
2006 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2007 self.write(cr, uid, [inv.id], {'state':'cancel'})
2013 class stock_inventory_line(osv.osv):
2014 _name = "stock.inventory.line"
2015 _description = "Inventory line"
2017 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2018 'location_id': fields.many2one('stock.location', 'Location', required=True),
2019 'product_id': fields.many2one('product.product', 'Product', required=True),
2020 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
2021 'product_qty': fields.float('Quantity'),
2022 'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
2023 'prod_lot_id': fields.many2one('stock.production.lot', 'Production Lot', domain="[('product_id','=',product_id)]"),
2024 'state': fields.related('inventory_id','state',type='char',string='State',readonly=True),
2027 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
2031 prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
2032 uom = prod.uom_id.id
2033 amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
2034 result = {'product_qty': amount, 'product_uom': uom}
2035 return {'value': result}
2037 stock_inventory_line()
2040 #----------------------------------------------------------
2042 #----------------------------------------------------------
2043 class stock_warehouse(osv.osv):
2044 _name = "stock.warehouse"
2045 _description = "Warehouse"
2047 'name': fields.char('Name', size=60, required=True),
2048 # 'partner_id': fields.many2one('res.partner', 'Owner'),
2049 'company_id': fields.many2one('res.company','Company',required=True,select=1),
2050 'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
2051 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True),
2052 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True),
2053 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True),
2056 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2062 # get confirm or assign stock move lines of partner and put in current picking.
2063 class stock_picking_move_wizard(osv.osv_memory):
2064 _name = 'stock.picking.move.wizard'
2066 def _get_picking(self, cr, uid, ctx):
2067 if ctx.get('action_id', False):
2068 return ctx['action_id']
2071 def _get_picking_address(self, cr, uid, ctx):
2072 picking_obj = self.pool.get('stock.picking')
2073 if ctx.get('action_id', False):
2074 picking = picking_obj.browse(cr, uid, [ctx['action_id']])[0]
2075 return picking.address_id and picking.address_id.id or False
2079 'name': fields.char('Name', size=64, invisible=True),
2080 #'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines',readonly=True),
2081 'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Entry lines', required=True),
2082 'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
2083 'picking_id': fields.many2one('stock.picking', 'Picking list', select=True, invisible=True),
2086 'picking_id': _get_picking,
2087 'address_id': _get_picking_address,
2090 def action_move(self, cr, uid, ids, context=None):
2091 move_obj = self.pool.get('stock.move')
2092 picking_obj = self.pool.get('stock.picking')
2093 for act in self.read(cr, uid, ids):
2094 move_lines = move_obj.browse(cr, uid, act['move_ids'])
2095 for line in move_lines:
2097 picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2098 picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2099 old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
2100 if not len(old_picking['move_lines']):
2101 picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
2103 raise osv.except_osv(_('UserError'),
2104 _('You can not create new moves.'))
2105 return {'type': 'ir.actions.act_window_close'}
2107 stock_picking_move_wizard()
2109 class report_products_to_received_planned(osv.osv):
2110 _name = "report.products.to.received.planned"
2111 _description = "Product to Received Vs Planned"
2114 'date':fields.date('Date'),
2115 'qty': fields.integer('Actual Qty'),
2116 'planned_qty': fields.integer('Planned Qty'),
2121 tools.drop_view_if_exists(cr, 'report_products_to_received_planned')
2123 create or replace view report_products_to_received_planned as (
2124 select stock.date, min(stock.id), sum(stock.product_qty) as qty, 0 as planned_qty
2125 from stock_picking picking
2126 inner join stock_move stock
2127 on picking.id = stock.picking_id and picking.type = 'in'
2128 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2133 select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2134 from stock_picking picking
2135 inner join stock_move stock
2136 on picking.id = stock.picking_id and picking.type = 'in'
2137 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)
2138 group by stock.date_planned
2141 report_products_to_received_planned()
2143 class report_delivery_products_planned(osv.osv):
2144 _name = "report.delivery.products.planned"
2145 _description = "Number of Delivery products vs planned"
2148 'date':fields.date('Date'),
2149 'qty': fields.integer('Actual Qty'),
2150 'planned_qty': fields.integer('Planned Qty'),
2155 tools.drop_view_if_exists(cr, 'report_delivery_products_planned')
2157 create or replace view report_delivery_products_planned as (
2158 select stock.date, min(stock.id), sum(stock.product_qty) as qty, 0 as planned_qty
2159 from stock_picking picking
2160 inner join stock_move stock
2161 on picking.id = stock.picking_id and picking.type = 'out'
2162 where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2167 select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2168 from stock_picking picking
2169 inner join stock_move stock
2170 on picking.id = stock.picking_id and picking.type = 'out'
2171 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)
2172 group by stock.date_planned
2177 report_delivery_products_planned()
2178 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: