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