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