1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
23 from mx import DateTime
26 from osv import fields, osv
27 from tools import config
28 from tools.translate import _
32 #----------------------------------------------------------
34 #----------------------------------------------------------
35 class stock_incoterms(osv.osv):
36 _name = "stock.incoterms"
37 _description = "Incoterms"
39 'name': fields.char('Name', size=64, required=True),
40 'code': fields.char('Code', size=3, required=True),
41 'active': fields.boolean('Active'),
44 'active': lambda *a: True,
50 #----------------------------------------------------------
52 #----------------------------------------------------------
53 class stock_location(osv.osv):
54 _name = "stock.location"
55 _description = "Location"
56 _parent_name = "location_id"
59 _order = 'parent_left'
61 def _complete_name(self, cr, uid, ids, name, args, context):
62 def _get_one_full_name(location, level=4):
63 if location.location_id:
64 parent_path = _get_one_full_name(location.location_id, level-1) + "/"
67 return parent_path + location.name
69 for m in self.browse(cr, uid, ids, context=context):
70 res[m.id] = _get_one_full_name(m)
73 def _product_qty_available(self, cr, uid, ids, field_names, arg, context={}):
76 res[id] = {}.fromkeys(field_names, 0.0)
77 if ('product_id' not in context) or not ids:
79 #location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
81 context['location'] = [loc]
82 prod = self.pool.get('product.product').browse(cr, uid, context['product_id'], context)
83 if 'stock_real' in field_names:
84 res[loc]['stock_real'] = prod.qty_available
85 if 'stock_virtual' in field_names:
86 res[loc]['stock_virtual'] = prod.virtual_available
89 def product_detail(self, cr, uid, id, field, context={}):
93 field_to_read = 'virtual_available'
94 if field == 'stock_real_value':
95 field_to_read = 'qty_available'
96 cr.execute('select distinct product_id from stock_move where (location_id=%s) or (location_dest_id=%s)', (id, id))
97 result = cr.dictfetchall()
100 c = (context or {}).copy()
102 product = self.pool.get('product.product').read(cr, uid, r['product_id'], [field_to_read, 'standard_price'], context=c)
103 final_value += (product[field_to_read] * product['standard_price'])
106 def _product_value(self, cr, uid, ids, field_names, arg, context={}):
109 result[id] = {}.fromkeys(field_names, 0.0)
110 for field_name in field_names:
112 ret_dict = self.product_detail(cr, uid, loc, field=field_name)
113 result[loc][field_name] = ret_dict
117 'name': fields.char('Location Name', size=64, required=True, translate=True),
118 'active': fields.boolean('Active'),
119 'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production')], 'Location Type', required=True),
120 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
122 'complete_name': fields.function(_complete_name, method=True, type='char', size=100, string="Location Name"),
124 'stock_real': fields.function(_product_qty_available, method=True, type='float', string='Real Stock', multi="stock"),
125 'stock_virtual': fields.function(_product_qty_available, method=True, type='float', string='Virtual Stock', multi="stock"),
127 'account_id': fields.many2one('account.account', string='Inventory Account', domain=[('type', '!=', 'view')]),
128 'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
129 'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
131 'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
132 'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
133 'Chained Location Type', required=True),
134 'chained_auto_packing': fields.selection(
135 [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
138 help="This is used only if you selected a chained location type.\n" \
139 "The 'Automatic Move' value will create a stock move after the current one that will be "\
140 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
141 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
143 'chained_delay': fields.integer('Chained Delay (days)'),
144 'address_id': fields.many2one('res.partner.address', 'Location Address'),
145 'icon': fields.selection(tools.icons, 'Icon', size=64),
147 'comment': fields.text('Additional Information'),
148 'posx': fields.integer('Corridor (X)'),
149 'posy': fields.integer('Shelves (Y)'),
150 'posz': fields.integer('Height (Z)'),
152 'parent_left': fields.integer('Left Parent', select=1),
153 'parent_right': fields.integer('Right Parent', select=1),
154 'stock_real_value': fields.function(_product_value, method=True, type='float', string='Real Stock Value', multi="stock"),
155 'stock_virtual_value': fields.function(_product_value, method=True, type='float', string='Virtual Stock Value', multi="stock"),
158 'active': lambda *a: 1,
159 'usage': lambda *a: 'internal',
160 'allocation_method': lambda *a: 'fifo',
161 'chained_location_type': lambda *a: 'none',
162 'chained_auto_packing': lambda *a: 'manual',
163 'posx': lambda *a: 0,
164 'posy': lambda *a: 0,
165 'posz': lambda *a: 0,
166 'icon': lambda *a: False
169 def chained_location_get(self, cr, uid, location, partner=None, product=None, context={}):
171 if location.chained_location_type == 'customer':
173 result = partner.property_stock_customer
174 elif location.chained_location_type == 'fixed':
175 result = location.chained_location_id
177 return result, location.chained_auto_packing, location.chained_delay
180 def picking_type_get(self, cr, uid, from_location, to_location, context={}):
182 if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
184 elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage=='internal'):
188 def _product_get_all_report(self, cr, uid, ids, product_ids=False,
190 return self._product_get_report(cr, uid, ids, product_ids, context,
193 def _product_get_report(self, cr, uid, ids, product_ids=False,
194 context=None, recursive=False):
197 product_obj = self.pool.get('product.product')
199 product_ids = product_obj.search(cr, uid, [])
201 products = product_obj.browse(cr, uid, product_ids, context=context)
204 for product in products:
205 products_by_uom.setdefault(product.uom_id.id, [])
206 products_by_uom[product.uom_id.id].append(product)
207 products_by_id.setdefault(product.id, [])
208 products_by_id[product.id] = product
211 result['product'] = []
215 for uom_id in products_by_uom.keys():
216 fnc = self._product_get
218 fnc = self._product_all_get
221 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
223 for product_id in qty.keys():
224 if not qty[product_id]:
226 product = products_by_id[product_id]
227 quantity_total += qty[product_id]
228 price = qty[product_id] * product.standard_price
230 result['product'].append({
231 'price': product.standard_price,
232 'prod_name': product.name,
233 'code': product.default_code, # used by lot_overview_all report!
234 'variants': product.variants or '',
235 'uom': product.uom_id.name,
236 'prod_qty': qty[product_id],
237 'price_value': price,
239 result['total'] = quantity_total
240 result['total_price'] = total_price
243 def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context={}, states=['done'], what=('in', 'out')):
244 product_obj = self.pool.get('product.product')
250 return product_obj.get_product_available(cr, uid, product_ids, context=context)
252 def _product_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
253 ids = id and [id] or []
254 return self._product_get_multi_location(cr, uid, ids, product_ids, context, states)
256 def _product_all_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
257 # build the list of ids of children of the location given by id
258 ids = id and [id] or []
259 location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
260 return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
262 def _product_virtual_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
263 return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
267 # Improve this function
270 # [ (tracking_id, product_qty, location_id) ]
272 def _product_reserve(self, cr, uid, ids, product_id, product_qty, context={}):
275 for id in self.search(cr, uid, [('location_id', 'child_of', ids)]):
276 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))
277 results = cr.dictfetchall()
278 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))
279 results += cr.dictfetchall()
284 amount = self.pool.get('product.uom')._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
293 if amount > min(total, product_qty):
294 amount = min(product_qty, total)
295 result.append((amount, id))
296 product_qty -= amount
298 if product_qty <= 0.0:
307 class stock_tracking(osv.osv):
308 _name = "stock.tracking"
309 _description = "Stock Tracking Lots"
312 salt = '31' * 8 + '3'
314 for sscc_part, salt_part in zip(sscc, salt):
315 sum += int(sscc_part) * int(salt_part)
316 return (10 - (sum % 10)) % 10
317 checksum = staticmethod(checksum)
319 def make_sscc(self, cr, uid, context={}):
320 sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
321 return sequence + str(self.checksum(sequence))
324 'name': fields.char('Tracking', size=64, required=True),
325 'active': fields.boolean('Active'),
326 'serial': fields.char('Reference', size=64),
327 'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves Tracked'),
328 'date': fields.datetime('Date Created', required=True),
331 'active': lambda *a: 1,
333 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
336 def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
341 ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
342 ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
343 return self.name_get(cr, user, ids, context)
345 def name_get(self, cr, uid, ids, context={}):
348 res = [(r['id'], r['name']+' ['+(r['serial'] or '')+']') for r in self.read(cr, uid, ids, ['name', 'serial'], context)]
351 def unlink(self, cr, uid, ids, context=None):
352 raise osv.except_osv(_('Error'), _('You can not remove a lot line !'))
357 #----------------------------------------------------------
359 #----------------------------------------------------------
360 class stock_picking(osv.osv):
361 _name = "stock.picking"
362 _description = "Packing List"
364 def _set_maximum_date(self, cr, uid, ids, name, value, arg, context):
367 if isinstance(ids, (int, long)):
369 for pick in self.browse(cr, uid, ids, context):
370 sql_str = """update stock_move set
373 picking_id=%d """ % (value, pick.id)
376 sql_str += " and (date_planned='" + pick.max_date + "' or date_planned>'" + value + "')"
380 def _set_minimum_date(self, cr, uid, ids, name, value, arg, context):
383 if isinstance(ids, (int, long)):
385 for pick in self.browse(cr, uid, ids, context):
386 sql_str = """update stock_move set
389 picking_id=%s """ % (value, pick.id)
391 sql_str += " and (date_planned='" + pick.min_date + "' or date_planned<'" + value + "')"
395 def get_min_max_date(self, cr, uid, ids, field_name, arg, context={}):
398 res[id] = {'min_date': False, 'max_date': False}
408 picking_id in (""" + ','.join(map(str, ids)) + """)
411 for pick, dt1, dt2 in cr.fetchall():
412 res[pick]['min_date'] = dt1
413 res[pick]['max_date'] = dt2
416 def create(self, cr, user, vals, context=None):
417 if ('name' not in vals) or (vals.get('name')=='/'):
418 vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking')
420 return super(stock_picking, self).create(cr, user, vals, context)
423 'name': fields.char('Reference', size=64, select=True),
424 'origin': fields.char('Origin Reference', size=64),
425 'backorder_id': fields.many2one('stock.picking', 'Back Order'),
426 'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('delivery', 'Delivery')], 'Shipping Type', required=True, select=True),
427 'active': fields.boolean('Active'),
428 'note': fields.text('Notes'),
430 'location_id': fields.many2one('stock.location', 'Location'),
431 'location_dest_id': fields.many2one('stock.location', 'Dest. Location'),
432 'move_type': fields.selection([('direct', 'Direct Delivery'), ('one', 'All at once')], 'Delivery Method', required=True),
433 'state': fields.selection([
436 ('confirmed', 'Confirmed'),
437 ('assigned', 'Available'),
439 ('cancel', 'Canceled'),
440 ], 'Status', readonly=True, select=True),
441 'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
442 method=True, store=True, type='datetime', string='Planned Date', select=1),
443 'date': fields.datetime('Date Order'),
444 'date_done': fields.datetime('Date Done'),
445 'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
446 method=True, store=True, type='datetime', string='Max. Planned Date', select=2),
447 'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
448 'auto_picking': fields.boolean('Auto-Packing'),
449 'address_id': fields.many2one('res.partner.address', 'Partner'),
450 'invoice_state': fields.selection([
451 ("invoiced", "Invoiced"),
452 ("2binvoiced", "To Be Invoiced"),
453 ("none", "Not from Packing")], "Invoice Status",
454 select=True, required=True, readonly=True, states={'draft': [('readonly', False)]}),
457 'name': lambda self, cr, uid, context: '/',
458 'active': lambda *a: 1,
459 'state': lambda *a: 'draft',
460 'move_type': lambda *a: 'direct',
461 'type': lambda *a: 'in',
462 'invoice_state': lambda *a: 'none',
463 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
466 def copy(self, cr, uid, id, default=None, context={}):
469 default = default.copy()
470 default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking')
471 return super(stock_picking, self).copy(cr, uid, id, default, context)
473 def onchange_partner_in(self, cr, uid, context, partner_id=None):
476 def action_explode(self, cr, uid, moves, context={}):
479 def action_confirm(self, cr, uid, ids, context={}):
480 self.write(cr, uid, ids, {'state': 'confirmed'})
482 for picking in self.browse(cr, uid, ids):
483 for r in picking.move_lines:
484 if r.state == 'draft':
486 todo = self.action_explode(cr, uid, todo, context)
488 self.pool.get('stock.move').action_confirm(cr, uid, todo, context)
491 def test_auto_picking(self, cr, uid, ids):
492 # TODO: Check locations to see if in the same location ?
495 def button_confirm(self, cr, uid, ids, *args):
497 wf_service = netsvc.LocalService("workflow")
498 wf_service.trg_validate(uid, 'stock.picking', id, 'button_confirm', cr)
499 self.force_assign(cr, uid, ids, *args)
502 def action_assign(self, cr, uid, ids, *args):
503 for pick in self.browse(cr, uid, ids):
504 move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
505 self.pool.get('stock.move').action_assign(cr, uid, move_ids)
508 def force_assign(self, cr, uid, ids, *args):
509 wf_service = netsvc.LocalService("workflow")
510 for pick in self.browse(cr, uid, ids):
511 # move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
512 move_ids = [x.id for x in pick.move_lines]
513 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
514 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
517 def draft_force_assign(self, cr, uid, ids, *args):
518 wf_service = netsvc.LocalService("workflow")
519 for pick in self.browse(cr, uid, ids):
520 wf_service.trg_validate(uid, 'stock.picking', pick.id,
521 'button_confirm', cr)
522 #move_ids = [x.id for x in pick.move_lines]
523 #self.pool.get('stock.move').force_assign(cr, uid, move_ids)
524 #wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
527 def draft_validate(self, cr, uid, ids, *args):
528 wf_service = netsvc.LocalService("workflow")
529 self.draft_force_assign(cr, uid, ids)
530 for pick in self.browse(cr, uid, ids):
531 move_ids = [x.id for x in pick.move_lines]
532 self.pool.get('stock.move').force_assign(cr, uid, move_ids)
533 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
535 self.action_move(cr, uid, [pick.id])
536 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
539 def cancel_assign(self, cr, uid, ids, *args):
540 wf_service = netsvc.LocalService("workflow")
541 for pick in self.browse(cr, uid, ids):
542 move_ids = [x.id for x in pick.move_lines]
543 self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
544 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
547 def action_assign_wkf(self, cr, uid, ids):
548 self.write(cr, uid, ids, {'state': 'assigned'})
551 def test_finnished(self, cr, uid, ids):
552 move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
553 for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
554 if move.state not in ('done', 'cancel'):
555 if move.product_qty != 0.0:
558 move.write(cr, uid, [move.id], {'state': 'done'})
561 def test_assigned(self, cr, uid, ids):
563 for pick in self.browse(cr, uid, ids):
565 for move in pick.move_lines:
566 if (move.state in ('confirmed', 'draft')) and (mt=='one'):
568 if (mt=='direct') and (move.state=='assigned') and (move.product_qty):
570 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
573 def action_cancel(self, cr, uid, ids, context={}):
574 for pick in self.browse(cr, uid, ids):
575 ids2 = [move.id for move in pick.move_lines]
576 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
577 self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
581 # TODO: change and create a move if not parents
583 def action_done(self, cr, uid, ids, context=None):
584 self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
587 def action_move(self, cr, uid, ids, context={}):
588 for pick in self.browse(cr, uid, ids):
590 for move in pick.move_lines:
591 if move.state == 'assigned':
595 self.pool.get('stock.move').action_done(cr, uid, todo,
599 def get_currency_id(self, cursor, user, picking):
602 def _get_payment_term(self, cursor, user, picking):
603 '''Return {'contact': address, 'invoice': address} for invoice'''
604 partner_obj = self.pool.get('res.partner')
605 partner = picking.address_id.partner_id
606 return partner.property_payment_term and partner.property_payment_term.id or False
608 def _get_address_invoice(self, cursor, user, picking):
609 '''Return {'contact': address, 'invoice': address} for invoice'''
610 partner_obj = self.pool.get('res.partner')
611 partner = picking.address_id.partner_id
613 return partner_obj.address_get(cursor, user, [partner.id],
614 ['contact', 'invoice'])
616 def _get_comment_invoice(self, cursor, user, picking):
617 '''Return comment string for invoice'''
618 return picking.note or ''
620 def _get_price_unit_invoice(self, cursor, user, move_line, type):
621 '''Return the price unit for the move line'''
622 if type in ('in_invoice', 'in_refund'):
623 return move_line.product_id.standard_price
625 return move_line.product_id.list_price
627 def _get_discount_invoice(self, cursor, user, move_line):
628 '''Return the discount for the move line'''
631 def _get_taxes_invoice(self, cursor, user, move_line, type):
632 '''Return taxes ids for the move line'''
633 if type in ('in_invoice', 'in_refund'):
634 taxes = move_line.product_id.supplier_taxes_id
636 taxes = move_line.product_id.taxes_id
638 if move_line.picking_id and move_line.picking_id.address_id and move_line.picking_id.address_id.partner_id:
639 return self.pool.get('account.fiscal.position').map_tax(
642 move_line.picking_id.address_id.partner_id.property_account_position,
646 return map(lambda x: x.id, taxes)
648 def _get_account_analytic_invoice(self, cursor, user, picking, move_line):
651 def _invoice_line_hook(self, cursor, user, move_line, invoice_line_id):
652 '''Call after the creation of the invoice line'''
655 def _invoice_hook(self, cursor, user, picking, invoice_id):
656 '''Call after the creation of the invoice'''
659 def action_invoice_create(self, cursor, user, ids, journal_id=False,
660 group=False, type='out_invoice', context=None):
661 '''Return ids of created invoices for the pickings'''
662 invoice_obj = self.pool.get('account.invoice')
663 invoice_line_obj = self.pool.get('account.invoice.line')
667 for picking in self.browse(cursor, user, ids, context=context):
668 if picking.invoice_state != '2binvoiced':
670 payment_term_id = False
671 partner = picking.address_id and picking.address_id.partner_id
673 raise osv.except_osv(_('Error, no partner !'),
674 _('Please put a partner on the picking list if you want to generate invoice.'))
676 if type in ('out_invoice', 'out_refund'):
677 account_id = partner.property_account_receivable.id
678 payment_term_id = self._get_payment_term(cursor, user, picking)
680 account_id = partner.property_account_payable.id
682 address_contact_id, address_invoice_id = \
683 self._get_address_invoice(cursor, user, picking).values()
685 comment = self._get_comment_invoice(cursor, user, picking)
686 if group and partner.id in invoices_group:
687 invoice_id = invoices_group[partner.id]
688 invoice = invoice_obj.browse(cursor, user, invoice_id)
690 'name': (invoice.name or '') + ', ' + (picking.name or ''),
691 'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
692 'comment': (comment and (invoice.comment and invoice.comment+"\n"+comment or comment)) or (invoice.comment and invoice.comment or ''),
694 invoice_obj.write(cursor, user, [invoice_id], invoice_vals, context=context)
697 'name': picking.name,
698 'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
700 'account_id': account_id,
701 'partner_id': partner.id,
702 'address_invoice_id': address_invoice_id,
703 'address_contact_id': address_contact_id,
705 'payment_term': payment_term_id,
706 'fiscal_position': partner.property_account_position.id
708 cur_id = self.get_currency_id(cursor, user, picking)
710 invoice_vals['currency_id'] = cur_id
712 invoice_vals['journal_id'] = journal_id
713 invoice_id = invoice_obj.create(cursor, user, invoice_vals,
715 invoices_group[partner.id] = invoice_id
716 res[picking.id] = invoice_id
717 for move_line in picking.move_lines:
718 origin = move_line.picking_id.name
719 if move_line.picking_id.origin:
720 origin += ':' + move_line.picking_id.origin
722 name = (picking.name or '') + '-' + move_line.name
724 name = move_line.name
726 if type in ('out_invoice', 'out_refund'):
727 account_id = move_line.product_id.product_tmpl_id.\
728 property_account_income.id
730 account_id = move_line.product_id.categ_id.\
731 property_account_income_categ.id
733 account_id = move_line.product_id.product_tmpl_id.\
734 property_account_expense.id
736 account_id = move_line.product_id.categ_id.\
737 property_account_expense_categ.id
739 price_unit = self._get_price_unit_invoice(cursor, user,
741 discount = self._get_discount_invoice(cursor, user, move_line)
742 tax_ids = self._get_taxes_invoice(cursor, user, move_line, type)
743 account_analytic_id = self._get_account_analytic_invoice(cursor,
744 user, picking, move_line)
746 account_id = self.pool.get('account.fiscal.position').map_account(cursor, user, partner.property_account_position, account_id)
747 invoice_line_id = invoice_line_obj.create(cursor, user, {
750 'invoice_id': invoice_id,
751 'uos_id': move_line.product_uos.id,
752 'product_id': move_line.product_id.id,
753 'account_id': account_id,
754 'price_unit': price_unit,
755 'discount': discount,
756 'quantity': move_line.product_uos_qty or move_line.product_qty,
757 'invoice_line_tax_id': [(6, 0, tax_ids)],
758 'account_analytic_id': account_analytic_id,
760 self._invoice_line_hook(cursor, user, move_line, invoice_line_id)
762 invoice_obj.button_compute(cursor, user, [invoice_id], context=context,
763 set_total=(type in ('in_invoice', 'in_refund')))
764 self.write(cursor, user, [picking.id], {
765 'invoice_state': 'invoiced',
767 self._invoice_hook(cursor, user, picking, invoice_id)
768 self.write(cursor, user, res.keys(), {
769 'invoice_state': 'invoiced',
773 def test_cancel(self, cr, uid, ids, context={}):
774 for pick in self.browse(cr, uid, ids, context=context):
775 if not pick.move_lines:
777 for move in pick.move_lines:
778 if move.state not in ('cancel',):
785 class stock_production_lot(osv.osv):
786 def name_get(self, cr, uid, ids, context={}):
789 reads = self.read(cr, uid, ids, ['name', 'ref'], context)
792 name = record['name']
794 name = name + '/' + record['ref']
795 res.append((record['id'], name))
798 _name = 'stock.production.lot'
799 _description = 'Production lot'
801 def _get_stock(self, cr, uid, ids, field_name, arg, context={}):
802 if 'location_id' not in context:
803 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
805 locations = context['location_id'] and [context['location_id']] or []
807 if isinstance(ids, (int, long)):
810 res = {}.fromkeys(ids, 0.0)
817 stock_report_prodlots
819 location_id in ('''+','.join(map(str, locations))+''') and
820 prodlot_id in ('''+','.join(map(str, ids))+''')
824 res.update(dict(cr.fetchall()))
827 def _stock_search(self, cr, uid, obj, name, args):
828 locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
833 stock_report_prodlots
835 location_id in ('''+','.join(map(str, locations)) + ''')
838 having sum(name) ''' + str(args[0][1]) + ''' ''' + str(args[0][2])
841 ids = [('id', 'in', map(lambda x: x[0], res))]
845 'name': fields.char('Serial', size=64, required=True),
846 'ref': fields.char('Internal Ref', size=64),
847 'product_id': fields.many2one('product.product', 'Product', required=True),
848 'date': fields.datetime('Created Date', required=True),
849 'stock_available': fields.function(_get_stock, fnct_search=_stock_search, method=True, type="float", string="Available", select="2"),
850 'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
853 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
854 'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
855 'product_id': lambda x, y, z, c: c.get('product_id', False),
858 ('name_ref_uniq', 'unique (name, ref)', 'The serial/ref must be unique !'),
861 stock_production_lot()
864 class stock_production_lot_revision(osv.osv):
865 _name = 'stock.production.lot.revision'
866 _description = 'Production lot revisions'
868 'name': fields.char('Revision Name', size=64, required=True),
869 'description': fields.text('Description'),
870 'date': fields.date('Revision Date'),
871 'indice': fields.char('Revision', size=16),
872 'author_id': fields.many2one('res.users', 'Author'),
873 'lot_id': fields.many2one('stock.production.lot', 'Production lot', select=True, ondelete='cascade'),
877 'author_id': lambda x, y, z, c: z,
878 'date': lambda *a: time.strftime('%Y-%m-%d'),
881 stock_production_lot_revision()
883 # ----------------------------------------------------
885 # ----------------------------------------------------
889 # location_dest_id is only used for predicting futur stocks
891 class stock_move(osv.osv):
892 def _getSSCC(self, cr, uid, context={}):
893 cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
895 return (res and res[0]) or False
897 _description = "Stock Move"
899 def name_get(self, cr, uid, ids, context={}):
901 for line in self.browse(cr, uid, ids, context):
902 res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))
905 def _check_tracking(self, cr, uid, ids):
906 for move in self.browse(cr, uid, ids):
907 if not move.prodlot_id and \
908 (move.state == 'done' and \
910 (move.product_id.track_production and move.location_id.usage=='production') or \
911 (move.product_id.track_production and move.location_dest_id.usage=='production') or \
912 (move.product_id.track_incoming and move.location_id.usage=='supplier') or \
913 (move.product_id.track_outgoing and move.location_dest_id.usage=='customer') \
918 def _check_product_lot(self, cr, uid, ids):
919 for move in self.browse(cr, uid, ids):
920 if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):
925 'name': fields.char('Name', size=64, required=True, select=True),
926 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
928 'date': fields.datetime('Date Created'),
929 'date_planned': fields.datetime('Date', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
931 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
933 'product_qty': fields.float('Quantity', required=True),
934 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
935 'product_uos_qty': fields.float('Quantity (UOS)'),
936 'product_uos': fields.many2one('product.uom', 'Product UOS'),
937 'product_packaging': fields.many2one('product.packaging', 'Packaging'),
939 'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True),
940 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, select=True),
941 'address_id': fields.many2one('res.partner.address', 'Dest. Address'),
943 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="Production lot is used to put a serial number on the production"),
944 '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"),
945 # 'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),
947 'auto_validate': fields.boolean('Auto Validate'),
949 'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),
950 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
951 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
952 'picking_id': fields.many2one('stock.picking', 'Packing List', select=True),
954 'note': fields.text('Notes'),
956 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Canceled')], 'Status', readonly=True, select=True),
957 'price_unit': fields.float('Unit Price',
958 digits=(16, int(config['price_accuracy']))),
962 'You must assign a production lot for this product',
965 'You try to assign a lot which is not from the same product',
968 def _default_location_destination(self, cr, uid, context={}):
969 if context.get('move_line', []):
970 if context['move_line'][0]:
971 if isinstance(context['move_line'][0], (tuple, list)):
972 return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
974 move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
975 return move_list and move_list['location_dest_id'][0] or False
976 if context.get('address_out_id', False):
977 return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id
980 def _default_location_source(self, cr, uid, context={}):
981 if context.get('move_line', []):
983 return context['move_line'][0][2]['location_id']
986 if context.get('address_in_id', False):
987 return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
991 'location_id': _default_location_source,
992 'location_dest_id': _default_location_destination,
993 'state': lambda *a: 'draft',
994 'priority': lambda *a: '1',
995 'product_qty': lambda *a: 1.0,
996 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
997 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1000 def _auto_init(self, cursor, context):
1001 res = super(stock_move, self)._auto_init(cursor, context)
1002 cursor.execute('SELECT indexname \
1004 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1005 if not cursor.fetchone():
1006 cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1007 ON stock_move (location_id, location_dest_id, product_id, state)')
1011 def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, context=None):
1012 if not prodlot_id or not loc_id:
1014 ctx = context and context.copy() or {}
1015 ctx['location_id'] = loc_id
1016 prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1017 location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1019 if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1021 'title': 'Bad Lot Assignation !',
1022 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1024 return {'warning': warning}
1026 def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False):
1029 product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0]
1031 'name': product.name,
1032 'product_uom': product.uom_id.id,
1035 result['location_id'] = loc_id
1037 result['location_dest_id'] = loc_dest_id
1038 return {'value': result}
1040 def _chain_compute(self, cr, uid, moves, context={}):
1043 dest = self.pool.get('stock.location').chained_location_get(
1047 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1052 if dest[1] == 'transparent':
1053 self.write(cr, uid, [m.id], {
1054 'date_planned': (DateTime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1055 DateTime.RelativeDateTime(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1056 'location_dest_id': dest[0].id})
1058 result.setdefault(m.picking_id, [])
1059 result[m.picking_id].append( (m, dest) )
1062 def action_confirm(self, cr, uid, ids, context={}):
1063 # ids = map(lambda m: m.id, moves)
1064 moves = self.browse(cr, uid, ids)
1065 self.write(cr, uid, ids, {'state': 'confirmed'})
1068 def create_chained_picking(self, cr, uid, moves, context):
1070 for picking, todo in self._chain_compute(cr, uid, moves, context).items():
1071 ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
1072 pickid = self.pool.get('stock.picking').create(cr, uid, {
1073 'name': picking.name,
1074 'origin': str(picking.origin or ''),
1076 'note': picking.note,
1077 'move_type': picking.move_type,
1078 'auto_picking': todo[0][1][1] == 'auto',
1079 'address_id': picking.address_id.id,
1080 'invoice_state': 'none'
1082 for move, (loc, auto, delay) in todo:
1083 # Is it smart to copy ? May be it's better to recreate ?
1084 new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {
1085 'location_id': move.location_dest_id.id,
1086 'location_dest_id': loc.id,
1087 'date_moved': time.strftime('%Y-%m-%d'),
1088 'picking_id': pickid,
1090 'move_history_ids': [],
1091 'date_planned': (DateTime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + DateTime.RelativeDateTime(days=delay or 0)).strftime('%Y-%m-%d'),
1092 'move_history_ids2': []}
1094 self.pool.get('stock.move').write(cr, uid, [move.id], {
1095 'move_dest_id': new_id,
1096 'move_history_ids': [(4, new_id)]
1098 new_moves.append(self.browse(cr, uid, [new_id])[0])
1099 wf_service = netsvc.LocalService("workflow")
1100 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1102 create_chained_picking(self, cr, uid, new_moves, context)
1103 create_chained_picking(self, cr, uid, moves, context)
1106 def action_assign(self, cr, uid, ids, *args):
1108 for move in self.browse(cr, uid, ids):
1109 if move.state in ('confirmed', 'waiting'):
1110 todo.append(move.id)
1111 res = self.check_assign(cr, uid, todo)
1114 def force_assign(self, cr, uid, ids, context={}):
1115 self.write(cr, uid, ids, {'state': 'assigned'})
1118 def cancel_assign(self, cr, uid, ids, context={}):
1119 self.write(cr, uid, ids, {'state': 'confirmed'})
1123 # Duplicate stock.move
1125 def check_assign(self, cr, uid, ids, context={}):
1129 for move in self.browse(cr, uid, ids):
1130 if move.product_id.type == 'consu':
1131 if move.state in ('confirmed', 'waiting'):
1132 done.append(move.id)
1133 pickings[move.picking_id.id] = 1
1135 if move.state in ('confirmed', 'waiting'):
1136 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})
1138 #_product_available_test depends on the next status for correct functioning
1139 #the test does not work correctly if the same product occurs multiple times
1140 #in the same order. This is e.g. the case when using the button 'split in two' of
1141 #the stock outgoing form
1142 self.write(cr, uid, move.id, {'state':'assigned'})
1143 done.append(move.id)
1144 pickings[move.picking_id.id] = 1
1146 cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1150 move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1151 done.append(move_id)
1152 #cr.execute('insert into stock_move_history_ids values (%s,%s)', (move.id,move_id))
1155 self.write(cr, uid, done, {'state': 'assigned'})
1158 for pick_id in pickings:
1159 wf_service = netsvc.LocalService("workflow")
1160 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1164 # Cancel move => cancel others move and pickings
1166 def action_cancel(self, cr, uid, ids, context={}):
1170 for move in self.browse(cr, uid, ids):
1171 if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1173 pickings[move.picking_id.id] = True
1174 if move.move_dest_id and move.move_dest_id.state == 'waiting':
1175 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1176 if move.move_dest_id.picking_id:
1177 wf_service = netsvc.LocalService("workflow")
1178 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1179 self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1181 for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1182 if all(move.state == 'cancel' for move in pick.move_lines):
1183 self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1185 wf_service = netsvc.LocalService("workflow")
1187 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1188 #self.action_cancel(cr,uid, ids2, context)
1191 def action_done(self, cr, uid, ids, context=None):
1193 for move in self.browse(cr, uid, ids):
1194 if move.move_dest_id.id and (move.state != 'done'):
1195 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1196 if move.move_dest_id.state in ('waiting', 'confirmed'):
1197 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1198 if move.move_dest_id.picking_id:
1199 wf_service = netsvc.LocalService("workflow")
1200 wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1203 # self.action_done(cr, uid, [move.move_dest_id.id])
1204 if move.move_dest_id.auto_validate:
1205 self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1208 # Accounting Entries
1212 if move.location_id.account_id:
1213 acc_src = move.location_id.account_id.id
1214 if move.location_dest_id.account_id:
1215 acc_dest = move.location_dest_id.account_id.id
1216 if acc_src or acc_dest:
1217 test = [('product.product', move.product_id.id)]
1218 if move.product_id.categ_id:
1219 test.append( ('product.category', move.product_id.categ_id.id) )
1221 acc_src = move.product_id.product_tmpl_id.\
1222 property_stock_account_input.id
1224 acc_src = move.product_id.categ_id.\
1225 property_stock_account_input_categ.id
1227 raise osv.except_osv(_('Error!'),
1228 _('There is no stock input account defined ' \
1229 'for this product: "%s" (id: %d)') % \
1230 (move.product_id.name,
1231 move.product_id.id,))
1233 acc_dest = move.product_id.product_tmpl_id.\
1234 property_stock_account_output.id
1236 acc_dest = move.product_id.categ_id.\
1237 property_stock_account_output_categ.id
1239 raise osv.except_osv(_('Error!'),
1240 _('There is no stock output account defined ' \
1241 'for this product: "%s" (id: %d)') % \
1242 (move.product_id.name,
1243 move.product_id.id,))
1244 if not move.product_id.categ_id.property_stock_journal.id:
1245 raise osv.except_osv(_('Error!'),
1246 _('There is no journal defined '\
1247 'on the product category: "%s" (id: %d)') % \
1248 (move.product_id.categ_id.name,
1249 move.product_id.categ_id.id,))
1250 journal_id = move.product_id.categ_id.property_stock_journal.id
1251 if acc_src != acc_dest:
1252 ref = move.picking_id and move.picking_id.name or False
1253 product_uom_obj = self.pool.get('product.uom')
1254 default_uom = move.product_id.uom_id.id
1255 q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1256 if move.product_id.cost_method == 'average' and move.price_unit:
1257 amount = q * move.price_unit
1259 amount = q * move.product_id.standard_price
1261 date = time.strftime('%Y-%m-%d')
1264 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
1268 'quantity': move.product_qty,
1269 'product_id': move.product_id and move.product_id.id or False,
1271 'account_id': acc_src,
1274 'partner_id': partner_id}),
1277 'product_id': move.product_id and move.product_id.id or False,
1278 'quantity': move.product_qty,
1280 'account_id': acc_dest,
1283 'partner_id': partner_id})
1285 self.pool.get('account.move').create(cr, uid, {
1287 'journal_id': journal_id,
1291 self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1292 wf_service = netsvc.LocalService("workflow")
1294 wf_service.trg_trigger(uid, 'stock.move', id, cr)
1297 def unlink(self, cr, uid, ids, context=None):
1298 for move in self.browse(cr, uid, ids, context=context):
1299 if move.state != 'draft':
1300 raise osv.except_osv(_('UserError'),
1301 _('You can only delete draft moves.'))
1302 return super(stock_move, self).unlink(
1303 cr, uid, ids, context=context)
1308 class stock_inventory(osv.osv):
1309 _name = "stock.inventory"
1310 _description = "Inventory"
1312 'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
1313 'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
1314 'date_done': fields.datetime('Date done'),
1315 'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
1316 'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
1317 'state': fields.selection( (('draft', 'Draft'), ('done', 'Done')), 'Status', readonly=True),
1320 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1321 'state': lambda *a: 'draft',
1325 # Update to support tracking
1327 def action_done(self, cr, uid, ids, context=None):
1328 for inv in self.browse(cr, uid, ids):
1331 for line in inv.inventory_line_id:
1332 pid = line.product_id.id
1333 price = line.product_id.standard_price or 0.0
1334 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
1335 change = line.product_qty - amount
1337 location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
1339 'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
1340 'product_id': line.product_id.id,
1341 'product_uom': line.product_uom.id,
1343 'date_planned': inv.date,
1348 'product_qty': change,
1349 'location_id': location_id,
1350 'location_dest_id': line.location_id.id,
1354 'product_qty': -change,
1355 'location_id': line.location_id.id,
1356 'location_dest_id': location_id,
1358 move_ids.append(self.pool.get('stock.move').create(cr, uid, value))
1360 self.pool.get('stock.move').action_done(cr, uid, move_ids,
1362 self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
1365 def action_cancel(self, cr, uid, ids, context={}):
1366 for inv in self.browse(cr, uid, ids):
1367 self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
1368 self.write(cr, uid, [inv.id], {'state': 'draft'})
1374 class stock_inventory_line(osv.osv):
1375 _name = "stock.inventory.line"
1376 _description = "Inventory line"
1378 'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
1379 'location_id': fields.many2one('stock.location', 'Location', required=True),
1380 'product_id': fields.many2one('product.product', 'Product', required=True),
1381 'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
1382 'product_qty': fields.float('Quantity')
1385 def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
1389 prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
1390 uom = prod.uom_id.id
1391 amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
1392 result = {'product_qty': amount, 'product_uom': uom}
1393 return {'value': result}
1395 stock_inventory_line()
1398 #----------------------------------------------------------
1400 #----------------------------------------------------------
1401 class stock_warehouse(osv.osv):
1402 _name = "stock.warehouse"
1403 _description = "Warehouse"
1405 'name': fields.char('Name', size=60, required=True),
1406 # 'partner_id': fields.many2one('res.partner', 'Owner'),
1407 'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
1408 'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True),
1409 'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True),
1410 'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True),
1417 # get confirm or assign stock move lines of partner and put in current picking.
1418 class stock_picking_move_wizard(osv.osv_memory):
1419 _name = 'stock.picking.move.wizard'
1421 def _get_picking(self, cr, uid, ctx):
1422 if ctx.get('action_id', False):
1423 return ctx['action_id']
1426 def _get_picking_address(self, cr, uid, ctx):
1427 picking_obj = self.pool.get('stock.picking')
1428 if ctx.get('action_id', False):
1429 picking = picking_obj.browse(cr, uid, [ctx['action_id']])[0]
1430 return picking.address_id and picking.address_id.id or False
1434 'name': fields.char('Name', size=64, invisible=True),
1435 #'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines',readonly=True),
1436 'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Move lines', required=True),
1437 'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
1438 'picking_id': fields.many2one('stock.picking', 'Packing list', select=True, invisible=True),
1441 'picking_id': _get_picking,
1442 'address_id': _get_picking_address,
1445 def action_move(self, cr, uid, ids, context=None):
1446 move_obj = self.pool.get('stock.move')
1447 picking_obj = self.pool.get('stock.picking')
1448 for act in self.read(cr, uid, ids):
1449 move_lines = move_obj.browse(cr, uid, act['move_ids'])
1450 for line in move_lines:
1452 picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
1453 picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
1455 old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
1456 if not len(old_picking['move_lines']):
1457 picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
1459 raise osv.except_osv(_('UserError'),
1460 _('You can not create new moves.'))
1461 return {'type': 'ir.actions.act_window_close'}
1463 stock_picking_move_wizard()
1466 class report_stock_lines_date(osv.osv):
1467 _name = "report.stock.lines.date"
1468 _description = "Dates of Inventories"
1471 'id': fields.integer('Inventory Line Id', readonly=True),
1472 'product_id': fields.integer('Product Id', readonly=True),
1473 'create_date': fields.datetime('Latest Date of Inventory'),
1478 create or replace view report_stock_lines_date as (
1482 max(l.create_date) as create_date
1486 stock_inventory_line l on (p.id=l.product_id)
1487 where l.create_date is not null
1491 report_stock_lines_date()