[fix] missed corrections
[odoo/odoo.git] / addons / stock / stock.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
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.
12 #
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.
17 #
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/>.
20 #
21 ##############################################################################
22
23 from mx import DateTime
24 import time
25 import netsvc
26 from osv import fields, osv
27 from tools import config
28 from tools.translate import _
29 import tools
30
31
32 #----------------------------------------------------------
33 # Incoterms
34 #----------------------------------------------------------
35 class stock_incoterms(osv.osv):
36     _name = "stock.incoterms"
37     _description = "Incoterms"
38     _columns = {
39         'name': fields.char('Name', size=64, required=True),
40         'code': fields.char('Code', size=3, required=True),
41         'active': fields.boolean('Active'),
42     }
43     _defaults = {
44         'active': lambda *a: True,
45     }
46
47 stock_incoterms()
48
49
50 #----------------------------------------------------------
51 # Stock Location
52 #----------------------------------------------------------
53 class stock_location(osv.osv):
54     _name = "stock.location"
55     _description = "Location"
56     _parent_name = "location_id"
57     _parent_store = True
58     _parent_order = 'id'
59     _order = 'parent_left'
60
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) + "/"
65             else:
66                 parent_path = ''
67             return parent_path + location.name
68         res = {}
69         for m in self.browse(cr, uid, ids, context=context):
70             res[m.id] = _get_one_full_name(m)
71         return res
72
73     def _product_qty_available(self, cr, uid, ids, field_names, arg, context={}):
74         res = {}
75         for id in ids:
76             res[id] = {}.fromkeys(field_names, 0.0)
77         if ('product_id' not in context) or not ids:
78             return res
79         #location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
80         for loc in 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
87         return res
88
89     def product_detail(self, cr, uid, id, field, context={}):
90         res = {}
91         res[id] = {}
92         final_value = 0.0
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()
98         if result:
99             for r in result:
100                 c = (context or {}).copy()
101                 c['location'] = id
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'])
104         return final_value
105
106     def _product_value(self, cr, uid, ids, field_names, arg, context={}):
107         result = {}
108         for id in ids:
109             result[id] = {}.fromkeys(field_names, 0.0)
110         for field_name in field_names:
111             for loc in ids:
112                 ret_dict = self.product_detail(cr, uid, loc, field=field_name)
113                 result[loc][field_name] = ret_dict
114         return result
115
116     _columns = {
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),
121
122         'complete_name': fields.function(_complete_name, method=True, type='char', size=100, string="Location Name"),
123
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"),
126
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'),
130
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')],
136             'Automatic Move',
137             required=True,
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."
142             ),
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),
146
147         'comment': fields.text('Additional Information'),
148         'posx': fields.integer('Corridor (X)'),
149         'posy': fields.integer('Shelves (Y)'),
150         'posz': fields.integer('Height (Z)'),
151
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"),
156     }
157     _defaults = {
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
167     }
168
169     def chained_location_get(self, cr, uid, location, partner=None, product=None, context={}):
170         result = None
171         if location.chained_location_type == 'customer':
172             if partner:
173                 result = partner.property_stock_customer
174         elif location.chained_location_type == 'fixed':
175             result = location.chained_location_id
176         if result:
177             return result, location.chained_auto_packing, location.chained_delay
178         return result
179
180     def picking_type_get(self, cr, uid, from_location, to_location, context={}):
181         result = 'internal'
182         if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
183             result = 'delivery'
184         elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage=='internal'):
185             result = 'in'
186         return result
187
188     def _product_get_all_report(self, cr, uid, ids, product_ids=False,
189             context=None):
190         return self._product_get_report(cr, uid, ids, product_ids, context,
191                 recursive=True)
192
193     def _product_get_report(self, cr, uid, ids, product_ids=False,
194             context=None, recursive=False):
195         if context is None:
196             context = {}
197         product_obj = self.pool.get('product.product')
198         if not product_ids:
199             product_ids = product_obj.search(cr, uid, [])
200
201         products = product_obj.browse(cr, uid, product_ids, context=context)
202         products_by_uom = {}
203         products_by_id = {}
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
209
210         result = {}
211         result['product'] = []
212         for id in ids:
213             quantity_total = 0.0
214             total_price = 0.0
215             for uom_id in products_by_uom.keys():
216                 fnc = self._product_get
217                 if recursive:
218                     fnc = self._product_all_get
219                 ctx = context.copy()
220                 ctx['uom'] = uom_id
221                 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
222                         context=ctx)
223                 for product_id in qty.keys():
224                     if not qty[product_id]:
225                         continue
226                     product = products_by_id[product_id]
227                     quantity_total += qty[product_id]
228                     price = qty[product_id] * product.standard_price
229                     total_price += 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,
238                     })
239         result['total'] = quantity_total
240         result['total_price'] = total_price
241         return result
242
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')
245         context.update({
246             'states': states,
247             'what': what,
248             'location': ids
249         })
250         return product_obj.get_product_available(cr, uid, product_ids, context=context)
251
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)
255
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)
261
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'])
264
265     #
266     # TODO:
267     #    Improve this function
268     #
269     # Returns:
270     #    [ (tracking_id, product_qty, location_id) ]
271     #
272     def _product_reserve(self, cr, uid, ids, product_id, product_qty, context={}):
273         result = []
274         amount = 0.0
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()
280
281             total = 0.0
282             results2 = 0.0
283             for r in results:
284                 amount = self.pool.get('product.uom')._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
285                 results2 += amount
286                 total += amount
287
288             if total <= 0.0:
289                 continue
290
291             amount = results2
292             if amount > 0:
293                 if amount > min(total, product_qty):
294                     amount = min(product_qty, total)
295                 result.append((amount, id))
296                 product_qty -= amount
297                 total -= amount
298                 if product_qty <= 0.0:
299                     return result
300                 if total <= 0.0:
301                     continue
302         return False
303
304 stock_location()
305
306
307 class stock_tracking(osv.osv):
308     _name = "stock.tracking"
309     _description = "Stock Tracking Lots"
310
311     def checksum(sscc):
312         salt = '31' * 8 + '3'
313         sum = 0
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)
318
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))
322
323     _columns = {
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),
329     }
330     _defaults = {
331         'active': lambda *a: 1,
332         'name': make_sscc,
333         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
334     }
335
336     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):
337         if not args:
338             args = []
339         if not context:
340             context = {}
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)
344
345     def name_get(self, cr, uid, ids, context={}):
346         if not len(ids):
347             return []
348         res = [(r['id'], r['name']+' ['+(r['serial'] or '')+']') for r in self.read(cr, uid, ids, ['name', 'serial'], context)]
349         return res
350
351     def unlink(self, cr, uid, ids, context=None):
352         raise osv.except_osv(_('Error'), _('You can not remove a lot line !'))
353
354 stock_tracking()
355
356
357 #----------------------------------------------------------
358 # Stock Picking
359 #----------------------------------------------------------
360 class stock_picking(osv.osv):
361     _name = "stock.picking"
362     _description = "Packing List"
363
364     def _set_maximum_date(self, cr, uid, ids, name, value, arg, context):
365         if not value:
366             return False
367         if isinstance(ids, (int, long)):
368             ids = [ids]
369         for pick in self.browse(cr, uid, ids, context):
370             sql_str = """update stock_move set
371                     date_planned=%s
372                 where
373                     picking_id=%s """
374             sqlargs = (value, pick.id)
375
376             if pick.max_date:
377                 sql_str += " and (date_planned=%s or date_planned>%s)"
378                 sqlargs += (pick.max_date, value)
379             cr.execute(sql_str, sqlargs)
380         return True
381
382     def _set_minimum_date(self, cr, uid, ids, name, value, arg, context):
383         if not value:
384             return False
385         if isinstance(ids, (int, long)):
386             ids = [ids]
387         for pick in self.browse(cr, uid, ids, context):
388             sql_str = """update stock_move set
389                     date_planned=%s
390                 where
391                     picking_id=%s """
392             sqlargs = (value, pick.id)
393             if pick.min_date:
394                 sql_str += " and (date_planned=%s or date_planned<%s)"
395                 sqlargs += (pick.min_date, value)
396             cr.execute(sql_str, sqlargs)
397         return True
398
399     def get_min_max_date(self, cr, uid, ids, field_name, arg, context={}):
400         res = {}
401         for id in ids:
402             res[id] = {'min_date': False, 'max_date': False}
403         if not ids:
404             return res
405         cr.execute("""select
406                 picking_id,
407                 min(date_planned),
408                 max(date_planned)
409             from
410                 stock_move
411             where
412                 picking_id in %s
413             group by
414                 picking_id""", (tuple(ids),))
415         for pick, dt1, dt2 in cr.fetchall():
416             res[pick]['min_date'] = dt1
417             res[pick]['max_date'] = dt2
418         return res
419
420     def create(self, cr, user, vals, context=None):
421         if ('name' not in vals) or (vals.get('name')=='/'):
422             vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking')
423
424         return super(stock_picking, self).create(cr, user, vals, context)
425
426     _columns = {
427         'name': fields.char('Reference', size=64, select=True),
428         'origin': fields.char('Origin Reference', size=64),
429         'backorder_id': fields.many2one('stock.picking', 'Back Order'),
430         'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('delivery', 'Delivery')], 'Shipping Type', required=True, select=True),
431         'active': fields.boolean('Active'),
432         'note': fields.text('Notes'),
433
434         'location_id': fields.many2one('stock.location', 'Location'),
435         'location_dest_id': fields.many2one('stock.location', 'Dest. Location'),
436         'move_type': fields.selection([('direct', 'Direct Delivery'), ('one', 'All at once')], 'Delivery Method', required=True),
437         'state': fields.selection([
438             ('draft', 'Draft'),
439             ('auto', 'Waiting'),
440             ('confirmed', 'Confirmed'),
441             ('assigned', 'Available'),
442             ('done', 'Done'),
443             ('cancel', 'Cancelled'),
444             ], 'Status', readonly=True, select=True),
445         'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
446                  method=True, store=True, type='datetime', string='Planned Date', select=1),
447         'date': fields.datetime('Date Order'),
448         'date_done': fields.datetime('Date Done'),
449         'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
450                  method=True, store=True, type='datetime', string='Max. Planned Date', select=2),
451         'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines', states={'cancel': [('readonly', True)]}),
452         'auto_picking': fields.boolean('Auto-Packing'),
453         'address_id': fields.many2one('res.partner.address', 'Partner'),
454         'invoice_state': fields.selection([
455             ("invoiced", "Invoiced"),
456             ("2binvoiced", "To Be Invoiced"),
457             ("none", "Not from Packing")], "Invoice Status",
458             select=True, required=True, readonly=True, states={'draft': [('readonly', False)]}),
459     }
460     _defaults = {
461         'name': lambda self, cr, uid, context: '/',
462         'active': lambda *a: 1,
463         'state': lambda *a: 'draft',
464         'move_type': lambda *a: 'direct',
465         'type': lambda *a: 'in',
466         'invoice_state': lambda *a: 'none',
467         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
468     }
469
470     def copy(self, cr, uid, id, default=None, context={}):
471         if default is None:
472             default = {}
473         default = default.copy()
474         if not default.get('name',False):
475             default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking')
476         return super(stock_picking, self).copy(cr, uid, id, default, context)
477
478     def onchange_partner_in(self, cr, uid, context, partner_id=None):
479         return {}
480
481     def action_explode(self, cr, uid, moves, context={}):
482         return moves
483
484     def action_confirm(self, cr, uid, ids, context={}):
485         self.write(cr, uid, ids, {'state': 'confirmed'})
486         todo = []
487         for picking in self.browse(cr, uid, ids):
488             for r in picking.move_lines:
489                 if r.state == 'draft':
490                     todo.append(r.id)
491         todo = self.action_explode(cr, uid, todo, context)
492         if len(todo):
493             self.pool.get('stock.move').action_confirm(cr, uid, todo, context)
494         return True
495
496     def test_auto_picking(self, cr, uid, ids):
497         # TODO: Check locations to see if in the same location ?
498         return True
499
500     def button_confirm(self, cr, uid, ids, *args):
501         for id in ids:
502             wf_service = netsvc.LocalService("workflow")
503             wf_service.trg_validate(uid, 'stock.picking', id, 'button_confirm', cr)
504         self.force_assign(cr, uid, ids, *args)
505         return True
506
507     def action_assign(self, cr, uid, ids, *args):
508         for pick in self.browse(cr, uid, ids):
509             move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
510             self.pool.get('stock.move').action_assign(cr, uid, move_ids)
511         return True
512
513     def force_assign(self, cr, uid, ids, *args):
514         wf_service = netsvc.LocalService("workflow")
515         for pick in self.browse(cr, uid, ids):
516             move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
517 #            move_ids = [x.id for x in pick.move_lines]
518             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
519             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
520         return True
521
522     def draft_force_assign(self, cr, uid, ids, *args):
523         wf_service = netsvc.LocalService("workflow")
524         for pick in self.browse(cr, uid, ids):
525             wf_service.trg_validate(uid, 'stock.picking', pick.id,
526                 'button_confirm', cr)
527             #move_ids = [x.id for x in pick.move_lines]
528             #self.pool.get('stock.move').force_assign(cr, uid, move_ids)
529             #wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
530         return True
531
532     def draft_validate(self, cr, uid, ids, *args):
533         wf_service = netsvc.LocalService("workflow")
534         self.draft_force_assign(cr, uid, ids)
535         for pick in self.browse(cr, uid, ids):
536             move_ids = [x.id for x in pick.move_lines]
537             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
538             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
539
540             self.action_move(cr, uid, [pick.id])
541             wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
542         return True
543
544     def cancel_assign(self, cr, uid, ids, *args):
545         wf_service = netsvc.LocalService("workflow")
546         for pick in self.browse(cr, uid, ids):
547             move_ids = [x.id for x in pick.move_lines]
548             self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
549             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
550         return True
551
552     def action_assign_wkf(self, cr, uid, ids):
553         self.write(cr, uid, ids, {'state': 'assigned'})
554         return True
555
556     def test_finnished(self, cr, uid, ids):
557         move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
558         for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
559             if move.state not in ('done', 'cancel'):
560                 if move.product_qty != 0.0:
561                     return False
562                 else:
563                     move.write(cr, uid, [move.id], {'state': 'done'})
564         return True
565
566     def test_assigned(self, cr, uid, ids):
567         ok = True
568         for pick in self.browse(cr, uid, ids):
569             mt = pick.move_type
570             for move in pick.move_lines:
571                 if (move.state in ('confirmed', 'draft')) and (mt=='one'):
572                     return False
573                 if (mt=='direct') and (move.state=='assigned') and (move.product_qty):
574                     return True
575                 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
576         return ok
577
578     def action_cancel(self, cr, uid, ids, context={}):
579         for pick in self.browse(cr, uid, ids):
580             ids2 = [move.id for move in pick.move_lines]
581             self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
582         self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
583         return True
584
585     #
586     # TODO: change and create a move if not parents
587     #
588     def action_done(self, cr, uid, ids, context=None):
589         self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
590         return True
591
592     def action_move(self, cr, uid, ids, context={}):
593         for pick in self.browse(cr, uid, ids):
594             todo = []
595             for move in pick.move_lines:
596                 if move.state == 'assigned':
597                     todo.append(move.id)
598
599             if len(todo):
600                 self.pool.get('stock.move').action_done(cr, uid, todo,
601                         context=context)
602         return True
603
604     def get_currency_id(self, cursor, user, picking):
605         return False
606
607     def _get_payment_term(self, cursor, user, picking):
608         '''Return {'contact': address, 'invoice': address} for invoice'''
609         partner_obj = self.pool.get('res.partner')
610         partner = picking.address_id.partner_id
611         return partner.property_payment_term and partner.property_payment_term.id or False
612
613     def _get_address_invoice(self, cursor, user, picking):
614         '''Return {'contact': address, 'invoice': address} for invoice'''
615         partner_obj = self.pool.get('res.partner')
616         partner = picking.address_id.partner_id
617
618         return partner_obj.address_get(cursor, user, [partner.id],
619                 ['contact', 'invoice'])
620
621     def _get_comment_invoice(self, cursor, user, picking):
622         '''Return comment string for invoice'''
623         return picking.note or ''
624
625     def _get_price_unit_invoice(self, cursor, user, move_line, type):
626         '''Return the price unit for the move line'''
627         if type in ('in_invoice', 'in_refund'):
628             return move_line.product_id.standard_price
629         else:
630             return move_line.product_id.list_price
631
632     def _get_discount_invoice(self, cursor, user, move_line):
633         '''Return the discount for the move line'''
634         return 0.0
635
636     def _get_taxes_invoice(self, cursor, user, move_line, type):
637         '''Return taxes ids for the move line'''
638         if type in ('in_invoice', 'in_refund'):
639             taxes = move_line.product_id.supplier_taxes_id
640         else:
641             taxes = move_line.product_id.taxes_id
642
643         if move_line.picking_id and move_line.picking_id.address_id and move_line.picking_id.address_id.partner_id:
644             return self.pool.get('account.fiscal.position').map_tax(
645                 cursor,
646                 user,
647                 move_line.picking_id.address_id.partner_id.property_account_position,
648                 taxes
649             )
650         else:
651             return map(lambda x: x.id, taxes)
652
653     def _get_account_analytic_invoice(self, cursor, user, picking, move_line):
654         return False
655
656     def _invoice_line_hook(self, cursor, user, move_line, invoice_line_id):
657         '''Call after the creation of the invoice line'''
658         return
659
660     def _invoice_hook(self, cursor, user, picking, invoice_id):
661         '''Call after the creation of the invoice'''
662         return
663
664     def action_invoice_create(self, cursor, user, ids, journal_id=False,
665             group=False, type='out_invoice', context=None):
666         '''Return ids of created invoices for the pickings'''
667         invoice_obj = self.pool.get('account.invoice')
668         invoice_line_obj = self.pool.get('account.invoice.line')
669         invoices_group = {}
670         res = {}
671
672         for picking in self.browse(cursor, user, ids, context=context):
673             if picking.invoice_state != '2binvoiced':
674                 continue
675             payment_term_id = False
676             partner = picking.address_id and picking.address_id.partner_id
677             if not partner:
678                 raise osv.except_osv(_('Error, no partner !'),
679                     _('Please put a partner on the picking list if you want to generate invoice.'))
680
681             if type in ('out_invoice', 'out_refund'):
682                 account_id = partner.property_account_receivable.id
683                 payment_term_id = self._get_payment_term(cursor, user, picking)
684             else:
685                 account_id = partner.property_account_payable.id
686
687             address_contact_id, address_invoice_id = \
688                     self._get_address_invoice(cursor, user, picking).values()
689
690             comment = self._get_comment_invoice(cursor, user, picking)
691             if group and partner.id in invoices_group:
692                 invoice_id = invoices_group[partner.id]
693                 invoice = invoice_obj.browse(cursor, user, invoice_id)
694                 invoice_vals = {
695                     'name': (invoice.name or '') + ', ' + (picking.name or ''),
696                     'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
697                     'comment': (comment and (invoice.comment and invoice.comment+"\n"+comment or comment)) or (invoice.comment and invoice.comment or ''),
698                 }
699                 invoice_obj.write(cursor, user, [invoice_id], invoice_vals, context=context)
700             else:
701                 invoice_vals = {
702                     'name': picking.name,
703                     'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
704                     'type': type,
705                     'account_id': account_id,
706                     'partner_id': partner.id,
707                     'address_invoice_id': address_invoice_id,
708                     'address_contact_id': address_contact_id,
709                     'comment': comment,
710                     'payment_term': payment_term_id,
711                     'fiscal_position': partner.property_account_position.id
712                     }
713                 cur_id = self.get_currency_id(cursor, user, picking)
714                 if cur_id:
715                     invoice_vals['currency_id'] = cur_id
716                 if journal_id:
717                     invoice_vals['journal_id'] = journal_id
718                 invoice_id = invoice_obj.create(cursor, user, invoice_vals,
719                         context=context)
720                 invoices_group[partner.id] = invoice_id
721             res[picking.id] = invoice_id
722             for move_line in picking.move_lines:
723                 origin = move_line.picking_id.name
724                 if move_line.picking_id.origin:
725                     origin += ':' + move_line.picking_id.origin
726                 if group:
727                     name = (picking.name or '') + '-' + move_line.name
728                 else:
729                     name = move_line.name
730
731                 if type in ('out_invoice', 'out_refund'):
732                     account_id = move_line.product_id.product_tmpl_id.\
733                             property_account_income.id
734                     if not account_id:
735                         account_id = move_line.product_id.categ_id.\
736                                 property_account_income_categ.id
737                 else:
738                     account_id = move_line.product_id.product_tmpl_id.\
739                             property_account_expense.id
740                     if not account_id:
741                         account_id = move_line.product_id.categ_id.\
742                                 property_account_expense_categ.id
743
744                 price_unit = self._get_price_unit_invoice(cursor, user,
745                         move_line, type)
746                 discount = self._get_discount_invoice(cursor, user, move_line)
747                 tax_ids = self._get_taxes_invoice(cursor, user, move_line, type)
748                 account_analytic_id = self._get_account_analytic_invoice(cursor,
749                         user, picking, move_line)
750
751                 #set UoS if it's a sale and the picking doesn't have one
752                 uos_id = move_line.product_uos and move_line.product_uos.id or False
753                 if not uos_id and type in ('out_invoice', 'out_refund'):
754                     uos_id = move_line.product_uom.id
755
756                 account_id = self.pool.get('account.fiscal.position').map_account(cursor, user, partner.property_account_position, account_id)
757                 invoice_line_id = invoice_line_obj.create(cursor, user, {
758                     'name': name,
759                     'origin': origin,
760                     'invoice_id': invoice_id,
761                     'uos_id': uos_id,
762                     'product_id': move_line.product_id.id,
763                     'account_id': account_id,
764                     'price_unit': price_unit,
765                     'discount': discount,
766                     'quantity': move_line.product_uos_qty or move_line.product_qty,
767                     'invoice_line_tax_id': [(6, 0, tax_ids)],
768                     'account_analytic_id': account_analytic_id,
769                     }, context=context)
770                 self._invoice_line_hook(cursor, user, move_line, invoice_line_id)
771
772             invoice_obj.button_compute(cursor, user, [invoice_id], context=context,
773                     set_total=(type in ('in_invoice', 'in_refund')))
774             self.write(cursor, user, [picking.id], {
775                 'invoice_state': 'invoiced',
776                 }, context=context)
777             self._invoice_hook(cursor, user, picking, invoice_id)
778         self.write(cursor, user, res.keys(), {
779             'invoice_state': 'invoiced',
780             }, context=context)
781         return res
782
783     def test_cancel(self, cr, uid, ids, context={}):
784         for pick in self.browse(cr, uid, ids, context=context):
785             if not pick.move_lines:
786                 return False
787             for move in pick.move_lines:
788                 if move.state not in ('cancel',):
789                     return False
790         return True
791
792     def unlink(self, cr, uid, ids, context=None):
793         for pick in self.browse(cr, uid, ids, context=context):
794             if pick.state in ['done','cancel']:
795                 raise osv.except_osv(_('Error'), _('You cannot remove the picking which is in %s state !')%(pick.state,))
796             elif pick.state in ['confirmed','assigned']:
797                 ids2 = [move.id for move in pick.move_lines]
798                 context.update({'call_unlink':True})
799                 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
800             else:
801                 continue
802         return super(stock_picking, self).unlink(cr, uid, ids, context=context)
803
804 stock_picking()
805
806
807 class stock_production_lot(osv.osv):
808     def name_get(self, cr, uid, ids, context={}):
809         if not ids:
810             return []
811         reads = self.read(cr, uid, ids, ['name', 'ref'], context)
812         res = []
813         for record in reads:
814             name = record['name']
815             if record['ref']:
816                 name = name + '/' + record['ref']
817             res.append((record['id'], name))
818         return res
819
820     _name = 'stock.production.lot'
821     _description = 'Production lot'
822
823     def _get_stock(self, cr, uid, ids, field_name, arg, context={}):
824         if 'location_id' not in context:
825             locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
826         else:
827             locations = context['location_id'] and [context['location_id']] or []
828
829         if isinstance(ids, (int, long)):
830             ids = [ids]
831
832         res = {}.fromkeys(ids, 0.0)
833
834         if locations:
835             cr.execute('''select
836                     prodlot_id,
837                     sum(name)
838                 from
839                     stock_report_prodlots
840                 where
841                     location_id in %s  and
842                     prodlot_id in  %s
843                 group by
844                     prodlot_id
845             ''', (tuple(locations), tuple(ids)))
846             res.update(dict(cr.fetchall()))
847         return res
848
849     def _stock_search(self, cr, uid, obj, name, args, context):
850         locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
851         cr.execute('''select
852                 prodlot_id,
853                 sum(name)
854             from
855                 stock_report_prodlots
856             where
857                 location_id in %s
858             group by
859                 prodlot_id
860             having sum(name) ''' + str(args[0][1]) + ' %s',
861                    (tuple(locations), args[0][2]))
862         res = cr.fetchall()
863         ids = [('id', 'in', map(lambda x: x[0], res))]
864         return ids
865
866     _columns = {
867         'name': fields.char('Serial', size=64, required=True),
868         'ref': fields.char('Internal Ref', size=64),
869         'product_id': fields.many2one('product.product', 'Product', required=True),
870         'date': fields.datetime('Created Date', required=True),
871         'stock_available': fields.function(_get_stock, fnct_search=_stock_search, method=True, type="float", string="Available", select="2"),
872         'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
873     }
874     _defaults = {
875         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
876         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
877         'product_id': lambda x, y, z, c: c.get('product_id', False),
878     }
879     _sql_constraints = [
880         ('name_ref_uniq', 'unique (name, ref)', 'The serial/ref must be unique !'),
881     ]
882
883 stock_production_lot()
884
885
886 class stock_production_lot_revision(osv.osv):
887     _name = 'stock.production.lot.revision'
888     _description = 'Production lot revisions'
889     _columns = {
890         'name': fields.char('Revision Name', size=64, required=True),
891         'description': fields.text('Description'),
892         'date': fields.date('Revision Date'),
893         'indice': fields.char('Revision', size=16),
894         'author_id': fields.many2one('res.users', 'Author'),
895         'lot_id': fields.many2one('stock.production.lot', 'Production lot', select=True, ondelete='cascade'),
896     }
897
898     _defaults = {
899         'author_id': lambda x, y, z, c: z,
900         'date': lambda *a: time.strftime('%Y-%m-%d'),
901     }
902
903 stock_production_lot_revision()
904
905 # ----------------------------------------------------
906 # Move
907 # ----------------------------------------------------
908
909 #
910 # Fields:
911 #   location_dest_id is only used for predicting futur stocks
912 #
913 class stock_move(osv.osv):
914     def _getSSCC(self, cr, uid, context={}):
915         cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
916         res = cr.fetchone()
917         return (res and res[0]) or False
918     _name = "stock.move"
919     _description = "Stock Move"
920
921     def name_get(self, cr, uid, ids, context={}):
922         res = []
923         for line in self.browse(cr, uid, ids, context):
924             res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))
925         return res
926
927     def _check_tracking(self, cr, uid, ids):
928         for move in self.browse(cr, uid, ids):
929             if not move.prodlot_id and \
930                (move.state == 'done' and \
931                ( \
932                    (move.product_id.track_production and move.location_id.usage=='production') or \
933                    (move.product_id.track_production and move.location_dest_id.usage=='production') or \
934                    (move.product_id.track_incoming and move.location_id.usage in ('supplier','internal')) or \
935                    (move.product_id.track_outgoing and move.location_dest_id.usage in ('customer','internal')) \
936                )):
937                 return False
938         return True
939
940     def _check_product_lot(self, cr, uid, ids):
941         for move in self.browse(cr, uid, ids):
942             if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):
943                 return False
944         return True
945
946     _columns = {
947         'name': fields.char('Name', size=64, required=True, select=True),
948         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
949
950         'date': fields.datetime('Date Created'),
951         'date_planned': fields.datetime('Date', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
952
953         'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
954
955         'product_qty': fields.float('Quantity', required=True),
956         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
957         'product_uos_qty': fields.float('Quantity (UOS)'),
958         'product_uos': fields.many2one('product.uom', 'Product UOS'),
959         'product_packaging': fields.many2one('product.packaging', 'Packaging'),
960
961         'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True),
962         'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, select=True),
963         'address_id': fields.many2one('res.partner.address', 'Dest. Address'),
964
965         'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="Production lot is used to put a serial number on the production"),
966         '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"),
967 #       'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),
968
969         'auto_validate': fields.boolean('Auto Validate'),
970
971         'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),
972         'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
973         'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
974         'picking_id': fields.many2one('stock.picking', 'Packing List', select=True),
975
976         'note': fields.text('Notes'),
977
978         'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Status', readonly=True, select=True),
979         'price_unit': fields.float('Unit Price',
980             digits=(16, int(config['price_accuracy']))),
981     }
982     _constraints = [
983         (_check_tracking,
984             'You must assign a production lot for this product',
985             ['prodlot_id']),
986         (_check_product_lot,
987             'You try to assign a lot which is not from the same product',
988             ['prodlot_id'])]
989
990     def _default_location_destination(self, cr, uid, context={}):
991         if context.get('move_line', []):
992             if context['move_line'][0]:
993                 if isinstance(context['move_line'][0], (tuple, list)):
994                     return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
995                 else:
996                     move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
997                     return move_list and move_list['location_dest_id'][0] or False
998         if context.get('address_out_id', False):
999             return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id
1000         return False
1001
1002     def _default_location_source(self, cr, uid, context={}):
1003         if context.get('move_line', []):
1004             try:
1005                 return context['move_line'][0][2]['location_id']
1006             except:
1007                 pass
1008         if context.get('address_in_id', False):
1009             return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1010         return False
1011
1012     _defaults = {
1013         'location_id': _default_location_source,
1014         'location_dest_id': _default_location_destination,
1015         'state': lambda *a: 'draft',
1016         'priority': lambda *a: '1',
1017         'product_qty': lambda *a: 1.0,
1018         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1019         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1020     }
1021
1022     def _auto_init(self, cursor, context):
1023         res = super(stock_move, self)._auto_init(cursor, context)
1024         cursor.execute('SELECT indexname \
1025                 FROM pg_indexes \
1026                 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1027         if not cursor.fetchone():
1028             cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1029                     ON stock_move (location_id, location_dest_id, product_id, state)')
1030             cursor.commit()
1031         return res
1032
1033     def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, context=None):
1034         if not prodlot_id or not loc_id:
1035             return {}
1036         ctx = context and context.copy() or {}
1037         ctx['location_id'] = loc_id
1038         prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1039         location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1040         warning = {}
1041         if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1042             warning = {
1043                 'title': 'Bad Lot Assignation !',
1044                 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1045             }
1046         return {'warning': warning}
1047
1048     def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1049         result = {
1050                   'product_uos_qty': 0.00
1051           }
1052
1053         if (not product_id) or (product_qty <=0.0):
1054             return {'value': result}
1055
1056         product_obj = self.pool.get('product.product')
1057         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1058
1059         if product_uos and product_uom and (product_uom != product_uos):
1060             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1061         else:
1062             result['product_uos_qty'] = product_qty
1063
1064         return {'value': result}
1065
1066     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, address_id=False):
1067         if not prod_id:
1068             return {}
1069         lang = False
1070         if address_id:
1071             addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1072             if addr_rec:
1073                 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1074         ctx = {'lang': lang}
1075
1076         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1077         uos_id  = product.uos_id and product.uos_id.id or False
1078         result = {
1079             'name': product.partner_ref,
1080             'product_uom': product.uom_id.id,
1081             'product_uos': uos_id,
1082             'product_qty': 1.00,
1083             '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']
1084         }
1085
1086         if loc_id:
1087             result['location_id'] = loc_id
1088         if loc_dest_id:
1089             result['location_dest_id'] = loc_dest_id
1090         return {'value': result}
1091
1092     def _chain_compute(self, cr, uid, moves, context={}):
1093         result = {}
1094         for m in moves:
1095             dest = self.pool.get('stock.location').chained_location_get(
1096                 cr,
1097                 uid,
1098                 m.location_dest_id,
1099                 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1100                 m.product_id,
1101                 context
1102             )
1103             if dest:
1104                 if dest[1] == 'transparent':
1105                     self.write(cr, uid, [m.id], {
1106                         'date_planned': (DateTime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1107                             DateTime.RelativeDateTime(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1108                         'location_dest_id': dest[0].id})
1109                 else:
1110                     result.setdefault(m.picking_id, [])
1111                     result[m.picking_id].append( (m, dest) )
1112         return result
1113
1114     def action_confirm(self, cr, uid, ids, context={}):
1115 #        ids = map(lambda m: m.id, moves)
1116         moves = self.browse(cr, uid, ids)
1117         self.write(cr, uid, ids, {'state': 'confirmed'})
1118         i = 0
1119
1120         def create_chained_picking(self, cr, uid, moves, context):
1121             new_moves = []
1122             for picking, todo in self._chain_compute(cr, uid, moves, context).items():
1123                 ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
1124                 pickid = self.pool.get('stock.picking').create(cr, uid, {
1125                     'name': picking.name,
1126                     'origin': str(picking.origin or ''),
1127                     'type': ptype,
1128                     'note': picking.note,
1129                     'move_type': picking.move_type,
1130                     'auto_picking': todo[0][1][1] == 'auto',
1131                     'address_id': picking.address_id.id,
1132                     'invoice_state': 'none'
1133                 })
1134                 for move, (loc, auto, delay) in todo:
1135                     # Is it smart to copy ? May be it's better to recreate ?
1136                     new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {
1137                         'location_id': move.location_dest_id.id,
1138                         'location_dest_id': loc.id,
1139                         'date_moved': time.strftime('%Y-%m-%d'),
1140                         'picking_id': pickid,
1141                         'state': 'waiting',
1142                         'move_history_ids': [],
1143                         'date_planned': (DateTime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + DateTime.RelativeDateTime(days=delay or 0)).strftime('%Y-%m-%d'),
1144                         'move_history_ids2': []}
1145                     )
1146                     self.pool.get('stock.move').write(cr, uid, [move.id], {
1147                         'move_dest_id': new_id,
1148                         'move_history_ids': [(4, new_id)]
1149                     })
1150                     new_moves.append(self.browse(cr, uid, [new_id])[0])
1151                 wf_service = netsvc.LocalService("workflow")
1152                 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1153             if new_moves:
1154                 create_chained_picking(self, cr, uid, new_moves, context)
1155         create_chained_picking(self, cr, uid, moves, context)
1156         return []
1157
1158     def action_assign(self, cr, uid, ids, *args):
1159         todo = []
1160         for move in self.browse(cr, uid, ids):
1161             if move.state in ('confirmed', 'waiting'):
1162                 todo.append(move.id)
1163         res = self.check_assign(cr, uid, todo)
1164         return res
1165
1166     def force_assign(self, cr, uid, ids, context={}):
1167         self.write(cr, uid, ids, {'state': 'assigned'})
1168         return True
1169
1170     def cancel_assign(self, cr, uid, ids, context={}):
1171         self.write(cr, uid, ids, {'state': 'confirmed'})
1172         return True
1173
1174     #
1175     # Duplicate stock.move
1176     #
1177     def check_assign(self, cr, uid, ids, context={}):
1178         done = []
1179         count = 0
1180         pickings = {}
1181         for move in self.browse(cr, uid, ids):
1182             if move.product_id.type == 'consu':
1183                 if move.state in ('confirmed', 'waiting'):
1184                     done.append(move.id)
1185                 pickings[move.picking_id.id] = 1
1186                 continue
1187             if move.state in ('confirmed', 'waiting'):
1188                 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})
1189                 if res:
1190                     #_product_available_test depends on the next status for correct functioning
1191                     #the test does not work correctly if the same product occurs multiple times
1192                     #in the same order. This is e.g. the case when using the button 'split in two' of
1193                     #the stock outgoing form
1194                     self.write(cr, uid, move.id, {'state':'assigned'})
1195                     done.append(move.id)
1196                     pickings[move.picking_id.id] = 1
1197                     r = res.pop(0)
1198                     cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1199
1200                     while res:
1201                         r = res.pop(0)
1202                         move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1203                         done.append(move_id)
1204         if done:
1205             count += len(done)
1206             self.write(cr, uid, done, {'state': 'assigned'})
1207
1208         if count:
1209             for pick_id in pickings:
1210                 wf_service = netsvc.LocalService("workflow")
1211                 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1212         return count
1213
1214     #
1215     # Cancel move => cancel others move and pickings
1216     #
1217     def action_cancel(self, cr, uid, ids, context={}):
1218         if not len(ids):
1219             return True
1220         pickings = {}
1221         for move in self.browse(cr, uid, ids):
1222             if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1223                 if move.picking_id:
1224                     pickings[move.picking_id.id] = True
1225             if move.move_dest_id and move.move_dest_id.state == 'waiting':
1226                 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1227                 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1228                     wf_service = netsvc.LocalService("workflow")
1229                     wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1230         self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1231         if not context.get('call_unlink',False):
1232             for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1233                 if all(move.state == 'cancel' for move in pick.move_lines):
1234                     self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1235
1236         wf_service = netsvc.LocalService("workflow")
1237         for id in ids:
1238             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1239         #self.action_cancel(cr,uid, ids2, context)
1240         return True
1241
1242     def action_done(self, cr, uid, ids, context=None):
1243         track_flag = False
1244         for move in self.browse(cr, uid, ids):
1245             if move.move_dest_id.id and (move.state != 'done'):
1246                 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1247                 if move.move_dest_id.state in ('waiting', 'confirmed'):
1248                     self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1249                     if move.move_dest_id.picking_id:
1250                         wf_service = netsvc.LocalService("workflow")
1251                         wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1252                     else:
1253                         pass
1254                         # self.action_done(cr, uid, [move.move_dest_id.id])
1255                     if move.move_dest_id.auto_validate:
1256                         self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1257
1258             #
1259             # Accounting Entries
1260             #
1261             acc_src = None
1262             acc_dest = None
1263             if move.location_id.account_id:
1264                 acc_src = move.location_id.account_id.id
1265             if move.location_dest_id.account_id:
1266                 acc_dest = move.location_dest_id.account_id.id
1267             if acc_src or acc_dest:
1268                 test = [('product.product', move.product_id.id)]
1269                 if move.product_id.categ_id:
1270                     test.append( ('product.category', move.product_id.categ_id.id) )
1271                 if not acc_src:
1272                     acc_src = move.product_id.product_tmpl_id.\
1273                             property_stock_account_input.id
1274                     if not acc_src:
1275                         acc_src = move.product_id.categ_id.\
1276                                 property_stock_account_input_categ.id
1277                     if not acc_src:
1278                         raise osv.except_osv(_('Error!'),
1279                                 _('There is no stock input account defined ' \
1280                                         'for this product: "%s" (id: %d)') % \
1281                                         (move.product_id.name,
1282                                             move.product_id.id,))
1283                 if not acc_dest:
1284                     acc_dest = move.product_id.product_tmpl_id.\
1285                             property_stock_account_output.id
1286                     if not acc_dest:
1287                         acc_dest = move.product_id.categ_id.\
1288                                 property_stock_account_output_categ.id
1289                     if not acc_dest:
1290                         raise osv.except_osv(_('Error!'),
1291                                 _('There is no stock output account defined ' \
1292                                         'for this product: "%s" (id: %d)') % \
1293                                         (move.product_id.name,
1294                                             move.product_id.id,))
1295                 if not move.product_id.categ_id.property_stock_journal.id:
1296                     raise osv.except_osv(_('Error!'),
1297                         _('There is no journal defined '\
1298                             'on the product category: "%s" (id: %d)') % \
1299                             (move.product_id.categ_id.name,
1300                                 move.product_id.categ_id.id,))
1301                 journal_id = move.product_id.categ_id.property_stock_journal.id
1302                 if acc_src != acc_dest:
1303                     ref = move.picking_id and move.picking_id.name or False
1304                     product_uom_obj = self.pool.get('product.uom')
1305                     default_uom = move.product_id.uom_id.id
1306                     q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1307                     if move.product_id.cost_method == 'average' and move.price_unit:
1308                         amount = q * move.price_unit
1309                     else:
1310                         amount = q * move.product_id.standard_price
1311
1312                     date = time.strftime('%Y-%m-%d')
1313                     partner_id = False
1314                     if move.picking_id:
1315                         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
1316                     lines = [
1317                             (0, 0, {
1318                                 'name': move.name,
1319                                 'quantity': move.product_qty,
1320                                 'product_id': move.product_id and move.product_id.id or False,
1321                                 'credit': amount,
1322                                 'account_id': acc_src,
1323                                 'ref': ref,
1324                                 'date': date,
1325                                 'partner_id': partner_id}),
1326                             (0, 0, {
1327                                 'name': move.name,
1328                                 'product_id': move.product_id and move.product_id.id or False,
1329                                 'quantity': move.product_qty,
1330                                 'debit': amount,
1331                                 'account_id': acc_dest,
1332                                 'ref': ref,
1333                                 'date': date,
1334                                 'partner_id': partner_id})
1335                     ]
1336                     self.pool.get('account.move').create(cr, uid, {
1337                         'name': move.name,
1338                         'journal_id': journal_id,
1339                         'line_id': lines,
1340                         'ref': ref,
1341                     })
1342         self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1343         wf_service = netsvc.LocalService("workflow")
1344         for id in ids:
1345             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1346         return True
1347
1348     def unlink(self, cr, uid, ids, context=None):
1349         for move in self.browse(cr, uid, ids, context=context):
1350             if move.state != 'draft':
1351                 raise osv.except_osv(_('UserError'),
1352                         _('You can only delete draft moves.'))
1353         return super(stock_move, self).unlink(
1354             cr, uid, ids, context=context)
1355
1356 stock_move()
1357
1358
1359 class stock_inventory(osv.osv):
1360     _name = "stock.inventory"
1361     _description = "Inventory"
1362     _columns = {
1363         'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
1364         'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
1365         'date_done': fields.datetime('Date done'),
1366         'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
1367         'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
1368         'state': fields.selection( (('draft', 'Draft'), ('done', 'Done')), 'Status', readonly=True),
1369     }
1370     _defaults = {
1371         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1372         'state': lambda *a: 'draft',
1373     }
1374
1375     #
1376     # Update to support tracking
1377     #
1378     def action_done(self, cr, uid, ids, context=None):
1379         for inv in self.browse(cr, uid, ids):
1380             move_ids = []
1381             move_line = []
1382             for line in inv.inventory_line_id:
1383                 pid = line.product_id.id
1384                 price = line.product_id.standard_price or 0.0
1385                 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
1386                 change = line.product_qty - amount
1387                 if change:
1388                     location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
1389                     value = {
1390                         'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
1391                         'product_id': line.product_id.id,
1392                         'product_uom': line.product_uom.id,
1393                         'date': inv.date,
1394                         'date_planned': inv.date,
1395                         'state': 'assigned'
1396                     }
1397                     if change > 0:
1398                         value.update( {
1399                             'product_qty': change,
1400                             'location_id': location_id,
1401                             'location_dest_id': line.location_id.id,
1402                         })
1403                     else:
1404                         value.update( {
1405                             'product_qty': -change,
1406                             'location_id': line.location_id.id,
1407                             'location_dest_id': location_id,
1408                         })
1409                     move_ids.append(self.pool.get('stock.move').create(cr, uid, value))
1410             if len(move_ids):
1411                 self.pool.get('stock.move').action_done(cr, uid, move_ids,
1412                         context=context)
1413             self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
1414         return True
1415
1416     def action_cancel(self, cr, uid, ids, context={}):
1417         for inv in self.browse(cr, uid, ids):
1418             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
1419             self.write(cr, uid, [inv.id], {'state': 'draft'})
1420         return True
1421
1422 stock_inventory()
1423
1424
1425 class stock_inventory_line(osv.osv):
1426     _name = "stock.inventory.line"
1427     _description = "Inventory line"
1428     _columns = {
1429         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
1430         'location_id': fields.many2one('stock.location', 'Location', required=True),
1431         'product_id': fields.many2one('product.product', 'Product', required=True),
1432         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
1433         'product_qty': fields.float('Quantity')
1434     }
1435
1436     def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
1437         if not product:
1438             return {}
1439         if not uom:
1440             prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
1441             uom = prod.uom_id.id
1442         amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
1443         result = {'product_qty': amount, 'product_uom': uom}
1444         return {'value': result}
1445
1446 stock_inventory_line()
1447
1448
1449 #----------------------------------------------------------
1450 # Stock Warehouse
1451 #----------------------------------------------------------
1452 class stock_warehouse(osv.osv):
1453     _name = "stock.warehouse"
1454     _description = "Warehouse"
1455     _columns = {
1456         'name': fields.char('Name', size=60, required=True),
1457 #       'partner_id': fields.many2one('res.partner', 'Owner'),
1458         'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
1459         'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True),
1460         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True),
1461         'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True),
1462     }
1463
1464 stock_warehouse()
1465
1466
1467 # Move wizard :
1468 #    get confirm or assign stock move lines of partner and put in current picking.
1469 class stock_picking_move_wizard(osv.osv_memory):
1470     _name = 'stock.picking.move.wizard'
1471
1472     def _get_picking(self, cr, uid, ctx):
1473         if ctx.get('action_id', False):
1474             return ctx['action_id']
1475         return False
1476
1477     def _get_picking_address(self, cr, uid, ctx):
1478         picking_obj = self.pool.get('stock.picking')
1479         if ctx.get('action_id', False):
1480             picking = picking_obj.browse(cr, uid, [ctx['action_id']])[0]
1481             return picking.address_id and picking.address_id.id or False
1482         return False
1483
1484     _columns = {
1485         'name': fields.char('Name', size=64, invisible=True),
1486         #'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines',readonly=True),
1487         'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Move lines', required=True),
1488         'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
1489         'picking_id': fields.many2one('stock.picking', 'Packing list', select=True, invisible=True),
1490     }
1491     _defaults = {
1492         'picking_id': _get_picking,
1493         'address_id': _get_picking_address,
1494     }
1495
1496     def action_move(self, cr, uid, ids, context=None):
1497         move_obj = self.pool.get('stock.move')
1498         picking_obj = self.pool.get('stock.picking')
1499         for act in self.read(cr, uid, ids):
1500             move_lines = move_obj.browse(cr, uid, act['move_ids'])
1501             for line in move_lines:
1502                 if line.picking_id:
1503                     picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
1504                     picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
1505                     cr.commit()
1506                     old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
1507                     if not len(old_picking['move_lines']):
1508                         picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
1509                 else:
1510                     raise osv.except_osv(_('UserError'),
1511                         _('You can not create new moves.'))
1512         return {'type': 'ir.actions.act_window_close'}
1513
1514 stock_picking_move_wizard()
1515
1516
1517 class report_stock_lines_date(osv.osv):
1518     _name = "report.stock.lines.date"
1519     _description = "Dates of Inventories"
1520     _auto = False
1521     _columns = {
1522         'id': fields.integer('Inventory Line Id', readonly=True),
1523         'product_id': fields.integer('Product Id', readonly=True),
1524         'create_date': fields.datetime('Latest Date of Inventory'),
1525         }
1526
1527     def init(self, cr):
1528         cr.execute("""
1529             create or replace view report_stock_lines_date as (
1530                 select
1531                 l.id as id,
1532                 p.id as product_id,
1533                 max(l.create_date) as create_date
1534                 from
1535                 product_product p
1536                 left outer join
1537                 stock_inventory_line l on (p.id=l.product_id)
1538                 where l.create_date is not null
1539                 group by p.id,l.id
1540             )""")
1541
1542 report_stock_lines_date()