[MERGE]: Merge with lp:openobject-addons
[odoo/odoo.git] / addons / stock / stock.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from datetime import datetime
23 from dateutil.relativedelta import relativedelta
24
25 from osv import fields, osv
26 from tools import config
27 from tools.translate import _
28 import math
29 import netsvc
30 import time
31 import tools
32
33 import decimal_precision as dp
34
35
36 #----------------------------------------------------------
37 # Incoterms
38 #----------------------------------------------------------
39 class stock_incoterms(osv.osv):
40     _name = "stock.incoterms"
41     _description = "Incoterms"
42     _columns = {
43         'name': fields.char('Name', size=64, required=True,help="Incoterms are series of sales terms.They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
44         'code': fields.char('Code', size=3, required=True,help="Code for Incoterms"),
45         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the incoterms without removing it."),
46     }
47     _defaults = {
48         'active': lambda *a: True,
49     }
50
51 stock_incoterms()
52
53
54 #----------------------------------------------------------
55 # Stock Location
56 #----------------------------------------------------------
57 class stock_location(osv.osv):
58     _name = "stock.location"
59     _description = "Location"
60     _parent_name = "location_id"
61     _parent_store = True
62     _parent_order = 'id'
63     _order = 'parent_left'
64
65     def name_get(self, cr, uid, ids, context={}):
66         if not len(ids):
67             return []
68         reads = self.read(cr, uid, ids, ['name','location_id'], context)
69         res = []
70         for record in reads:
71             name = record['name']
72             if context.get('full',False):
73                 if record['location_id']:
74                     name = record['location_id'][1]+' / '+name
75                 res.append((record['id'], name))
76             else:
77                 res.append((record['id'], name))
78         return res
79
80     def _complete_name(self, cr, uid, ids, name, args, context):
81         def _get_one_full_name(location, level=4):
82             if location.location_id:
83                 parent_path = _get_one_full_name(location.location_id, level-1) + "/"
84             else:
85                 parent_path = ''
86             return parent_path + location.name
87         res = {}
88         for m in self.browse(cr, uid, ids, context=context):
89             res[m.id] = _get_one_full_name(m)
90         return res
91
92     def _product_qty_available(self, cr, uid, ids, field_names, arg, context={}):
93         res = {}
94         for id in ids:
95             res[id] = {}.fromkeys(field_names, 0.0)
96         if ('product_id' not in context) or not ids:
97             return res
98         #location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
99         for loc in ids:
100             context['location'] = [loc]
101             prod = self.pool.get('product.product').browse(cr, uid, context['product_id'], context)
102             if 'stock_real' in field_names:
103                 res[loc]['stock_real'] = prod.qty_available
104             if 'stock_virtual' in field_names:
105                 res[loc]['stock_virtual'] = prod.virtual_available
106         return res
107
108     def product_detail(self, cr, uid, id, field, context={}):
109         res = {}
110         res[id] = {}
111         final_value = 0.0
112         field_to_read = 'virtual_available'
113         if field == 'stock_real_value':
114             field_to_read = 'qty_available'
115         cr.execute('select distinct product_id from stock_move where (location_id=%s) or (location_dest_id=%s)', (id, id))
116         result = cr.dictfetchall()
117         if result:
118             # Choose the right filed standard_price to read
119             # Take the user company
120             price_type_id=self.pool.get('res.users').browse(cr,uid,uid).company_id.property_valuation_price_type.id
121             pricetype=self.pool.get('product.price.type').browse(cr,uid,price_type_id)
122             for r in result:
123                 c = (context or {}).copy()
124                 c['location'] = id
125                 product = self.pool.get('product.product').read(cr, uid, r['product_id'], [field_to_read], context=c)
126                 # Compute the amount_unit in right currency
127
128                 context['currency_id']=self.pool.get('res.users').browse(cr,uid,uid).company_id.currency_id.id
129                 amount_unit=self.pool.get('product.product').browse(cr,uid,r['product_id']).price_get(pricetype.field, context)[r['product_id']]
130
131                 final_value += (product[field_to_read] * amount_unit)
132         return final_value
133
134     def _product_value(self, cr, uid, ids, field_names, arg, context={}):
135         result = {}
136         for id in ids:
137             result[id] = {}.fromkeys(field_names, 0.0)
138         for field_name in field_names:
139             for loc in ids:
140                 ret_dict = self.product_detail(cr, uid, loc, field=field_name)
141                 result[loc][field_name] = ret_dict
142         return result
143
144     _columns = {
145         'name': fields.char('Location Name', size=64, required=True, translate=True),
146         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the stock location without removing it."),
147         'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production')], 'Location Type', required=True),
148         'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
149
150         'complete_name': fields.function(_complete_name, method=True, type='char', size=100, string="Location Name"),
151
152         'stock_real': fields.function(_product_qty_available, method=True, type='float', string='Real Stock', multi="stock"),
153         'stock_virtual': fields.function(_product_qty_available, method=True, type='float', string='Virtual Stock', multi="stock"),
154
155         'account_id': fields.many2one('account.account', string='Inventory Account', domain=[('type', '!=', 'view')]),
156         'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
157         'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
158
159         'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
160         'chained_location_type': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
161             'Chained Location Type', required=True),
162         'chained_auto_packing': fields.selection(
163             [('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
164             'Automatic Move',
165             required=True,
166             help="This is used only if you select a chained location type.\n" \
167                 "The 'Automatic Move' value will create a stock move after the current one that will be "\
168                 "validated automatically. With 'Manual Operation', the stock move has to be validated "\
169                 "by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
170             ),
171         'chained_delay': fields.integer('Chained lead time (days)'),
172         'address_id': fields.many2one('res.partner.address', 'Location Address'),
173         'icon': fields.selection(tools.icons, 'Icon', size=64),
174
175         'comment': fields.text('Additional Information'),
176         'posx': fields.integer('Corridor (X)'),
177         'posy': fields.integer('Shelves (Y)'),
178         'posz': fields.integer('Height (Z)'),
179
180         'parent_left': fields.integer('Left Parent', select=1),
181         'parent_right': fields.integer('Right Parent', select=1),
182         'stock_real_value': fields.function(_product_value, method=True, type='float', string='Real Stock Value', multi="stock"),
183         'stock_virtual_value': fields.function(_product_value, method=True, type='float', string='Virtual Stock Value', multi="stock"),
184         'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
185     }
186     _defaults = {
187         'active': lambda *a: 1,
188         'usage': lambda *a: 'internal',
189         'allocation_method': lambda *a: 'fifo',
190         'chained_location_type': lambda *a: 'none',
191         'chained_auto_packing': lambda *a: 'manual',
192         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.location', context=c),
193         'posx': lambda *a: 0,
194         'posy': lambda *a: 0,
195         'posz': lambda *a: 0,
196         'icon': lambda *a: False,
197     }
198
199     def chained_location_get(self, cr, uid, location, partner=None, product=None, context={}):
200         result = None
201         if location.chained_location_type == 'customer':
202             if partner:
203                 result = partner.property_stock_customer
204         elif location.chained_location_type == 'fixed':
205             result = location.chained_location_id
206         if result:
207             return result, location.chained_auto_packing, location.chained_delay
208         return result
209
210     def picking_type_get(self, cr, uid, from_location, to_location, context={}):
211         result = 'internal'
212         if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
213             result = 'delivery'
214         elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage=='internal'):
215             result = 'in'
216         return result
217
218     def _product_get_all_report(self, cr, uid, ids, product_ids=False,
219             context=None):
220         return self._product_get_report(cr, uid, ids, product_ids, context,
221                 recursive=True)
222
223     def _product_get_report(self, cr, uid, ids, product_ids=False,
224             context=None, recursive=False):
225         if context is None:
226             context = {}
227         product_obj = self.pool.get('product.product')
228         # Take the user company and pricetype
229         price_type_id=self.pool.get('res.users').browse(cr,uid,uid).company_id.property_valuation_price_type.id
230         pricetype=self.pool.get('product.price.type').browse(cr,uid,price_type_id)
231         context['currency_id']=self.pool.get('res.users').browse(cr,uid,uid).company_id.currency_id.id
232
233         if not product_ids:
234             product_ids = product_obj.search(cr, uid, [])
235
236         products = product_obj.browse(cr, uid, product_ids, context=context)
237         products_by_uom = {}
238         products_by_id = {}
239         for product in products:
240             products_by_uom.setdefault(product.uom_id.id, [])
241             products_by_uom[product.uom_id.id].append(product)
242             products_by_id.setdefault(product.id, [])
243             products_by_id[product.id] = product
244
245         result = {}
246         result['product'] = []
247         for id in ids:
248             quantity_total = 0.0
249             total_price = 0.0
250             for uom_id in products_by_uom.keys():
251                 fnc = self._product_get
252                 if recursive:
253                     fnc = self._product_all_get
254                 ctx = context.copy()
255                 ctx['uom'] = uom_id
256                 qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
257                         context=ctx)
258                 for product_id in qty.keys():
259                     if not qty[product_id]:
260                         continue
261                     product = products_by_id[product_id]
262                     quantity_total += qty[product_id]
263
264                     # Compute based on pricetype
265                     # Choose the right filed standard_price to read
266                     amount_unit=product.price_get(pricetype.field, context)[product.id]
267                     price = qty[product_id] * amount_unit
268                     # price = qty[product_id] * product.standard_price
269
270                     total_price += price
271                     result['product'].append({
272                         'price': amount_unit,
273                         'prod_name': product.name,
274                         'code': product.default_code, # used by lot_overview_all report!
275                         'variants': product.variants or '',
276                         'uom': product.uom_id.name,
277                         'prod_qty': qty[product_id],
278                         'price_value': price,
279                     })
280         result['total'] = quantity_total
281         result['total_price'] = total_price
282         return result
283
284     def _product_get_multi_location(self, cr, uid, ids, product_ids=False, context={}, states=['done'], what=('in', 'out')):
285         product_obj = self.pool.get('product.product')
286         context.update({
287             'states': states,
288             'what': what,
289             'location': ids
290         })
291         return product_obj.get_product_available(cr, uid, product_ids, context=context)
292
293     def _product_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
294         ids = id and [id] or []
295         return self._product_get_multi_location(cr, uid, ids, product_ids, context, states)
296
297     def _product_all_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
298         # build the list of ids of children of the location given by id
299         ids = id and [id] or []
300         location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
301         return self._product_get_multi_location(cr, uid, location_ids, product_ids, context, states)
302
303     def _product_virtual_get(self, cr, uid, id, product_ids=False, context={}, states=['done']):
304         return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
305
306     #
307     # TODO:
308     #    Improve this function
309     #
310     # Returns:
311     #    [ (tracking_id, product_qty, location_id) ]
312     #
313     def _product_reserve(self, cr, uid, ids, product_id, product_qty, context={}):
314         result = []
315         amount = 0.0
316         for id in self.search(cr, uid, [('location_id', 'child_of', ids)]):
317             cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id))
318             results = cr.dictfetchall()
319             cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id))
320             results += cr.dictfetchall()
321
322             total = 0.0
323             results2 = 0.0
324             for r in results:
325                 amount = self.pool.get('product.uom')._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
326                 results2 += amount
327                 total += amount
328
329             if total <= 0.0:
330                 continue
331
332             amount = results2
333             if amount > 0:
334                 if amount > min(total, product_qty):
335                     amount = min(product_qty, total)
336                 result.append((amount, id))
337                 product_qty -= amount
338                 total -= amount
339                 if product_qty <= 0.0:
340                     return result
341                 if total <= 0.0:
342                     continue
343         return False
344
345 stock_location()
346
347
348 class stock_tracking(osv.osv):
349     _name = "stock.tracking"
350     _description = "Stock Tracking Lots"
351
352     def checksum(sscc):
353         salt = '31' * 8 + '3'
354         sum = 0
355         for sscc_part, salt_part in zip(sscc, salt):
356             sum += int(sscc_part) * int(salt_part)
357         return (10 - (sum % 10)) % 10
358     checksum = staticmethod(checksum)
359
360     def make_sscc(self, cr, uid, context={}):
361         sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
362         return sequence + str(self.checksum(sequence))
363
364     _columns = {
365         'name': fields.char('Tracking ID', size=64, required=True),
366         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the tracking lots without removing it."),
367         'serial': fields.char('Reference', size=64),
368         'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves Tracked'),
369         'date': fields.datetime('Created Date', required=True),
370     }
371     _defaults = {
372         'active': lambda *a: 1,
373         'name': make_sscc,
374         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
375     }
376
377     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
378         if not args:
379             args = []
380         if not context:
381             context = {}
382         ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
383         ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
384         return self.name_get(cr, user, ids, context)
385
386     def name_get(self, cr, uid, ids, context={}):
387         if not len(ids):
388             return []
389         res = [(r['id'], r['name']+' ['+(r['serial'] or '')+']') for r in self.read(cr, uid, ids, ['name', 'serial'], context)]
390         return res
391
392     def unlink(self, cr, uid, ids, context=None):
393         raise osv.except_osv(_('Error'), _('You can not remove a lot line !'))
394
395 stock_tracking()
396
397
398 #----------------------------------------------------------
399 # Stock Picking
400 #----------------------------------------------------------
401 class stock_picking(osv.osv):
402     _name = "stock.picking"
403     _description = "Picking List"
404
405     def _set_maximum_date(self, cr, uid, ids, name, value, arg, context):
406         if not value:
407             return False
408         if isinstance(ids, (int, long)):
409             ids = [ids]
410         for pick in self.browse(cr, uid, ids, context):
411             sql_str = """update stock_move set
412                     date_planned='%s'
413                 where
414                     picking_id=%d """ % (value, pick.id)
415
416             if pick.max_date:
417                 sql_str += " and (date_planned='" + pick.max_date + "' or date_planned>'" + value + "')"
418             cr.execute(sql_str)
419         return True
420
421     def _set_minimum_date(self, cr, uid, ids, name, value, arg, context):
422         if not value:
423             return False
424         if isinstance(ids, (int, long)):
425             ids = [ids]
426         for pick in self.browse(cr, uid, ids, context):
427             sql_str = """update stock_move set
428                     date_planned='%s'
429                 where
430                     picking_id=%s """ % (value, pick.id)
431             if pick.min_date:
432                 sql_str += " and (date_planned='" + pick.min_date + "' or date_planned<'" + value + "')"
433             cr.execute(sql_str)
434         return True
435
436     def get_min_max_date(self, cr, uid, ids, field_name, arg, context={}):
437         res = {}
438         for id in ids:
439             res[id] = {'min_date': False, 'max_date': False}
440         if not ids:
441             return res
442         cr.execute("""select
443                 picking_id,
444                 min(date_planned),
445                 max(date_planned)
446             from
447                 stock_move
448             where
449                 picking_id=ANY(%s)
450             group by
451                 picking_id""",(ids,))
452         for pick, dt1, dt2 in cr.fetchall():
453             res[pick]['min_date'] = dt1
454             res[pick]['max_date'] = dt2
455         return res
456
457     def create(self, cr, user, vals, context=None):
458         if ('name' not in vals) or (vals.get('name')=='/'):
459             vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking')
460
461         return super(stock_picking, self).create(cr, user, vals, context)
462
463     _columns = {
464         'name': fields.char('Reference', size=64, select=True),
465         'origin': fields.char('Origin', size=64, help="Reference of the document that produced this picking."),
466         'backorder_id': fields.many2one('stock.picking', 'Back Order', help="If the picking is splitted then the picking id in available state of move for this picking is stored in Backorder."),
467         'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal'), ('delivery', 'Delivery')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."),
468         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the picking without removing it."),
469         'note': fields.text('Notes'),
470
471         'location_id': fields.many2one('stock.location', 'Location', help="Keep empty if you produce at the location where the finished products are needed." \
472                 "Set a location if you produce at a fixed location. This can be a partner location " \
473                 "if you subcontract the manufacturing operations."),
474         'location_dest_id': fields.many2one('stock.location', 'Dest. Location',help="Location where the system will stock the finished products."),
475         'move_type': fields.selection([('direct', 'Direct Delivery'), ('one', 'All at once')], 'Delivery Method', required=True, help="It specifies goods to be delivered all at once or by direct delivery"),
476         'state': fields.selection([
477             ('draft', 'Draft'),
478             ('auto', 'Waiting'),
479             ('confirmed', 'Confirmed'),
480             ('assigned', 'Available'),
481             ('done', 'Done'),
482             ('cancel', 'Cancelled'),
483             ], 'State', readonly=True, select=True,
484             help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed picking. \
485             \n* The \'Confirmed\' state is used for stock movement to do with unavailable products. \
486             \n* The \'Available\' state is set automatically when the products are ready to be moved.\
487             \n* The \'Waiting\' state is used in MTO moves when a movement is waiting for another one.'),
488         'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
489                  method=True, store=True, type='datetime', string='Expected Date', select=1, help="Expected date for Picking. Default it takes current date"),
490         'date': fields.datetime('Order Date', help="Date of Order"),
491         'date_done': fields.datetime('Date Done', help="Date of completion"),
492         'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
493                  method=True, store=True, type='datetime', string='Max. Expected Date', select=2),
494         'move_lines': fields.one2many('stock.move', 'picking_id', 'Entry lines', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
495         'delivery_line':fields.one2many('stock.delivery', 'picking_id', 'Delivery lines', readonly=True),
496         'auto_picking': fields.boolean('Auto-Picking'),
497         'address_id': fields.many2one('res.partner.address', 'Partner', help="Address of partner"),
498         'invoice_state': fields.selection([
499             ("invoiced", "Invoiced"),
500             ("2binvoiced", "To Be Invoiced"),
501             ("none", "Not from Picking")], "Invoice Status",
502             select=True, required=True, readonly=True, states={'draft': [('readonly', False)]}),
503         'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
504     }
505     _defaults = {
506         'name': lambda self, cr, uid, context: '/',
507         'active': lambda *a: 1,
508         'state': lambda *a: 'draft',
509         'move_type': lambda *a: 'direct',
510         'type': lambda *a: 'in',
511         'invoice_state': lambda *a: 'none',
512         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
513         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock_picking', context=c)
514     }
515
516     def copy(self, cr, uid, id, default=None, context={}):
517         if default is None:
518             default = {}
519         default = default.copy()
520         if not default.get('name',False):
521             default['name'] = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking')
522         return super(stock_picking, self).copy(cr, uid, id, default, context)
523
524     def onchange_partner_in(self, cr, uid, context, partner_id=None):
525         return {}
526
527     def action_explode(self, cr, uid, moves, context={}):
528         return moves
529
530     def action_confirm(self, cr, uid, ids, context={}):
531         self.write(cr, uid, ids, {'state': 'confirmed'})
532         todo = []
533         for picking in self.browse(cr, uid, ids):
534             for r in picking.move_lines:
535                 if r.state == 'draft':
536                     todo.append(r.id)
537         todo = self.action_explode(cr, uid, todo, context)
538         if len(todo):
539             self.pool.get('stock.move').action_confirm(cr, uid, todo, context)
540         return True
541
542     def test_auto_picking(self, cr, uid, ids):
543         # TODO: Check locations to see if in the same location ?
544         return True
545
546 #    def button_confirm(self, cr, uid, ids, *args):
547 #        for id in ids:
548 #            wf_service = netsvc.LocalService("workflow")
549 #            wf_service.trg_validate(uid, 'stock.picking', id, 'button_confirm', cr)
550 #        self.force_assign(cr, uid, ids, *args)
551 #        return True
552
553     def action_assign(self, cr, uid, ids, *args):
554         for pick in self.browse(cr, uid, ids):
555             move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
556             if not move_ids:
557                 raise osv.except_osv(_('Warning !'),_('Not Available. Moves are not confirmed.'))
558             self.pool.get('stock.move').action_assign(cr, uid, move_ids)
559         return True
560
561     def force_assign(self, cr, uid, ids, *args):
562         wf_service = netsvc.LocalService("workflow")
563         for pick in self.browse(cr, uid, ids):
564             move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
565 #            move_ids = [x.id for x in pick.move_lines]
566             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
567             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
568         return True
569
570     def draft_force_assign(self, cr, uid, ids, *args):
571         wf_service = netsvc.LocalService("workflow")
572         for pick in self.browse(cr, uid, ids):
573             wf_service.trg_validate(uid, 'stock.picking', pick.id,
574                 'button_confirm', cr)
575             #move_ids = [x.id for x in pick.move_lines]
576             #self.pool.get('stock.move').force_assign(cr, uid, move_ids)
577             #wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
578         return True
579
580     def draft_validate(self, cr, uid, ids, *args):
581         wf_service = netsvc.LocalService("workflow")
582         self.draft_force_assign(cr, uid, ids)
583         for pick in self.browse(cr, uid, ids):
584             move_ids = [x.id for x in pick.move_lines]
585             self.pool.get('stock.move').force_assign(cr, uid, move_ids)
586             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
587
588             self.action_move(cr, uid, [pick.id])
589             wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
590         return True
591
592     def cancel_assign(self, cr, uid, ids, *args):
593         wf_service = netsvc.LocalService("workflow")
594         for pick in self.browse(cr, uid, ids):
595             move_ids = [x.id for x in pick.move_lines]
596             self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
597             wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
598         return True
599
600     def action_assign_wkf(self, cr, uid, ids):
601         self.write(cr, uid, ids, {'state': 'assigned'})
602         return True
603
604     def test_finnished(self, cr, uid, ids):
605         move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
606         for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
607             if move.state not in ('done', 'cancel'):
608                 if move.product_qty != 0.0:
609                     return False
610                 else:
611                     move.write(cr, uid, [move.id], {'state': 'done'})
612         return True
613
614     def test_assigned(self, cr, uid, ids):
615         ok = True
616         for pick in self.browse(cr, uid, ids):
617             mt = pick.move_type
618             for move in pick.move_lines:
619                 if (move.state in ('confirmed', 'draft')) and (mt=='one'):
620                     return False
621                 if (mt=='direct') and (move.state=='assigned') and (move.product_qty):
622                     return True
623                 ok = ok and (move.state in ('cancel', 'done', 'assigned'))
624         return ok
625
626     def action_cancel(self, cr, uid, ids, context={}):
627         for pick in self.browse(cr, uid, ids):
628             ids2 = [move.id for move in pick.move_lines]
629             self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
630         self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
631         return True
632
633     #
634     # TODO: change and create a move if not parents
635     #
636     def action_done(self, cr, uid, ids, context=None):
637         self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
638         return True
639
640     def action_move(self, cr, uid, ids, context={}):
641         for pick in self.browse(cr, uid, ids):
642             todo = []
643             for move in pick.move_lines:
644                 if move.state == 'assigned':
645                     todo.append(move.id)
646
647             if len(todo):
648                 self.pool.get('stock.move').action_done(cr, uid, todo,
649                         context=context)
650         return True
651
652     def get_currency_id(self, cr, uid, picking):
653         return False
654
655     def _get_payment_term(self, cr, uid, picking):
656         '''Return {'contact': address, 'invoice': address} for invoice'''
657         partner_obj = self.pool.get('res.partner')
658         partner = picking.address_id.partner_id
659         return partner.property_payment_term and partner.property_payment_term.id or False
660
661     def _get_address_invoice(self, cr, uid, picking):
662         '''Return {'contact': address, 'invoice': address} for invoice'''
663         partner_obj = self.pool.get('res.partner')
664         partner = picking.address_id.partner_id
665
666         return partner_obj.address_get(cr, uid, [partner.id],
667                 ['contact', 'invoice'])
668
669     def _get_comment_invoice(self, cr, uid, picking):
670         '''Return comment string for invoice'''
671         return picking.note or ''
672
673     def _get_price_unit_invoice(self, cr, uid, move_line, type, context=None):
674         '''Return the price unit for the move line'''
675         if context is None:
676             context = {}
677
678         if type in ('in_invoice', 'in_refund'):
679             # Take the user company and pricetype
680             price_type_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.property_valuation_price_type.id
681             pricetype = self.pool.get('product.price.type').browse(cr, uid, price_type_id)
682             context['currency_id'] = move_line.company_id.currency_id.id
683
684             amount_unit = move_line.product_id.price_get(pricetype.field, context)[move_line.product_id.id]
685             return amount_unit
686         else:
687             return move_line.product_id.list_price
688
689     def _get_discount_invoice(self, cr, uid, move_line):
690         '''Return the discount for the move line'''
691         return 0.0
692
693     def _get_taxes_invoice(self, cr, uid, move_line, type):
694         '''Return taxes ids for the move line'''
695         if type in ('in_invoice', 'in_refund'):
696             taxes = move_line.product_id.supplier_taxes_id
697         else:
698             taxes = move_line.product_id.taxes_id
699
700         if move_line.picking_id and move_line.picking_id.address_id and move_line.picking_id.address_id.partner_id:
701             return self.pool.get('account.fiscal.position').map_tax(
702                 cr,
703                 uid,
704                 move_line.picking_id.address_id.partner_id.property_account_position,
705                 taxes
706             )
707         else:
708             return map(lambda x: x.id, taxes)
709
710     def _get_account_analytic_invoice(self, cr, uid, picking, move_line):
711         return False
712
713     def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
714         '''Call after the creation of the invoice line'''
715         return
716
717     def _invoice_hook(self, cr, uid, picking, invoice_id):
718         '''Call after the creation of the invoice'''
719         return
720
721     def action_invoice_create(self, cr, uid, ids, journal_id=False,
722             group=False, type='out_invoice', context=None):
723         '''Return ids of created invoices for the pickings'''
724         if context is None:
725             context = {}
726
727         invoice_obj = self.pool.get('account.invoice')
728         invoice_line_obj = self.pool.get('account.invoice.line')
729         invoices_group = {}
730         res = {}
731
732         for picking in self.browse(cr, uid, ids, context=context):
733             if picking.invoice_state != '2binvoiced':
734                 continue
735             payment_term_id = False
736             partner = picking.address_id and picking.address_id.partner_id
737             if not partner:
738                 raise osv.except_osv(_('Error, no partner !'),
739                     _('Please put a partner on the picking list if you want to generate invoice.'))
740
741             if type in ('out_invoice', 'out_refund'):
742                 account_id = partner.property_account_receivable.id
743                 payment_term_id = self._get_payment_term(cr, uid, picking)
744             else:
745                 account_id = partner.property_account_payable.id
746
747             address_contact_id, address_invoice_id = \
748                     self._get_address_invoice(cr, uid, picking).values()
749
750             comment = self._get_comment_invoice(cr, uid, picking)
751             if group and partner.id in invoices_group:
752                 invoice_id = invoices_group[partner.id]
753                 invoice = invoice_obj.browse(cr, uid, invoice_id)
754                 invoice_vals = {
755                     'name': (invoice.name or '') + ', ' + (picking.name or ''),
756                     'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
757                     'comment': (comment and (invoice.comment and invoice.comment+"\n"+comment or comment)) or (invoice.comment and invoice.comment or ''),
758                     'date_invoice':context.get('date_inv',False)
759                 }
760                 invoice_obj.write(cr, uid, [invoice_id], invoice_vals, context=context)
761             else:
762                 invoice_vals = {
763                     'name': picking.name,
764                     'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
765                     'type': type,
766                     'account_id': account_id,
767                     'partner_id': partner.id,
768                     'address_invoice_id': address_invoice_id,
769                     'address_contact_id': address_contact_id,
770                     'comment': comment,
771                     'payment_term': payment_term_id,
772                     'fiscal_position': partner.property_account_position.id,
773                     'date_invoice': context.get('date_inv',False),
774                     'company_id': picking.company_id.id,
775                     }
776                 cur_id = self.get_currency_id(cr, uid, picking)
777                 if cur_id:
778                     invoice_vals['currency_id'] = cur_id
779                 if journal_id:
780                     invoice_vals['journal_id'] = journal_id
781                 invoice_id = invoice_obj.create(cr, uid, invoice_vals,
782                         context=context)
783                 invoices_group[partner.id] = invoice_id
784             res[picking.id] = invoice_id
785             for move_line in picking.move_lines:
786                 origin = move_line.picking_id.name
787                 if move_line.picking_id.origin:
788                     origin += ':' + move_line.picking_id.origin
789                 if group:
790                     name = (picking.name or '') + '-' + move_line.name
791                 else:
792                     name = move_line.name
793
794                 if type in ('out_invoice', 'out_refund'):
795                     account_id = move_line.product_id.product_tmpl_id.\
796                             property_account_income.id
797                     if not account_id:
798                         account_id = move_line.product_id.categ_id.\
799                                 property_account_income_categ.id
800                 else:
801                     account_id = move_line.product_id.product_tmpl_id.\
802                             property_account_expense.id
803                     if not account_id:
804                         account_id = move_line.product_id.categ_id.\
805                                 property_account_expense_categ.id
806
807                 price_unit = self._get_price_unit_invoice(cr, uid,
808                         move_line, type)
809                 discount = self._get_discount_invoice(cr, uid, move_line)
810                 tax_ids = self._get_taxes_invoice(cr, uid, move_line, type)
811                 account_analytic_id = self._get_account_analytic_invoice(cr, uid, picking, move_line)
812
813                 #set UoS if it's a sale and the picking doesn't have one
814                 uos_id = move_line.product_uos and move_line.product_uos.id or False
815                 if not uos_id and type in ('out_invoice', 'out_refund'):
816                     uos_id = move_line.product_uom.id
817
818                 account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, partner.property_account_position, account_id)
819                 notes = False
820                 if move_line.sale_line_id:
821                     notes = move_line.sale_line_id.notes
822                 elif move_line.purchase_line_id:
823                     notes = move_line.purchase_line_id.notes
824
825                 invoice_line_id = invoice_line_obj.create(cr, uid, {
826                     'name': name,
827                     'origin': origin,
828                     'invoice_id': invoice_id,
829                     'uos_id': uos_id,
830                     'product_id': move_line.product_id.id,
831                     'account_id': account_id,
832                     'price_unit': price_unit,
833                     'discount': discount,
834                     'quantity': move_line.product_uos_qty or move_line.product_qty,
835                     'invoice_line_tax_id': [(6, 0, tax_ids)],
836                     'account_analytic_id': account_analytic_id,
837                     'note': notes,
838                     }, context=context)
839                 self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
840
841             invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
842                     set_total=(type in ('in_invoice', 'in_refund')))
843             self.write(cr, uid, [picking.id], {
844                 'invoice_state': 'invoiced',
845                 }, context=context)
846             self._invoice_hook(cr, uid, picking, invoice_id)
847         self.write(cr, uid, res.keys(), {
848             'invoice_state': 'invoiced',
849             }, context=context)
850         return res
851
852     def test_cancel(self, cr, uid, ids, context={}):
853         for pick in self.browse(cr, uid, ids, context=context):
854             if not pick.move_lines:
855                 return False
856             for move in pick.move_lines:
857                 if move.state not in ('cancel',):
858                     return False
859         return True
860
861     def unlink(self, cr, uid, ids, context=None):
862         for pick in self.browse(cr, uid, ids, context=context):
863             if pick.state in ['done','cancel']:
864                 raise osv.except_osv(_('Error'), _('You cannot remove the picking which is in %s state !')%(pick.state,))
865             elif pick.state in ['confirmed','assigned']:
866                 ids2 = [move.id for move in pick.move_lines]
867                 context.update({'call_unlink':True})
868                 self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
869             else:
870                 continue
871         return super(stock_picking, self).unlink(cr, uid, ids, context=context)
872
873     def do_partial(self, cr, uid, ids, partial_datas, context={}):
874         """
875         @ partial_datas : dict. contain details of partial picking
876                           like partner_id, address_id, delivery_date, delivery moves with product_id, product_qty, uom
877         """
878         res = {}
879         move_obj = self.pool.get('stock.move')
880         delivery_obj = self.pool.get('stock.delivery')
881         product_obj = self.pool.get('product.product')
882         currency_obj = self.pool.get('res.currency')
883         users_obj = self.pool.get('res.users')
884         uom_obj = self.pool.get('product.uom')
885         price_type_obj = self.pool.get('product.price.type')
886         sequence_obj = self.pool.get('ir.sequence')
887         wf_service = netsvc.LocalService("workflow")
888         partner_id = partial_datas.get('partner_id', False)
889         address_id = partial_datas.get('address_id', False)
890         delivery_date = partial_datas.get('delivery_date', False)
891         for pick in self.browse(cr, uid, ids, context=context):
892             new_picking = None
893             new_moves = []
894
895             complete, too_many, too_few = [], [], []
896             move_product_qty = {}
897             for move in pick.move_lines:
898                 if move.state in ('done', 'cancel'):
899                     continue
900                 partial_data = partial_datas.get('move%s'%(move.id), False)
901                 assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
902                 product_qty = partial_data.get('product_qty',0.0)
903                 move_product_qty[move.id] = product_qty
904                 product_uom = partial_data.get('product_uom',False)
905                 product_price = partial_data.get('product_price',0.0)
906                 product_currency = partial_data.get('product_currency',False)
907                 if move.product_qty == product_qty:
908                     complete.append(move)
909                 elif move.product_qty > product_qty:
910                     too_few.append(move)
911                 else:
912                     too_many.append(move)
913
914                 # Average price computation
915                 if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
916                     product = product_obj.browse(cr, uid, move.product_id.id)
917                     user = users_obj.browse(cr, uid, uid)
918                     context['currency_id'] = move.company_id.currency_id.id
919                     qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
920                     pricetype = False
921                     if user.company_id.property_valuation_price_type:
922                         pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
923                     if pricetype and qty > 0:
924                         new_price = currency_obj.compute(cr, uid, product_currency,
925                                 user.company_id.currency_id.id, product_price)
926                         new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
927                                 product.uom_id.id)
928                         if product.qty_available <= 0:
929                             new_std_price = new_price
930                         else:
931                             # Get the standard price
932                             amount_unit = product.price_get(pricetype.field, context)[product.id]
933                             new_std_price = ((amount_unit * product.qty_available)\
934                                 + (new_price * qty))/(product.qty_available + qty)
935
936                         # Write the field according to price type field
937                         product_obj.write(cr, uid, [product.id],
938                                 {pricetype.field: new_std_price})
939                         move_obj.write(cr, uid, [move.id], {'price_unit': new_price})
940
941
942             for move in too_few:
943                 product_qty = move_product_qty[move.id]
944                 if not new_picking:
945
946                     new_picking = self.copy(cr, uid, pick.id,
947                             {
948                                 'name': sequence_obj.get(cr, uid, 'stock.picking.%s'%(pick.type)),
949                                 'move_lines' : [],
950                                 'state':'draft',
951                             })
952                 if product_qty != 0:
953
954                     new_obj = move_obj.copy(cr, uid, move.id,
955                         {
956                             'product_qty' : product_qty,
957                             'product_uos_qty': product_qty, #TODO: put correct uos_qty
958                             'picking_id' : new_picking,
959                             'state': 'assigned',
960                             'move_dest_id': False,
961                             'price_unit': move.price_unit,
962                         })
963
964                 move_obj.write(cr, uid, [move.id],
965                         {
966                             'product_qty' : move.product_qty - product_qty,
967                             'product_uos_qty':move.product_qty - product_qty, #TODO: put correct uos_qty
968
969                         })
970
971             if new_picking:
972                 move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
973                 for move in too_many:
974                     product_qty = move_product_qty[move.id]
975                     move_obj.write(cr, uid, [move.id],
976                             {
977                                 'product_qty' : product_qty,
978                                 'product_uos_qty': product_qty, #TODO: put correct uos_qty
979                                 'picking_id': new_picking,
980                             })
981             else:
982                 for move in too_many:
983                     product_qty = move_product_qty[move.id]
984                     move_obj.write(cr, uid, [move.id],
985                             {
986                                 'product_qty': product_qty,
987                                 'product_uos_qty': product_qty #TODO: put correct uos_qty
988                             })
989
990             # At first we confirm the new picking (if necessary)
991             if new_picking:
992                 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
993             # Then we finish the good picking
994             if new_picking:
995                 self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
996                 self.action_move(cr, uid, [new_picking])
997                 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr)
998                 wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
999                 delivered_pack_id = new_picking
1000             else:
1001                 self.action_move(cr, uid, [pick.id])
1002                 wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
1003                 delivered_pack_id = pick.id
1004
1005             delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
1006             delivery_id = delivery_obj.create(cr, uid, {
1007                 'name':  delivered_pack.name,
1008                 'partner_id': partner_id,
1009                 'address_id': address_id,
1010                 'date': delivery_date,
1011                 'picking_id' :  pick.id,
1012                 'move_delivered' : [(6,0, map(lambda x:x.id, delivered_pack.move_lines))]
1013             }, context=context)
1014             res[pick.id] = {'delivered_picking': delivered_pack.id or False}
1015         return res
1016
1017 stock_picking()
1018
1019
1020 class stock_production_lot(osv.osv):
1021     def name_get(self, cr, uid, ids, context={}):
1022         if not ids:
1023             return []
1024         reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
1025         res = []
1026         for record in reads:
1027             name = record['name']
1028             prefix = record['prefix']
1029             if prefix:
1030                 name = prefix + '/' + name
1031             if record['ref']:
1032                 name = '%s [%s]' % (name, record['ref'])
1033             res.append((record['id'], name))
1034         return res
1035
1036     _name = 'stock.production.lot'
1037     _description = 'Production lot'
1038
1039     def _get_stock(self, cr, uid, ids, field_name, arg, context={}):
1040         if 'location_id' not in context:
1041             locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
1042         else:
1043             locations = context['location_id'] and [context['location_id']] or []
1044
1045         if isinstance(ids, (int, long)):
1046             ids = [ids]
1047
1048         res = {}.fromkeys(ids, 0.0)
1049         if locations:
1050             cr.execute('''select
1051                     prodlot_id,
1052                     sum(name)
1053                 from
1054                     stock_report_prodlots
1055                 where
1056                     location_id =ANY(%s) and prodlot_id =ANY(%s) group by prodlot_id''',(locations,ids,))
1057             res.update(dict(cr.fetchall()))
1058         return res
1059
1060     def _stock_search(self, cr, uid, obj, name, args, context):
1061         locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
1062         cr.execute('''select
1063                 prodlot_id,
1064                 sum(name)
1065             from
1066                 stock_report_prodlots
1067             where
1068                 location_id =ANY(%s) group by prodlot_id
1069             having  sum(name) '''+ str(args[0][1]) + str(args[0][2]),(locations,))
1070         res = cr.fetchall()
1071         ids = [('id', 'in', map(lambda x: x[0], res))]
1072         return ids
1073
1074     _columns = {
1075         'name': fields.char('Serial', size=64, required=True),
1076         'ref': fields.char('Internal Reference', size=256),
1077         'prefix': fields.char('Prefix', size=64),
1078         'product_id': fields.many2one('product.product', 'Product', required=True),
1079         'date': fields.datetime('Created Date', required=True),
1080         'stock_available': fields.function(_get_stock, fnct_search=_stock_search, method=True, type="float", string="Available", select="2"),
1081         'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
1082         'company_id': fields.many2one('res.company','Company',select=1),
1083     }
1084     _defaults = {
1085         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1086         'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
1087         'product_id': lambda x, y, z, c: c.get('product_id', False),
1088     }
1089     _sql_constraints = [
1090         ('name_ref_uniq', 'unique (name, ref)', 'The serial/ref must be unique !'),
1091     ]
1092
1093 stock_production_lot()
1094
1095 class stock_production_lot_revision(osv.osv):
1096     _name = 'stock.production.lot.revision'
1097     _description = 'Production lot revisions'
1098     _columns = {
1099         'name': fields.char('Revision Name', size=64, required=True),
1100         'description': fields.text('Description'),
1101         'date': fields.date('Revision Date'),
1102         'indice': fields.char('Revision', size=16),
1103         'author_id': fields.many2one('res.users', 'Author'),
1104         'lot_id': fields.many2one('stock.production.lot', 'Production lot', select=True, ondelete='cascade'),
1105         'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
1106     }
1107
1108     _defaults = {
1109         'author_id': lambda x, y, z, c: z,
1110         'date': lambda *a: time.strftime('%Y-%m-%d'),
1111     }
1112
1113 stock_production_lot_revision()
1114
1115 class stock_delivery(osv.osv):
1116
1117     """ Tracability of partialdeliveries """
1118
1119     _name = "stock.delivery"
1120     _description = "Delivery"
1121     _columns = {
1122         'name': fields.char('Name', size=60, required=True),
1123         'date': fields.datetime('Date', required=True),
1124         'partner_id': fields.many2one('res.partner', 'Partner', required=True),
1125         'address_id': fields.many2one('res.partner.address', 'Address', required=True),
1126         'move_delivered':fields.one2many('stock.move', 'delivered_id', 'Move Delivered'),
1127         'picking_id': fields.many2one('stock.picking', 'Picking list'),
1128
1129     }
1130 stock_delivery()
1131 # ----------------------------------------------------
1132 # Move
1133 # ----------------------------------------------------
1134
1135 #
1136 # Fields:
1137 #   location_dest_id is only used for predicting futur stocks
1138 #
1139 class stock_move(osv.osv):
1140     def _getSSCC(self, cr, uid, context={}):
1141         cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
1142         res = cr.fetchone()
1143         return (res and res[0]) or False
1144     _name = "stock.move"
1145     _description = "Stock Move"
1146
1147     def name_get(self, cr, uid, ids, context={}):
1148         res = []
1149         for line in self.browse(cr, uid, ids, context):
1150             res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))
1151         return res
1152
1153     def _check_tracking(self, cr, uid, ids):
1154         for move in self.browse(cr, uid, ids):
1155             if not move.prodlot_id and \
1156                (move.state == 'done' and \
1157                ( \
1158                    (move.product_id.track_production and move.location_id.usage=='production') or \
1159                    (move.product_id.track_production and move.location_dest_id.usage=='production') or \
1160                    (move.product_id.track_incoming and move.location_id.usage in ('supplier','internal')) or \
1161                    (move.product_id.track_outgoing and move.location_dest_id.usage in ('customer','internal')) \
1162                )):
1163                 return False
1164         return True
1165
1166     def _check_product_lot(self, cr, uid, ids):
1167         for move in self.browse(cr, uid, ids):
1168             if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):
1169                 return False
1170         return True
1171
1172     _columns = {
1173         'name': fields.char('Name', size=64, required=True, select=True),
1174         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
1175
1176         'date': fields.datetime('Created Date'),
1177         'date_planned': fields.datetime('Date', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
1178
1179         'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
1180
1181         'product_qty': fields.float('Quantity', required=True),
1182         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
1183         'product_uos_qty': fields.float('Quantity (UOS)'),
1184         'product_uos': fields.many2one('product.uom', 'Product UOS'),
1185         'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
1186
1187         'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."),
1188         'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, select=True, help="Location where the system will stock the finished products."),
1189         'address_id': fields.many2one('res.partner.address', 'Dest. Address', help="Address where goods are to be delivered"),
1190
1191         'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="Production lot is used to put a serial number on the production"),
1192         'tracking_id': fields.many2one('stock.tracking', 'Tracking Lot', select=True, help="Tracking lot is the code that will be put on the logistical unit/pallet"),
1193 #       'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),
1194
1195         'auto_validate': fields.boolean('Auto Validate'),
1196
1197         'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),
1198         'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
1199         'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
1200         'picking_id': fields.many2one('stock.picking', 'Picking List', select=True),
1201
1202         'note': fields.text('Notes'),
1203
1204         'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')], 'State', readonly=True, select=True,
1205                                   help='When the stock move is created it is in the \'Draft\' state.\n After that it is set to \'Confirmed\' state.\n If stock is available state is set to \'Avaiable\'.\n When the picking it done the state is \'Done\'.\
1206                                   \nThe state is \'Waiting\' if the move is waiting for another one.'),
1207         'price_unit': fields.float('Unit Price',
1208             digits_compute= dp.get_precision('Account')),
1209         'company_id': fields.many2one('res.company', 'Company', required=True,select=1),
1210         'partner_id': fields.related('picking_id','address_id','partner_id',type='many2one', relation="res.partner", string="Partner"),
1211         'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Orders"),
1212         'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Origin"),
1213         'move_stock_return_history': fields.many2many('stock.move', 'stock_move_return_history', 'move_id', 'return_move_id', 'Move Return History',readonly=True),
1214         'delivered_id': fields.many2one('stock.delivery', 'Product delivered'),
1215         'scraped': fields.boolean('Scraped'),
1216     }
1217     _constraints = [
1218         (_check_tracking,
1219             'You must assign a production lot for this product',
1220             ['prodlot_id']),
1221         (_check_product_lot,
1222             'You try to assign a lot which is not from the same product',
1223             ['prodlot_id'])]
1224
1225     def _default_location_destination(self, cr, uid, context={}):
1226         if context.get('move_line', []):
1227             if context['move_line'][0]:
1228                 if isinstance(context['move_line'][0], (tuple, list)):
1229                     return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
1230                 else:
1231                     move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1232                     return move_list and move_list['location_dest_id'][0] or False
1233         if context.get('address_out_id', False):
1234             return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id
1235         return False
1236
1237     def _default_location_source(self, cr, uid, context={}):
1238         if context.get('move_line', []):
1239             try:
1240                 return context['move_line'][0][2]['location_id']
1241             except:
1242                 pass
1243         if context.get('address_in_id', False):
1244             return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1245         return False
1246
1247     _defaults = {
1248         'location_id': _default_location_source,
1249         'location_dest_id': _default_location_destination,
1250         'state': lambda *a: 'draft',
1251         'priority': lambda *a: '1',
1252         'scraped' : lambda *a:False,
1253         'product_qty': lambda *a: 1.0,
1254         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1255         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1256         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c)
1257     }
1258
1259     def copy(self, cr, uid, id, default=None, context={}):
1260         if default is None:
1261             default = {}
1262         default = default.copy()
1263         default['move_stock_return_history'] = []
1264         return super(stock_move, self).copy(cr, uid, id, default, context)
1265
1266     def create(self, cr, user, vals, context=None):
1267         if vals.get('move_stock_return_history',False):
1268             vals['move_stock_return_history'] = []
1269         return super(stock_move, self).create(cr, user, vals, context)
1270
1271     def _auto_init(self, cursor, context):
1272         res = super(stock_move, self)._auto_init(cursor, context)
1273         cursor.execute('SELECT indexname \
1274                 FROM pg_indexes \
1275                 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1276         if not cursor.fetchone():
1277             cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1278                     ON stock_move (location_id, location_dest_id, product_id, state)')
1279             cursor.commit()
1280         return res
1281
1282     def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_id=False, context=None):
1283         if not prodlot_id or not loc_id:
1284             return {}
1285         ctx = context and context.copy() or {}
1286         ctx['location_id'] = loc_id
1287         prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1288         location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1289         warning = {}
1290         if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1291             warning = {
1292                 'title': 'Bad Lot Assignation !',
1293                 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1294             }
1295         return {'warning': warning}
1296
1297     def onchange_quantity(self, cr, uid, ids, product_id, product_qty, product_uom, product_uos):
1298         result = {
1299                   'product_uos_qty': 0.00
1300           }
1301
1302         if (not product_id) or (product_qty <=0.0):
1303             return {'value': result}
1304
1305         product_obj = self.pool.get('product.product')
1306         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1307
1308         if product_uos and product_uom and (product_uom != product_uos):
1309             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1310         else:
1311             result['product_uos_qty'] = product_qty
1312
1313         return {'value': result}
1314
1315     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, address_id=False):
1316         if not prod_id:
1317             return {}
1318         lang = False
1319         if address_id:
1320             addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1321             if addr_rec:
1322                 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1323         ctx = {'lang': lang}
1324
1325         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1326         uos_id  = product.uos_id and product.uos_id.id or False
1327         result = {
1328             'product_uom': product.uom_id.id,
1329             'product_uos': uos_id,
1330             'product_qty': 1.00,
1331             'product_uos_qty' : self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty']
1332         }
1333         if not ids:
1334             result['name'] = product.partner_ref
1335         if loc_id:
1336             result['location_id'] = loc_id
1337         if loc_dest_id:
1338             result['location_dest_id'] = loc_dest_id
1339         return {'value': result}
1340
1341     def _chain_compute(self, cr, uid, moves, context={}):
1342         result = {}
1343         for m in moves:
1344             dest = self.pool.get('stock.location').chained_location_get(
1345                 cr,
1346                 uid,
1347                 m.location_dest_id,
1348                 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1349                 m.product_id,
1350                 context
1351             )
1352             if dest:
1353                 if dest[1] == 'transparent':
1354                     self.write(cr, uid, [m.id], {
1355                         'date_planned': (datetime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1356                             relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1357                         'location_dest_id': dest[0].id})
1358                 else:
1359                     result.setdefault(m.picking_id, [])
1360                     result[m.picking_id].append( (m, dest) )
1361         return result
1362
1363     def action_confirm(self, cr, uid, ids, context={}):
1364 #        ids = map(lambda m: m.id, moves)
1365         moves = self.browse(cr, uid, ids)
1366         self.write(cr, uid, ids, {'state': 'confirmed'})
1367         i = 0
1368
1369         def create_chained_picking(self, cr, uid, moves, context):
1370             new_moves = []
1371             for picking, todo in self._chain_compute(cr, uid, moves, context).items():
1372                 ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
1373                 pickid = self.pool.get('stock.picking').create(cr, uid, {
1374                     'name': picking.name,
1375                     'origin': str(picking.origin or ''),
1376                     'type': ptype,
1377                     'note': picking.note,
1378                     'move_type': picking.move_type,
1379                     'auto_picking': todo[0][1][1] == 'auto',
1380                     'address_id': picking.address_id.id,
1381                     'invoice_state': 'none'
1382                 })
1383                 for move, (loc, auto, delay) in todo:
1384                     # Is it smart to copy ? May be it's better to recreate ?
1385                     new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {
1386                         'location_id': move.location_dest_id.id,
1387                         'location_dest_id': loc.id,
1388                         'date_moved': time.strftime('%Y-%m-%d'),
1389                         'picking_id': pickid,
1390                         'state': 'waiting',
1391                         'move_history_ids': [],
1392                         'date_planned': (datetime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
1393                         'move_history_ids2': []}
1394                     )
1395                     self.pool.get('stock.move').write(cr, uid, [move.id], {
1396                         'move_dest_id': new_id,
1397                         'move_history_ids': [(4, new_id)]
1398                     })
1399                     new_moves.append(self.browse(cr, uid, [new_id])[0])
1400                 wf_service = netsvc.LocalService("workflow")
1401                 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1402             if new_moves:
1403                 create_chained_picking(self, cr, uid, new_moves, context)
1404         create_chained_picking(self, cr, uid, moves, context)
1405         return []
1406
1407     def action_assign(self, cr, uid, ids, *args):
1408         todo = []
1409         for move in self.browse(cr, uid, ids):
1410             if move.state in ('confirmed', 'waiting'):
1411                 todo.append(move.id)
1412         res = self.check_assign(cr, uid, todo)
1413         return res
1414
1415     def force_assign(self, cr, uid, ids, context={}):
1416         self.write(cr, uid, ids, {'state': 'assigned'})
1417         return True
1418
1419     def cancel_assign(self, cr, uid, ids, context={}):
1420         self.write(cr, uid, ids, {'state': 'confirmed'})
1421         return True
1422
1423     #
1424     # Duplicate stock.move
1425     #
1426     def check_assign(self, cr, uid, ids, context={}):
1427         done = []
1428         count = 0
1429         pickings = {}
1430         for move in self.browse(cr, uid, ids):
1431             if move.product_id.type == 'consu':
1432                 if move.state in ('confirmed', 'waiting'):
1433                     done.append(move.id)
1434                 pickings[move.picking_id.id] = 1
1435                 continue
1436             if move.state in ('confirmed', 'waiting'):
1437                 res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id})
1438                 if res:
1439                     #_product_available_test depends on the next status for correct functioning
1440                     #the test does not work correctly if the same product occurs multiple times
1441                     #in the same order. This is e.g. the case when using the button 'split in two' of
1442                     #the stock outgoing form
1443                     self.write(cr, uid, move.id, {'state':'assigned'})
1444                     done.append(move.id)
1445                     pickings[move.picking_id.id] = 1
1446                     r = res.pop(0)
1447                     cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1448
1449                     while res:
1450                         r = res.pop(0)
1451                         move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1452                         done.append(move_id)
1453                         #cr.execute('insert into stock_move_history_ids values (%s,%s)', (move.id,move_id))
1454         if done:
1455             count += len(done)
1456             self.write(cr, uid, done, {'state': 'assigned'})
1457
1458         if count:
1459             for pick_id in pickings:
1460                 wf_service = netsvc.LocalService("workflow")
1461                 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1462         return count
1463
1464     #
1465     # Cancel move => cancel others move and pickings
1466     #
1467     def action_cancel(self, cr, uid, ids, context={}):
1468         if not len(ids):
1469             return True
1470         pickings = {}
1471         for move in self.browse(cr, uid, ids):
1472             if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1473                 if move.picking_id:
1474                     pickings[move.picking_id.id] = True
1475             if move.move_dest_id and move.move_dest_id.state == 'waiting':
1476                 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1477                 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1478                     wf_service = netsvc.LocalService("workflow")
1479                     wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1480         self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1481         if not context.get('call_unlink',False):
1482             for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1483                 if all(move.state == 'cancel' for move in pick.move_lines):
1484                     self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1485
1486         wf_service = netsvc.LocalService("workflow")
1487         for id in ids:
1488             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1489         #self.action_cancel(cr,uid, ids2, context)
1490         return True
1491
1492     def action_done(self, cr, uid, ids, context=None):
1493         track_flag = False
1494         picking_ids = []
1495         for move in self.browse(cr, uid, ids):
1496             if move.picking_id: picking_ids.append(move.picking_id.id)
1497             if move.move_dest_id.id and (move.state != 'done'):
1498                 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1499                 if move.move_dest_id.state in ('waiting', 'confirmed'):
1500                     self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1501                     if move.move_dest_id.picking_id:
1502                         wf_service = netsvc.LocalService("workflow")
1503                         wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1504                     else:
1505                         pass
1506                         # self.action_done(cr, uid, [move.move_dest_id.id])
1507                     if move.move_dest_id.auto_validate:
1508                         self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1509
1510             #
1511             # Accounting Entries
1512             #
1513             acc_src = None
1514             acc_dest = None
1515             if move.location_id.account_id:
1516                 acc_src = move.location_id.account_id.id
1517             if move.location_dest_id.account_id:
1518                 acc_dest = move.location_dest_id.account_id.id
1519             if acc_src or acc_dest:
1520                 test = [('product.product', move.product_id.id)]
1521                 if move.product_id.categ_id:
1522                     test.append( ('product.category', move.product_id.categ_id.id) )
1523                 if not acc_src:
1524                     acc_src = move.product_id.product_tmpl_id.\
1525                             property_stock_account_input.id
1526                     if not acc_src:
1527                         acc_src = move.product_id.categ_id.\
1528                                 property_stock_account_input_categ.id
1529                     if not acc_src:
1530                         raise osv.except_osv(_('Error!'),
1531                                 _('There is no stock input account defined ' \
1532                                         'for this product: "%s" (id: %d)') % \
1533                                         (move.product_id.name,
1534                                             move.product_id.id,))
1535                 if not acc_dest:
1536                     acc_dest = move.product_id.product_tmpl_id.\
1537                             property_stock_account_output.id
1538                     if not acc_dest:
1539                         acc_dest = move.product_id.categ_id.\
1540                                 property_stock_account_output_categ.id
1541                     if not acc_dest:
1542                         raise osv.except_osv(_('Error!'),
1543                                 _('There is no stock output account defined ' \
1544                                         'for this product: "%s" (id: %d)') % \
1545                                         (move.product_id.name,
1546                                             move.product_id.id,))
1547                 if not move.product_id.categ_id.property_stock_journal.id:
1548                     raise osv.except_osv(_('Error!'),
1549                         _('There is no journal defined '\
1550                             'on the product category: "%s" (id: %d)') % \
1551                             (move.product_id.categ_id.name,
1552                                 move.product_id.categ_id.id,))
1553                 journal_id = move.product_id.categ_id.property_stock_journal.id
1554                 if acc_src != acc_dest:
1555                     ref = move.picking_id and move.picking_id.name or False
1556                     product_uom_obj = self.pool.get('product.uom')
1557                     default_uom = move.product_id.uom_id.id
1558                     date = time.strftime('%Y-%m-%d')
1559                     q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1560                     if move.product_id.cost_method == 'average' and move.price_unit:
1561                         amount = q * move.price_unit
1562                     # Base computation on valuation price type
1563                     else:
1564                         company_id=move.company_id.id
1565                         context['currency_id']=move.company_id.currency_id.id
1566                         pricetype=self.pool.get('product.price.type').browse(cr,uid,move.company_id.property_valuation_price_type.id)
1567                         amount_unit=move.product_id.price_get(pricetype.field, context)[move.product_id.id]
1568                         amount=amount_unit * q or 1.0
1569                         # amount = q * move.product_id.standard_price
1570
1571                     partner_id = False
1572                     if move.picking_id:
1573                         partner_id = move.picking_id.address_id and (move.picking_id.address_id.partner_id and move.picking_id.address_id.partner_id.id or False) or False
1574                     lines = [
1575                             (0, 0, {
1576                                 'name': move.name,
1577                                 'quantity': move.product_qty,
1578                                 'product_id': move.product_id and move.product_id.id or False,
1579                                 'credit': amount,
1580                                 'account_id': acc_src,
1581                                 'ref': ref,
1582                                 'date': date,
1583                                 'partner_id': partner_id}),
1584                             (0, 0, {
1585                                 'name': move.name,
1586                                 'product_id': move.product_id and move.product_id.id or False,
1587                                 'quantity': move.product_qty,
1588                                 'debit': amount,
1589                                 'account_id': acc_dest,
1590                                 'ref': ref,
1591                                 'date': date,
1592                                 'partner_id': partner_id})
1593                     ]
1594                     self.pool.get('account.move').create(cr, uid, {
1595                         'name': move.name,
1596                         'journal_id': journal_id,
1597                         'line_id': lines,
1598                         'ref': ref,
1599                     })
1600         self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1601         for pick in self.pool.get('stock.picking').browse(cr, uid, picking_ids):
1602             if all(move.state == 'done' for move in pick.move_lines):
1603                 self.pool.get('stock.picking').action_done(cr, uid, [pick.id])
1604
1605         wf_service = netsvc.LocalService("workflow")
1606         for id in ids:
1607             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1608         return True
1609
1610     def unlink(self, cr, uid, ids, context=None):
1611         for move in self.browse(cr, uid, ids, context=context):
1612             if move.state != 'draft':
1613                 raise osv.except_osv(_('UserError'),
1614                         _('You can only delete draft moves.'))
1615         return super(stock_move, self).unlink(
1616             cr, uid, ids, context=context)
1617
1618     def _create_lot(self, cr, uid, ids, product_id, prefix=False):
1619         prodlot_obj = self.pool.get('stock.production.lot')
1620         ir_sequence_obj = self.pool.get('ir.sequence')
1621         sequence = ir_sequence_obj.get(cr, uid, 'stock.lot.serial')
1622         if not sequence:
1623             raise osv.except_osv(_('Error!'), _('No production sequence defined'))
1624         prodlot_id = prodlot_obj.create(cr, uid, {'name': sequence, 'prefix': prefix}, {'product_id': product_id})
1625         prodlot = prodlot_obj.browse(cr, uid, prodlot_id)
1626         ref = ','.join(map(lambda x:str(x),ids))
1627         if prodlot.ref:
1628             ref = '%s, %s' % (prodlot.ref, ref)
1629         prodlot_obj.write(cr, uid, [prodlot_id], {'ref': ref})
1630         return prodlot_id
1631
1632     def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1633         '''
1634         Move the scrap/damaged product into scrap location
1635
1636         @ param cr: the database cursor
1637         @ param uid: the user id
1638         @ param ids: ids of stock move object to be scraped
1639         @ param quantity : specify scrap qty
1640         @ param location_id : specify scrap location
1641         @ param context: context arguments
1642
1643         @ return: Scraped lines
1644         '''
1645         if quantity <= 0:
1646             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1647         res = []
1648         for move in self.browse(cr, uid, ids, context=context):
1649             move_qty = move.product_qty
1650             uos_qty = quantity / move_qty * move.product_uos_qty
1651             default_val = {
1652                     'product_qty': quantity,
1653                     'product_uos_qty': uos_qty,
1654                     'state': move.state,
1655                     'scraped' : True,
1656                     'location_dest_id': location_id
1657                 }
1658             new_move = self.copy(cr, uid, move.id, default_val)
1659             #self.write(cr, uid, [new_move], {'move_history_ids':[(4,move.id)]}) #TODO : to track scrap moves
1660             res += [new_move]
1661         self.action_done(cr, uid, res)
1662         return res
1663
1664     def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
1665         '''
1666         Split Stock Move lines into production lot which specified split by quantity.
1667
1668         @ param cr: the database cursor
1669         @ param uid: the user id
1670         @ param ids: ids of stock move object to be splited
1671         @ param split_by_qty : specify split by qty
1672         @ param prefix : specify prefix of production lot
1673         @ param with_lot : if true, prodcution lot will assign for split line otherwise not.
1674         @ param context: context arguments
1675
1676         @ return: splited move lines
1677         '''
1678
1679         if quantity <= 0:
1680             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1681
1682         res = []
1683
1684         for move in self.browse(cr, uid, ids):
1685             if split_by_qty <= 0 or quantity == 0:
1686                 return res
1687
1688             uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
1689
1690             quantity_rest = quantity % split_by_qty
1691             uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
1692
1693             update_val = {
1694                 'product_qty': split_by_qty,
1695                 'product_uos_qty': uos_qty,
1696             }
1697             for idx in range(int(quantity//split_by_qty)):
1698                 if not idx and move.product_qty<=quantity:
1699                     current_move = move.id
1700                 else:
1701                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
1702                 res.append(current_move)
1703                 if with_lot:
1704                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1705
1706                 self.write(cr, uid, [current_move], update_val)
1707
1708
1709             if quantity_rest > 0:
1710                 idx = int(quantity//split_by_qty)
1711                 update_val['product_qty'] = quantity_rest
1712                 update_val['product_uos_qty'] = uos_qty_rest
1713                 if not idx and move.product_qty<=quantity:
1714                     current_move = move.id
1715                 else:
1716                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
1717
1718                 res.append(current_move)
1719
1720
1721                 if with_lot:
1722                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1723
1724                 self.write(cr, uid, [current_move], update_val)
1725         return res
1726
1727     def action_consume(self, cr, uid, ids, quantity, location_id=False,  context=None):
1728         '''
1729         Consumed product with specific quatity from specific source location
1730
1731         @ param cr: the database cursor
1732         @ param uid: the user id
1733         @ param ids: ids of stock move object to be consumed
1734         @ param quantity : specify consume quantity
1735         @ param location_id : specify source location
1736         @ param context: context arguments
1737
1738         @ return: Consumed lines
1739         '''
1740         if not context:
1741             context = {}
1742
1743         if quantity <= 0:
1744             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1745
1746         res = []
1747         for move in self.browse(cr, uid, ids, context=context):
1748             move_qty = move.product_qty
1749             quantity_rest = move.product_qty
1750
1751             quantity_rest -= quantity
1752             uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
1753             if quantity_rest <= 0:
1754                 quantity_rest = 0
1755                 uos_qty_rest = 0
1756                 quantity = move.product_qty
1757
1758             uos_qty = quantity / move_qty * move.product_uos_qty
1759
1760             if quantity_rest > 0:
1761                 default_val = {
1762                     'product_qty': quantity,
1763                     'product_uos_qty': uos_qty,
1764                     'state': move.state,
1765                     'location_id': location_id
1766                 }
1767                 if move.product_id.track_production and location_id:
1768                     # IF product has checked track for production lot, move lines will be split by 1
1769                     res += self.action_split(cr, uid, [move.id], quantity, split_by_qty=1, context=context)
1770                 else:
1771                     current_move = self.copy(cr, uid, move.id, default_val)
1772                     res += [current_move]
1773
1774                 update_val = {}
1775                 update_val['product_qty'] = quantity_rest
1776                 update_val['product_uos_qty'] = uos_qty_rest
1777                 self.write(cr, uid, [move.id], update_val)
1778
1779             else:
1780                 quantity_rest = quantity
1781                 uos_qty_rest =  uos_qty
1782
1783                 if move.product_id.track_production and location_id:
1784                     res += self.split_lines(cr, uid, [move.id], quantity_rest, split_by_qty=1, context=context)
1785                 else:
1786                     res += [move.id]
1787                     update_val = {
1788                         'product_qty' : quantity_rest,
1789                         'product_uos_qty' : uos_qty_rest,
1790                         'location_id': location_id
1791                     }
1792
1793                     self.write(cr, uid, [move.id], update_val)
1794
1795         self.action_done(cr, uid, res)
1796         return res
1797
1798     def do_partial(self, cr, uid, ids, partial_datas, context={}):
1799         """
1800         @ partial_datas : dict. contain details of partial picking
1801                           like partner_id, address_id, delivery_date, delivery moves with product_id, product_qty, uom
1802         """
1803         res = {}
1804         picking_obj = self.pool.get('stock.picking')
1805         delivery_obj = self.pool.get('stock.delivery')
1806         product_obj = self.pool.get('product.product')
1807         currency_obj = self.pool.get('res.currency')
1808         users_obj = self.pool.get('res.users')
1809         uom_obj = self.pool.get('product.uom')
1810         price_type_obj = self.pool.get('product.price.type')
1811         sequence_obj = self.pool.get('ir.sequence')
1812         wf_service = netsvc.LocalService("workflow")
1813         partner_id = partial_datas.get('partner_id', False)
1814         address_id = partial_datas.get('address_id', False)
1815         delivery_date = partial_datas.get('delivery_date', False)
1816
1817         new_moves = []
1818
1819         complete, too_many, too_few = [], [], []
1820         move_product_qty = {}
1821         for move in self.browse(cr, uid, ids, context=context):
1822             if move.state in ('done', 'cancel'):
1823                 continue
1824             partial_data = partial_datas.get('move%s'%(move.id), False)
1825             assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
1826             product_qty = partial_data.get('product_qty',0.0)
1827             move_product_qty[move.id] = product_qty
1828             product_uom = partial_data.get('product_uom',False)
1829             product_price = partial_data.get('product_price',0.0)
1830             product_currency = partial_data.get('product_currency',False)
1831             if move.product_qty == product_qty:
1832                 complete.append(move)
1833             elif move.product_qty > product_qty:
1834                 too_few.append(move)
1835             else:
1836                 too_many.append(move)
1837
1838             # Average price computation
1839             if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
1840                 product = product_obj.browse(cr, uid, move.product_id.id)
1841                 user = users_obj.browse(cr, uid, uid)
1842                 context['currency_id'] = move.company_id.currency_id.id
1843                 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
1844                 pricetype = False
1845                 if user.company_id.property_valuation_price_type:
1846                     pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
1847                 if pricetype and qty > 0:
1848                     new_price = currency_obj.compute(cr, uid, product_currency,
1849                             user.company_id.currency_id.id, product_price)
1850                     new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
1851                             product.uom_id.id)
1852                     if product.qty_available <= 0:
1853                         new_std_price = new_price
1854                     else:
1855                         # Get the standard price
1856                         amount_unit = product.price_get(pricetype.field, context)[product.id]
1857                         new_std_price = ((amount_unit * product.qty_available)\
1858                             + (new_price * qty))/(product.qty_available + qty)
1859
1860                     # Write the field according to price type field
1861                     product_obj.write(cr, uid, [product.id],
1862                             {pricetype.field: new_std_price})
1863                     self.write(cr, uid, [move.id], {'price_unit': new_price})
1864
1865         for move in too_few:
1866             product_qty = move_product_qty[move.id]
1867             if product_qty != 0:
1868                 new_move = self.copy(cr, uid, move.id,
1869                     {
1870                         'product_qty' : product_qty,
1871                         'product_uos_qty': product_qty,
1872                         'picking_id' : move.picking_id.id,
1873                         'state': 'assigned',
1874                         'move_dest_id': False,
1875                         'price_unit': move.price_unit,
1876                     })
1877                 complete.append(self.browse(cr, uid, new_move))
1878             self.write(cr, uid, move.id,
1879                     {
1880                         'product_qty' : move.product_qty - product_qty,
1881                         'product_uos_qty':move.product_qty - product_qty,
1882                     })
1883
1884
1885         for move in too_many:
1886             self.write(cr, uid, move.id,
1887                     {
1888                         'product_qty': product_qty,
1889                         'product_uos_qty': product_qty
1890                     })
1891             complete.append(move)
1892
1893         for move in complete:
1894             self.action_done(cr, uid, [move.id])
1895
1896             # TOCHECK : Done picking if all moves are done
1897             cr.execute("""
1898                 SELECT move.id FROM stock_picking pick
1899                 RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
1900                 WHERE pick.id = %s""",
1901                         ('done', move.picking_id.id))
1902             res = cr.fetchall()
1903             if len(res) == len(move.picking_id.move_lines):
1904                 picking_obj.action_move(cr, uid, [move.picking_id.id])
1905                 wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
1906
1907         ref = {}
1908         done_move_ids = []
1909         for move in complete:
1910             done_move_ids.append(move.id)
1911             if move.picking_id.id not in ref:
1912                 delivery_id = delivery_obj.create(cr, uid, {
1913                     'partner_id': partner_id,
1914                     'address_id': address_id,
1915                     'date': delivery_date,
1916                     'name' : move.picking_id.name,
1917                     'picking_id':  move.picking_id.id
1918                 }, context=context)
1919                 ref[move.picking_id.id] = delivery_id
1920             delivery_obj.write(cr, uid, ref[move.picking_id.id], {
1921                 'move_delivered' : [(4,move.id)]
1922             })
1923         return done_move_ids
1924
1925 stock_move()
1926
1927
1928 class stock_inventory(osv.osv):
1929     _name = "stock.inventory"
1930     _description = "Inventory"
1931     _columns = {
1932         'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
1933         'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
1934         'date_done': fields.datetime('Date done'),
1935         'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'done': [('readonly', True)]}),
1936         'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
1937         'state': fields.selection( (('draft', 'Draft'), ('done', 'Done'), ('cancel','Cancelled')), 'State', readonly=True),
1938         'company_id': fields.many2one('res.company','Company',required=True,select=1),
1939     }
1940     _defaults = {
1941         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
1942         'state': lambda *a: 'draft',
1943         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
1944     }
1945
1946
1947     def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
1948         '''Creates a stock move from an inventory line'''
1949         return self.pool.get('stock.move').create(cr, uid, move_vals)
1950
1951     def action_done(self, cr, uid, ids, context=None):
1952         for inv in self.browse(cr, uid, ids):
1953             move_ids = []
1954             move_line = []
1955             for line in inv.inventory_line_id:
1956                 pid = line.product_id.id
1957
1958                 # price = line.product_id.standard_price or 0.0
1959                 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
1960                 change = line.product_qty - amount
1961                 lot_id = line.prod_lot_id.id
1962                 if change:
1963                     location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
1964                     value = {
1965                         'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
1966                         'product_id': line.product_id.id,
1967                         'product_uom': line.product_uom.id,
1968                         'prodlot_id': lot_id,
1969                         'date': inv.date,
1970                         'date_planned': inv.date,
1971                         'state': 'assigned'
1972                     }
1973                     if change > 0:
1974                         value.update( {
1975                             'product_qty': change,
1976                             'location_id': location_id,
1977                             'location_dest_id': line.location_id.id,
1978                         })
1979                     else:
1980                         value.update( {
1981                             'product_qty': -change,
1982                             'location_id': line.location_id.id,
1983                             'location_dest_id': location_id,
1984                         })
1985                     if lot_id:
1986                         value.update({
1987                             'prodlot_id': lot_id,
1988                             'product_qty': line.product_qty
1989                         })
1990                     move_ids.append(self._inventory_line_hook(cr, uid, line, value))
1991             if len(move_ids):
1992                 self.pool.get('stock.move').action_done(cr, uid, move_ids,
1993                         context=context)
1994             self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
1995         return True
1996
1997     def action_cancel(self, cr, uid, ids, context={}):
1998         for inv in self.browse(cr, uid, ids):
1999             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2000             self.write(cr, uid, [inv.id], {'state': 'draft'})
2001         return True
2002
2003     def action_cancel_inventary(self, cr, uid, ids, context={}):
2004         for inv in self.browse(cr,uid,ids):
2005             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2006             self.write(cr, uid, [inv.id], {'state':'cancel'})
2007         return True
2008
2009 stock_inventory()
2010
2011
2012 class stock_inventory_line(osv.osv):
2013     _name = "stock.inventory.line"
2014     _description = "Inventory line"
2015     _columns = {
2016         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2017         'location_id': fields.many2one('stock.location', 'Location', required=True),
2018         'product_id': fields.many2one('product.product', 'Product', required=True),
2019         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
2020         'product_qty': fields.float('Quantity'),
2021         'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
2022         'prod_lot_id': fields.many2one('stock.production.lot', 'Production Lot', domain="[('product_id','=',product_id)]"),
2023         'state': fields.related('inventory_id','state',type='char',string='State',readonly=True),
2024     }
2025
2026     def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
2027         if not product:
2028             return {}
2029         if not uom:
2030             prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
2031             uom = prod.uom_id.id
2032         amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
2033         result = {'product_qty': amount, 'product_uom': uom}
2034         return {'value': result}
2035
2036 stock_inventory_line()
2037
2038
2039 #----------------------------------------------------------
2040 # Stock Warehouse
2041 #----------------------------------------------------------
2042 class stock_warehouse(osv.osv):
2043     _name = "stock.warehouse"
2044     _description = "Warehouse"
2045     _columns = {
2046         'name': fields.char('Name', size=60, required=True),
2047 #       'partner_id': fields.many2one('res.partner', 'Owner'),
2048         'company_id': fields.many2one('res.company','Company',required=True,select=1),
2049         'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
2050         'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True),
2051         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True),
2052         'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True),
2053     }
2054     _defaults = {
2055         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2056     }
2057 stock_warehouse()
2058
2059
2060 # Move wizard :
2061 #    get confirm or assign stock move lines of partner and put in current picking.
2062 class stock_picking_move_wizard(osv.osv_memory):
2063     _name = 'stock.picking.move.wizard'
2064
2065     def _get_picking(self, cr, uid, ctx):
2066         if ctx.get('action_id', False):
2067             return ctx['action_id']
2068         return False
2069
2070     def _get_picking_address(self, cr, uid, ctx):
2071         picking_obj = self.pool.get('stock.picking')
2072         if ctx.get('action_id', False):
2073             picking = picking_obj.browse(cr, uid, [ctx['action_id']])[0]
2074             return picking.address_id and picking.address_id.id or False
2075         return False
2076
2077     _columns = {
2078         'name': fields.char('Name', size=64, invisible=True),
2079         #'move_lines': fields.one2many('stock.move', 'picking_id', 'Move lines',readonly=True),
2080         'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Entry lines', required=True),
2081         'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
2082         'picking_id': fields.many2one('stock.picking', 'Picking list', select=True, invisible=True),
2083     }
2084     _defaults = {
2085         'picking_id': _get_picking,
2086         'address_id': _get_picking_address,
2087     }
2088
2089     def action_move(self, cr, uid, ids, context=None):
2090         move_obj = self.pool.get('stock.move')
2091         picking_obj = self.pool.get('stock.picking')
2092         for act in self.read(cr, uid, ids):
2093             move_lines = move_obj.browse(cr, uid, act['move_ids'])
2094             for line in move_lines:
2095                 if line.picking_id:
2096                     picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2097                     picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2098                     old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
2099                     if not len(old_picking['move_lines']):
2100                         picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
2101                 else:
2102                     raise osv.except_osv(_('UserError'),
2103                         _('You can not create new moves.'))
2104         return {'type': 'ir.actions.act_window_close'}
2105
2106 stock_picking_move_wizard()
2107
2108 class report_products_to_received_planned(osv.osv):
2109     _name = "report.products.to.received.planned"
2110     _description = "Product to Received Vs Planned"
2111     _auto = False
2112     _columns = {
2113         'date':fields.date('Date'),
2114         'qty': fields.integer('Actual Qty'),
2115         'planned_qty': fields.integer('Planned Qty'),
2116
2117     }
2118
2119     def init(self, cr):
2120         tools.drop_view_if_exists(cr, 'report_products_to_received_planned')
2121         cr.execute("""
2122             create or replace view report_products_to_received_planned as (
2123                select stock.date, min(stock.id), sum(stock.product_qty) as qty, 0 as planned_qty
2124                    from stock_picking picking
2125                     inner join stock_move stock
2126                     on picking.id = stock.picking_id and picking.type = 'in'
2127                     where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2128                     group by stock.date
2129
2130                     union
2131
2132                select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2133                     from stock_picking picking
2134                     inner join stock_move stock
2135                     on picking.id = stock.picking_id and picking.type = 'in'
2136                     where stock.date_planned between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2137         group by stock.date_planned
2138                 )
2139         """)
2140 report_products_to_received_planned()
2141
2142 class report_delivery_products_planned(osv.osv):
2143     _name = "report.delivery.products.planned"
2144     _description = "Number of Delivery products vs planned"
2145     _auto = False
2146     _columns = {
2147         'date':fields.date('Date'),
2148         'qty': fields.integer('Actual Qty'),
2149         'planned_qty': fields.integer('Planned Qty'),
2150
2151     }
2152
2153     def init(self, cr):
2154         tools.drop_view_if_exists(cr, 'report_delivery_products_planned')
2155         cr.execute("""
2156             create or replace view report_delivery_products_planned as (
2157                 select stock.date, min(stock.id), sum(stock.product_qty) as qty, 0 as planned_qty
2158                    from stock_picking picking
2159                     inner join stock_move stock
2160                     on picking.id = stock.picking_id and picking.type = 'out'
2161                     where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2162                     group by stock.date
2163
2164                     union
2165
2166                select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2167                     from stock_picking picking
2168                     inner join stock_move stock
2169                     on picking.id = stock.picking_id and picking.type = 'out'
2170                     where stock.date_planned between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2171         group by stock.date_planned
2172
2173
2174                 )
2175         """)
2176 report_delivery_products_planned()
2177 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: