[IMP] stock: Remove the comment code and remove the address_id from internal_move
[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     }
1378     _constraints = [
1379         (_check_tracking,
1380             'You must assign a production lot for this product',
1381             ['prodlot_id']),
1382         (_check_product_lot,
1383             'You try to assign a lot which is not from the same product',
1384             ['prodlot_id'])]
1385
1386     def _default_location_destination(self, cr, uid, context=None):
1387         """ Gets default address of partner for destination location
1388         @return: Address id or False
1389         """
1390         if context.get('move_line', []):
1391             if context['move_line'][0]:
1392                 if isinstance(context['move_line'][0], (tuple, list)):
1393                     return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False
1394                 else:
1395                     move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
1396                     return move_list and move_list['location_dest_id'][0] or False
1397         if context.get('address_out_id', False):
1398             property_out = self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer
1399             return property_out and property_out.id or False
1400         return False
1401
1402     def _default_location_source(self, cr, uid, context=None):
1403         """ Gets default address of partner for source location
1404         @return: Address id or False
1405         """
1406         if context.get('move_line', []):
1407             try:
1408                 return context['move_line'][0][2]['location_id']
1409             except:
1410                 pass
1411         if context.get('address_in_id', False):
1412             return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id
1413         return False
1414
1415     _defaults = {
1416         'location_id': _default_location_source,
1417         'location_dest_id': _default_location_destination,
1418         'state': 'draft',
1419         'priority': '1',
1420         'product_qty': 1.0,
1421         'scraped' :  False,
1422         'date_planned': time.strftime('%Y-%m-%d %H:%M:%S'),
1423         'date': time.strftime('%Y-%m-%d %H:%M:%S'),
1424         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.move', context=c),
1425         'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
1426     }
1427
1428     def copy(self, cr, uid, id, default=None, context=None):
1429         if default is None:
1430             default = {}
1431         default = default.copy()
1432         return super(stock_move, self).copy(cr, uid, id, default, context=context)
1433
1434     def _auto_init(self, cursor, context=None):
1435         res = super(stock_move, self)._auto_init(cursor, context=context)
1436         cursor.execute('SELECT indexname \
1437                 FROM pg_indexes \
1438                 WHERE indexname = \'stock_move_location_id_location_dest_id_product_id_state\'')
1439         if not cursor.fetchone():
1440             cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \
1441                     ON stock_move (location_id, location_dest_id, product_id, state)')
1442         return res
1443
1444     def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
1445                         loc_id=False, product_id=False, context=None):
1446         """ On change of production lot gives a warning message.
1447         @param prodlot_id: Changed production lot id
1448         @param product_qty: Quantity of product
1449         @param loc_id: Location id
1450         @param product_id: Product id
1451         @return: Warning message
1452         """
1453         if not prodlot_id or not loc_id:
1454             return {}
1455         ctx = context and context.copy() or {}
1456         ctx['location_id'] = loc_id
1457         prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)
1458         location = self.pool.get('stock.location').browse(cr, uid, loc_id)
1459         warning = {}
1460         if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):
1461             warning = {
1462                 'title': 'Bad Lot Assignation !',
1463                 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)
1464             }
1465         return {'warning': warning}
1466
1467     def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
1468                           product_uom, product_uos):
1469         """ On change of product quantity finds UoM and UoS quantities
1470         @param product_id: Product id
1471         @param product_qty: Changed Quantity of product
1472         @param product_uom: Unit of measure of product
1473         @param product_uos: Unit of sale of product
1474         @return: Dictionary of values
1475         """
1476         result = {
1477                   'product_uos_qty': 0.00
1478           }
1479
1480         if (not product_id) or (product_qty <=0.0):
1481             return {'value': result}
1482
1483         product_obj = self.pool.get('product.product')
1484         uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
1485
1486         if product_uos and product_uom and (product_uom != product_uos):
1487             result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
1488         else:
1489             result['product_uos_qty'] = product_qty
1490
1491         return {'value': result}
1492
1493     def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
1494                             loc_dest_id=False, address_id=False):
1495         """ On change of product id, if finds UoM, UoS, quantity and UoS quantity.
1496         @param prod_id: Changed Product id
1497         @param loc_id: Source location id
1498         @param loc_id: Destination location id
1499         @param address_id: Address id of partner
1500         @return: Dictionary of values
1501         """
1502         if not prod_id:
1503             return {}
1504         lang = False
1505         if address_id:
1506             addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id)
1507             if addr_rec:
1508                 lang = addr_rec.partner_id and addr_rec.partner_id.lang or False
1509         ctx = {'lang': lang}
1510
1511         product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
1512         uos_id  = product.uos_id and product.uos_id.id or False
1513         result = {
1514             'product_uom': product.uom_id.id,
1515             'product_uos': uos_id,
1516             'product_qty': 1.00,
1517             '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']
1518         }
1519         if not ids:
1520             result['name'] = product.partner_ref
1521         if loc_id:
1522             result['location_id'] = loc_id
1523         if loc_dest_id:
1524             result['location_dest_id'] = loc_dest_id
1525         return {'value': result}
1526
1527     def _chain_compute(self, cr, uid, moves, context=None):
1528         """ Finds whether the location has chained location type or not.
1529         @param moves: Stock moves
1530         @return: Dictionary containing destination location with chained location type.
1531         """
1532         result = {}
1533         for m in moves:
1534             dest = self.pool.get('stock.location').chained_location_get(
1535                 cr,
1536                 uid,
1537                 m.location_dest_id,
1538                 m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,
1539                 m.product_id,
1540                 context
1541             )
1542             if dest:
1543                 if dest[1] == 'transparent':
1544                     self.write(cr, uid, [m.id], {
1545                         'date_planned': (datetime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \
1546                             relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d'),
1547                         'location_dest_id': dest[0].id})
1548                 else:
1549                     result.setdefault(m.picking_id, [])
1550                     result[m.picking_id].append( (m, dest) )
1551         return result
1552
1553     def action_confirm(self, cr, uid, ids, context=None):
1554         """ Confirms stock move.
1555         @return: List of ids.
1556         """
1557         moves = self.browse(cr, uid, ids)
1558         self.write(cr, uid, ids, {'state': 'confirmed'})
1559         i = 0
1560
1561         def create_chained_picking(self, cr, uid, moves, context=None):
1562             new_moves = []
1563             res_obj = self.pool.get('res.company')
1564             picking_obj = self.pool.get('stock.picking')
1565             move_obj = self.pool.get('stock.move')
1566             if context is None:
1567                 context = {}
1568             for picking, todo in self._chain_compute(cr, uid, moves, context=context).items():
1569                 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])
1570                 pick_name = picking.name
1571                 if ptype == 'delivery':
1572                     pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.delivery')
1573
1574                 pickid = picking_obj.create(cr, uid, {
1575                     'name': pick_name,
1576                     'origin': str(picking.origin or ''),
1577                     'type': ptype,
1578                     'note': picking.note,
1579                     'move_type': picking.move_type,
1580                     'auto_picking': todo[0][1][1] == 'auto',
1581                     'stock_journal_id': todo[0][1][3],
1582                     'company_id': todo[0][1][4] or res_obj._company_default_get(cr, uid, 'stock.company', context),
1583                     'address_id': picking.address_id.id,
1584                     'invoice_state': 'none',
1585                     'date': picking.date,
1586                     'sale_id':' sale_id' in picking._columns.keys() and  picking.sale_id.id or False
1587                     })
1588                 for move, (loc, auto, delay, journal, company_id, ptype) in todo:
1589                     new_id = move_obj.copy(cr, uid, move.id, {
1590                         'location_id': move.location_dest_id.id,
1591                         'location_dest_id': loc.id,
1592                         'date_moved': time.strftime('%Y-%m-%d'),
1593                         'picking_id': pickid,
1594                         'state': 'waiting',
1595                         'company_id': company_id or res_obj._company_default_get(cr, uid, 'stock.company', context)  ,
1596                         'move_history_ids': [],
1597                         'date_planned': (datetime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
1598                         'move_history_ids2': []}
1599                     )
1600                     move_obj.write(cr, uid, [move.id], {
1601                         'move_dest_id': new_id,
1602                         'move_history_ids': [(4, new_id)]
1603                     })
1604                     new_moves.append(self.browse(cr, uid, [new_id])[0])
1605                 wf_service = netsvc.LocalService("workflow")
1606                 wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
1607             if new_moves:
1608                 create_chained_picking(self, cr, uid, new_moves, context)
1609         create_chained_picking(self, cr, uid, moves, context)
1610         return []
1611
1612     def action_assign(self, cr, uid, ids, *args):
1613         """ Changes state to confirmed or waiting.
1614         @return: List of values
1615         """
1616         todo = []
1617         for move in self.browse(cr, uid, ids):
1618             if move.state in ('confirmed', 'waiting'):
1619                 todo.append(move.id)
1620         res = self.check_assign(cr, uid, todo)
1621         return res
1622
1623     def force_assign(self, cr, uid, ids, context={}):
1624         """ Changes the state to assigned.
1625         @return: True
1626         """
1627         self.write(cr, uid, ids, {'state': 'assigned'})
1628         return True
1629
1630     def cancel_assign(self, cr, uid, ids, context={}):
1631         """ Changes the state to confirmed.
1632         @return: True
1633         """
1634         self.write(cr, uid, ids, {'state': 'confirmed'})
1635         return True
1636
1637     #
1638     # Duplicate stock.move
1639     #
1640     def check_assign(self, cr, uid, ids, context=None):
1641         """ Checks the product type and accordingly writes the state.
1642         @return: No. of moves done
1643         """
1644         done = []
1645         count = 0
1646         pickings = {}
1647         if context is None:
1648             context = {}
1649         for move in self.browse(cr, uid, ids, context=context):
1650             if move.product_id.type == 'consu':
1651                 if move.state in ('confirmed', 'waiting'):
1652                     done.append(move.id)
1653                 pickings[move.picking_id.id] = 1
1654                 continue
1655             if move.state in ('confirmed', 'waiting'):
1656                 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})
1657                 if res:
1658                     #_product_available_test depends on the next status for correct functioning
1659                     #the test does not work correctly if the same product occurs multiple times
1660                     #in the same order. This is e.g. the case when using the button 'split in two' of
1661                     #the stock outgoing form
1662                     self.write(cr, uid, move.id, {'state':'assigned'})
1663                     done.append(move.id)
1664                     pickings[move.picking_id.id] = 1
1665                     r = res.pop(0)
1666                     cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
1667
1668                     while res:
1669                         r = res.pop(0)
1670                         move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})
1671                         done.append(move_id)
1672         if done:
1673             count += len(done)
1674             self.write(cr, uid, done, {'state': 'assigned'})
1675
1676         if count:
1677             for pick_id in pickings:
1678                 wf_service = netsvc.LocalService("workflow")
1679                 wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1680         return count
1681
1682     def setlast_tracking(self, cr, uid, ids, context=None):
1683         tracking_obj = self.pool.get('stock.tracking')
1684         tracking = context.get('tracking', False)
1685         last_track = [line.tracking_id.id for line in self.browse(cr, uid, ids)[0].picking_id.move_lines if line.tracking_id]
1686         if not last_track:
1687             last_track = tracking_obj.create(cr, uid, {}, context=context)
1688         else:
1689             last_track.sort()
1690             last_track = last_track[-1]
1691         self.write(cr, uid, ids, {'tracking_id': last_track})
1692         return True
1693
1694     #
1695     # Cancel move => cancel others move and pickings
1696     #
1697     def action_cancel(self, cr, uid, ids, context=None):
1698         """ Cancels the moves and if all moves are cancelled it cancels the picking.
1699         @return: True
1700         """
1701         if not len(ids):
1702             return True
1703         if context is None:
1704             context = {}
1705         pickings = {}
1706         for move in self.browse(cr, uid, ids):
1707             if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
1708                 if move.picking_id:
1709                     pickings[move.picking_id.id] = True
1710             if move.move_dest_id and move.move_dest_id.state == 'waiting':
1711                 self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1712                 if context.get('call_unlink',False) and move.move_dest_id.picking_id:
1713                     wf_service = netsvc.LocalService("workflow")
1714                     wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1715         self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})
1716         if not context.get('call_unlink',False):
1717             for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):
1718                 if all(move.state == 'cancel' for move in pick.move_lines):
1719                     self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})
1720
1721         wf_service = netsvc.LocalService("workflow")
1722         for id in ids:
1723             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1724         return True
1725
1726     def _get_accounting_values(self, cr, uid, move, context=None):
1727         product_obj=self.pool.get('product.product')
1728         product_uom_obj = self.pool.get('product.uom')
1729         price_type_obj = self.pool.get('product.price.type')
1730         accounts = product_obj.get_product_accounts(cr,uid,move.product_id.id,context)
1731         acc_src = accounts['stock_account_input']
1732         acc_dest = accounts['stock_account_output']
1733         acc_variation = accounts.get('property_stock_variation', False)
1734         journal_id = accounts['stock_journal']
1735
1736         if context is None:
1737             context = {}
1738
1739         if not acc_src:
1740             raise osv.except_osv(_('Error!'),  _('There is no stock input account defined ' \
1741                                     'for this product: "%s" (id: %d)') % \
1742                                     (move.product_id.name, move.product_id.id,))
1743         if not acc_dest:
1744             raise osv.except_osv(_('Error!'),  _('There is no stock output account defined ' \
1745                                     'for this product: "%s" (id: %d)') % \
1746                                     (move.product_id.name, move.product_id.id,))
1747         if not journal_id:
1748             raise osv.except_osv(_('Error!'), _('There is no journal defined '\
1749                                     'on the product category: "%s" (id: %d)') % \
1750                                     (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1751         if not acc_variation:
1752             raise osv.except_osv(_('Error!'), _('There is no variation  account defined '\
1753                                     'on the product category: "%s" (id: %d)') % \
1754                                     (move.product_id.categ_id.name, move.product_id.categ_id.id,))
1755         if acc_src != acc_dest:
1756             default_uom = move.product_id.uom_id.id
1757             q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
1758             if move.product_id.cost_method == 'average' and move.price_unit:
1759                 amount = q * move.price_unit
1760             # Base computation on valuation price type
1761             else:
1762                 company_id = move.company_id.id
1763                 context['currency_id'] = move.company_id.currency_id.id
1764                 pricetype = price_type_obj.browse(cr,uid,move.company_id.property_valuation_price_type.id)
1765                 amount_unit = move.product_id.price_get(pricetype.field, context)[move.product_id.id]
1766                 amount = amount_unit * q or 1.0
1767         return journal_id, acc_src, acc_dest, acc_variation, amount
1768
1769     def action_done(self, cr, uid, ids, context=None):
1770         """ Makes the move done and if all moves are done, it will finish the picking.
1771         @return:
1772         """
1773         track_flag = False
1774         picking_ids = []
1775         product_uom_obj = self.pool.get('product.uom')
1776         price_type_obj = self.pool.get('product.price.type')
1777         product_obj = self.pool.get('product.product')
1778         move_obj = self.pool.get('account.move')
1779         if context is None:
1780             context = {}
1781         for move in self.browse(cr, uid, ids):
1782             if move.picking_id:
1783                 picking_ids.append(move.picking_id.id)
1784             if move.move_dest_id.id and (move.state != 'done'):
1785                 cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))
1786                 if move.move_dest_id.state in ('waiting', 'confirmed'):
1787                     self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})
1788                     if move.move_dest_id.picking_id:
1789                         wf_service = netsvc.LocalService("workflow")
1790                         wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
1791                     else:
1792                         pass
1793                     if move.move_dest_id.auto_validate:
1794                         self.action_done(cr, uid, [move.move_dest_id.id], context=context)
1795
1796             #
1797             # Accounting Entries
1798             #
1799             acc_src = None
1800             acc_dest = None
1801             if move.product_id.valuation == 'real_time':
1802                 lines = []
1803                 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')):
1804                     if move.location_id.company_id:
1805                         context.update({'force_company': move.location_id.company_id.id})
1806                     journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1807                     lines = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1808
1809                 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')):
1810                     if move.location_dest_id.company_id:
1811                         context.update({'force_company': move.location_dest_id.company_id.id})
1812                     journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1813                     lines = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1814                 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):
1815                     if move.location_id.company_id:
1816                         context.update({'force_company': move.location_id.company_id.id})
1817                     journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1818                     line1 = [(journal_id, self.create_account_move(cr, uid, move, acc_dest, acc_variation, amount, context))]
1819                     if move.location_dest_id.company_id:
1820                         context.update({'force_company': move.location_dest_id.company_id.id})
1821                     journal_id, acc_src, acc_dest, acc_variation, amount = self._get_accounting_values(cr, uid, move, context)
1822                     line2 = [(journal_id, self.create_account_move(cr, uid, move, acc_variation, acc_src, amount, context))]
1823                     lines = line1 + line2
1824                 for j_id, line in lines:
1825                     move_obj.create(cr, uid, {
1826                         'name': move.name,
1827                         'journal_id': j_id,
1828                         'type':'cont_voucher',
1829                         'line_id': line,
1830                         'ref': move.picking_id and move.picking_id.name,
1831                         })
1832             
1833         self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})
1834         wf_service = netsvc.LocalService("workflow")
1835         for id in ids:
1836             wf_service.trg_trigger(uid, 'stock.move', id, cr)
1837
1838         picking_obj = self.pool.get('stock.picking')
1839         wf_service = netsvc.LocalService("workflow")
1840         for pick_id in picking_ids:
1841             wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
1842
1843         picking_obj.log_picking(cr, uid, picking_ids, context=context)
1844         return True
1845
1846     def create_account_move(self, cr, uid, move,account_id, account_variation, amount, context=None):
1847         if context is None:
1848             context = {}
1849         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
1850         lines=[(0, 0, {
1851                                     'name': move.name,
1852                                     'quantity': move.product_qty,
1853                                     'product_id': move.product_id and move.product_id.id or False,
1854                                     'credit': amount,
1855                                     'account_id': account_id,
1856                                     'ref': move.picking_id and move.picking_id.name or False,
1857                                     'date': time.strftime('%Y-%m-%d')   ,
1858                                     'partner_id': partner_id,
1859                                     }),
1860                                 (0, 0, {
1861                                     'name': move.name,
1862                                     'product_id': move.product_id and move.product_id.id or False,
1863                                     'quantity': move.product_qty,
1864                                     'debit': amount,
1865                                     'account_id': account_variation,
1866                                     'ref': move.picking_id and move.picking_id.name or False,
1867                                     'date': time.strftime('%Y-%m-%d')   ,
1868                                     'partner_id': partner_id,
1869                                     })]
1870         return lines
1871
1872     def unlink(self, cr, uid, ids, context=None):
1873         if context is None:
1874             context = {}
1875         for move in self.browse(cr, uid, ids, context=context):
1876             if move.state != 'draft':
1877                 raise osv.except_osv(_('UserError'),
1878                         _('You can only delete draft moves.'))
1879         return super(stock_move, self).unlink(
1880             cr, uid, ids, context=context)
1881
1882     def _create_lot(self, cr, uid, ids, product_id, prefix=False):
1883         """ Creates production lot
1884         @return: Production lot id
1885         """
1886         prodlot_obj = self.pool.get('stock.production.lot')
1887         prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
1888         return prodlot_id
1889
1890     def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
1891         """ Move the scrap/damaged product into scrap location
1892         @param cr: the database cursor
1893         @param uid: the user id
1894         @param ids: ids of stock move object to be scraped
1895         @param quantity : specify scrap qty
1896         @param location_id : specify scrap location
1897         @param context: context arguments
1898         @return: Scraped lines
1899         """
1900         if quantity <= 0:
1901             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1902         res = []
1903         for move in self.browse(cr, uid, ids, context=context):
1904             move_qty = move.product_qty
1905             uos_qty = quantity / move_qty * move.product_uos_qty
1906             default_val = {
1907                     'product_qty': quantity,
1908                     'product_uos_qty': uos_qty,
1909                     'state': move.state,
1910                     'scraped' : True,
1911                     'location_dest_id': location_id
1912                 }
1913             new_move = self.copy(cr, uid, move.id, default_val)
1914             res += [new_move]
1915             product_obj = self.pool.get('product.product')
1916             for (id, name) in product_obj.name_get(cr, uid, [move.product_id.id]):
1917                 message = _('Product ') + " '" + name + "' "+ _("is scraped with") + " '" + str(move.product_qty) + "' "+ _("quantity.")
1918             self.log(cr, uid, move.id, message)
1919
1920         self.action_done(cr, uid, res)
1921         return res
1922
1923     def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
1924         """ Split Stock Move lines into production lot which specified split by quantity.
1925         @param cr: the database cursor
1926         @param uid: the user id
1927         @param ids: ids of stock move object to be splited
1928         @param split_by_qty : specify split by qty
1929         @param prefix : specify prefix of production lot
1930         @param with_lot : if true, prodcution lot will assign for split line otherwise not.
1931         @param context: context arguments
1932         @return: Splited move lines
1933         """
1934
1935         if context is None:
1936             context = {}
1937         if quantity <= 0:
1938             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1939
1940         res = []
1941
1942         for move in self.browse(cr, uid, ids):
1943             if split_by_qty <= 0 or quantity == 0:
1944                 return res
1945
1946             uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
1947
1948             quantity_rest = quantity % split_by_qty
1949             uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
1950
1951             update_val = {
1952                 'product_qty': split_by_qty,
1953                 'product_uos_qty': uos_qty,
1954             }
1955             for idx in range(int(quantity//split_by_qty)):
1956                 if not idx and move.product_qty<=quantity:
1957                     current_move = move.id
1958                 else:
1959                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
1960                 res.append(current_move)
1961                 if with_lot:
1962                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1963
1964                 self.write(cr, uid, [current_move], update_val)
1965
1966
1967             if quantity_rest > 0:
1968                 idx = int(quantity//split_by_qty)
1969                 update_val['product_qty'] = quantity_rest
1970                 update_val['product_uos_qty'] = uos_qty_rest
1971                 if not idx and move.product_qty<=quantity:
1972                     current_move = move.id
1973                 else:
1974                     current_move = self.copy(cr, uid, move.id, {'state': move.state})
1975
1976                 res.append(current_move)
1977
1978
1979                 if with_lot:
1980                     update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
1981
1982                 self.write(cr, uid, [current_move], update_val)
1983         return res
1984
1985     def action_consume(self, cr, uid, ids, quantity, location_id=False,  context=None):
1986         """ Consumed product with specific quatity from specific source location
1987         @param cr: the database cursor
1988         @param uid: the user id
1989         @param ids: ids of stock move object to be consumed
1990         @param quantity : specify consume quantity
1991         @param location_id : specify source location
1992         @param context: context arguments
1993         @return: Consumed lines
1994         """
1995         if context is None:
1996             context = {}
1997         if quantity <= 0:
1998             raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
1999
2000         res = []
2001         for move in self.browse(cr, uid, ids, context=context):
2002             move_qty = move.product_qty
2003             quantity_rest = move.product_qty
2004
2005             quantity_rest -= quantity
2006             uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
2007             if quantity_rest <= 0:
2008                 quantity_rest = 0
2009                 uos_qty_rest = 0
2010                 quantity = move.product_qty
2011
2012             uos_qty = quantity / move_qty * move.product_uos_qty
2013
2014             if quantity_rest > 0:
2015                 default_val = {
2016                     'product_qty': quantity,
2017                     'product_uos_qty': uos_qty,
2018                     'state': move.state,
2019                     'location_id': location_id
2020                 }
2021                 if move.product_id.track_production and location_id:
2022                     # IF product has checked track for production lot, move lines will be split by 1
2023                     res += self.action_split(cr, uid, [move.id], quantity, split_by_qty=1, context=context)
2024                 else:
2025                     current_move = self.copy(cr, uid, move.id, default_val)
2026                     res += [current_move]
2027                 update_val = {}
2028                 update_val['product_qty'] = quantity_rest
2029                 update_val['product_uos_qty'] = uos_qty_rest
2030                 self.write(cr, uid, [move.id], update_val)
2031
2032             else:
2033                 quantity_rest = quantity
2034                 uos_qty_rest =  uos_qty
2035                 if move.product_id.track_production and location_id:
2036                     res += self.split_lines(cr, uid, [move.id], quantity_rest, split_by_qty=1, context=context)
2037                 else:
2038                     res += [move.id]
2039                     update_val = {
2040                         'product_qty' : quantity_rest,
2041                         'product_uos_qty' : uos_qty_rest,
2042                         'location_id': location_id
2043                     }
2044
2045                     self.write(cr, uid, [move.id], update_val)
2046
2047             product_obj = self.pool.get('product.product')
2048             for new_move in self.browse(cr, uid, res, context=context):
2049                 for (id, name) in product_obj.name_get(cr, uid, [new_move.product_id.id]):
2050                     message = _('Product ') + " '" + name + "' "+ _("is consumed with") + " '" + str(new_move.product_qty) + "' "+ _("quantity.")
2051                     self.log(cr, uid, new_move.id, message)
2052         self.action_done(cr, uid, res)
2053
2054         return res
2055
2056     def do_partial(self, cr, uid, ids, partial_datas, context=None):
2057         """ Makes partial pickings and moves done.
2058         @param partial_datas: Dictionary containing details of partial picking
2059                           like partner_id, address_id, delivery_date, delivery
2060                           moves with product_id, product_qty, uom
2061         """
2062         res = {}
2063         picking_obj = self.pool.get('stock.picking')
2064         product_obj = self.pool.get('product.product')
2065         currency_obj = self.pool.get('res.currency')
2066         users_obj = self.pool.get('res.users')
2067         uom_obj = self.pool.get('product.uom')
2068         price_type_obj = self.pool.get('product.price.type')
2069         sequence_obj = self.pool.get('ir.sequence')
2070         wf_service = netsvc.LocalService("workflow")
2071         partner_id = partial_datas.get('partner_id', False)
2072         address_id = partial_datas.get('address_id', False)
2073         delivery_date = partial_datas.get('delivery_date', False)
2074         new_moves = []
2075
2076         if  context is None:
2077             context = {}
2078
2079         complete, too_many, too_few = [], [], []
2080         move_product_qty = {}
2081         for move in self.browse(cr, uid, ids, context=context):
2082             if move.state in ('done', 'cancel'):
2083                 continue
2084             partial_data = partial_datas.get('move%s'%(move.id), False)
2085             assert partial_data, _('Do not Found Partial data of Stock Move Line :%s' %(move.id))
2086             product_qty = partial_data.get('product_qty',0.0)
2087             move_product_qty[move.id] = product_qty
2088             product_uom = partial_data.get('product_uom',False)
2089             product_price = partial_data.get('product_price',0.0)
2090             product_currency = partial_data.get('product_currency',False)
2091             if move.product_qty == product_qty:
2092                 complete.append(move)
2093             elif move.product_qty > product_qty:
2094                 too_few.append(move)
2095             else:
2096                 too_many.append(move)
2097
2098             # Average price computation
2099             if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
2100                 product = product_obj.browse(cr, uid, move.product_id.id)
2101                 user = users_obj.browse(cr, uid, uid)
2102                 context['currency_id'] = move.company_id.currency_id.id
2103                 qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
2104                 pricetype = False
2105                 if user.company_id.property_valuation_price_type:
2106                     pricetype = price_type_obj.browse(cr, uid, user.company_id.property_valuation_price_type.id)
2107                 if pricetype and qty > 0:
2108                     new_price = currency_obj.compute(cr, uid, product_currency,
2109                             user.company_id.currency_id.id, product_price)
2110                     new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
2111                             product.uom_id.id)
2112                     if product.qty_available <= 0:
2113                         new_std_price = new_price
2114                     else:
2115                         # Get the standard price
2116                         amount_unit = product.price_get(pricetype.field, context)[product.id]
2117                         new_std_price = ((amount_unit * product.qty_available)\
2118                             + (new_price * qty))/(product.qty_available + qty)
2119
2120                     # Write the field according to price type field
2121                     product_obj.write(cr, uid, [product.id],
2122                             {pricetype.field: new_std_price})
2123                     self.write(cr, uid, [move.id], {'price_unit': new_price})
2124
2125         for move in too_few:
2126             product_qty = move_product_qty[move.id]
2127             if product_qty != 0:
2128                 new_move = self.copy(cr, uid, move.id,
2129                     {
2130                         'product_qty' : product_qty,
2131                         'product_uos_qty': product_qty,
2132                         'picking_id' : move.picking_id.id,
2133                         'state': 'assigned',
2134                         'move_dest_id': False,
2135                         'price_unit': move.price_unit,
2136                     })
2137                 complete.append(self.browse(cr, uid, new_move))
2138             self.write(cr, uid, move.id,
2139                     {
2140                         'product_qty' : move.product_qty - product_qty,
2141                         'product_uos_qty':move.product_qty - product_qty,
2142                     })
2143
2144
2145         for move in too_many:
2146             self.write(cr, uid, move.id,
2147                     {
2148                         'product_qty': move.product_qty,
2149                         'product_uos_qty': move.product_qty,
2150                     })
2151             complete.append(move)
2152
2153         for move in complete:
2154             self.action_done(cr, uid, [move.id], context=context)
2155             if  move.picking_id.id :
2156                 # TOCHECK : Done picking if all moves are done
2157                 cr.execute("""
2158                     SELECT move.id FROM stock_picking pick
2159                     RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
2160                     WHERE pick.id = %s""",
2161                             ('done', move.picking_id.id))
2162                 res = cr.fetchall()
2163                 if len(res) == len(move.picking_id.move_lines):
2164                     picking_obj.action_move(cr, uid, [move.picking_id.id])
2165                     wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
2166
2167         ref = {}
2168         done_move_ids = []
2169         for move in complete:
2170             done_move_ids.append(move.id)
2171         return done_move_ids
2172
2173 stock_move()
2174
2175 class stock_inventory(osv.osv):
2176     _name = "stock.inventory"
2177     _description = "Inventory"
2178     _columns = {
2179         'name': fields.char('Inventory', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
2180         'date': fields.datetime('Date create', required=True, readonly=True, states={'draft': [('readonly', False)]}),
2181         'date_done': fields.datetime('Date done'),
2182         'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'done': [('readonly', True)]}),
2183         'move_ids': fields.many2many('stock.move', 'stock_inventory_move_rel', 'inventory_id', 'move_id', 'Created Moves'),
2184         'state': fields.selection( (('draft', 'Draft'), ('done', 'Done'), ('cancel','Cancelled')), 'State', readonly=True),
2185         'company_id': fields.many2one('res.company','Company',required=True,select=1),
2186     }
2187     _defaults = {
2188         'date': time.strftime('%Y-%m-%d %H:%M:%S'),
2189         'state': 'draft',
2190         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c)
2191     }
2192
2193     def _inventory_line_hook(self, cr, uid, inventory_line, move_vals):
2194         """ Creates a stock move from an inventory line
2195         @param inventory_line:
2196         @param move_vals:
2197         @return:
2198         """
2199         return self.pool.get('stock.move').create(cr, uid, move_vals)
2200
2201     def action_done(self, cr, uid, ids, context=None):
2202         """ Finishes the inventory and writes its finished date
2203         @return: True
2204         """
2205         if context is None:
2206             context = {}
2207         for inv in self.browse(cr, uid, ids):
2208             move_ids = []
2209             move_line = []
2210             for line in inv.inventory_line_id:
2211                 pid = line.product_id.id
2212
2213                 amount = self.pool.get('stock.location')._product_get(cr, uid, line.location_id.id, [pid], {'uom': line.product_uom.id})[pid]
2214                 #TOCHECK: Why put restriction like new inventory qty should greater available qty ?
2215                 change = line.product_qty - amount
2216                 lot_id = line.prod_lot_id.id
2217                 if change:
2218                     location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
2219                     value = {
2220                         'name': 'INV:' + str(line.inventory_id.id) + ':' + line.inventory_id.name,
2221                         'product_id': line.product_id.id,
2222                         'product_uom': line.product_uom.id,
2223                         'prodlot_id': lot_id,
2224                         'date': inv.date,
2225                         'date_planned': inv.date,
2226                         'state': 'done'
2227                     }
2228                     if change > 0:
2229                         value.update( {
2230                             'product_qty': change,
2231                             'location_id': location_id,
2232                             'location_dest_id': line.location_id.id,
2233                         })
2234                     else:
2235                         value.update( {
2236                             'product_qty': -change,
2237                             'location_id': line.location_id.id,
2238                             'location_dest_id': location_id,
2239                         })
2240                     if lot_id:
2241                         value.update({
2242                             'prodlot_id': lot_id,
2243                             'product_qty': line.product_qty
2244                         })
2245                     move_ids.append(self._inventory_line_hook(cr, uid, line, value))
2246             message = _('Inventory') + " '" + inv.name + "' "+ _("is done.")
2247             self.log(cr, uid, inv.id, message)
2248             self.write(cr, uid, [inv.id], {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S'), 'move_ids': [(6, 0, move_ids)]})
2249         return True
2250
2251     def action_cancel(self, cr, uid, ids, context=None):
2252         """ Cancels the stock move and change inventory state to draft.
2253         @return: True
2254         """
2255         for inv in self.browse(cr, uid, ids):
2256             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2257             self.write(cr, uid, [inv.id], {'state': 'draft'})
2258         return True
2259
2260     def action_cancel_inventary(self, cr, uid, ids, context=None):
2261         """ Cancels both stock move and inventory
2262         @return: True
2263         """
2264         for inv in self.browse(cr,uid,ids):
2265             self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context)
2266             self.write(cr, uid, [inv.id], {'state':'cancel'})
2267         return True
2268
2269 stock_inventory()
2270
2271 class stock_inventory_line(osv.osv):
2272     _name = "stock.inventory.line"
2273     _description = "Inventory Line"
2274     _columns = {
2275         'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
2276         'location_id': fields.many2one('stock.location', 'Location', required=True),
2277         'product_id': fields.many2one('product.product', 'Product', required=True),
2278         'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
2279         'product_qty': fields.float('Quantity'),
2280         'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
2281         'prod_lot_id': fields.many2one('stock.production.lot', 'Production Lot', domain="[('product_id','=',product_id)]"),
2282         'state': fields.related('inventory_id','state',type='char',string='State',readonly=True),
2283     }
2284
2285     def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
2286         """ Changes UoM and name if product_id changes.
2287         @param location_id: Location id
2288         @param product: Changed product_id
2289         @param uom: UoM product
2290         @return:  Dictionary of changed values
2291         """
2292         if not product:
2293             return {}
2294         if not uom:
2295             prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0]
2296             uom = prod.uom_id.id
2297         amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
2298         result = {'product_qty': amount, 'product_uom': uom}
2299         return {'value': result}
2300
2301 stock_inventory_line()
2302
2303 #----------------------------------------------------------
2304 # Stock Warehouse
2305 #----------------------------------------------------------
2306 class stock_warehouse(osv.osv):
2307     _name = "stock.warehouse"
2308     _description = "Warehouse"
2309     _columns = {
2310         'name': fields.char('Name', size=60, required=True),
2311         'company_id': fields.many2one('res.company','Company',required=True,select=1),
2312         'partner_address_id': fields.many2one('res.partner.address', 'Owner Address'),
2313         'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
2314         'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','<>','view')]),
2315         'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
2316     }
2317     _defaults = {
2318         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.inventory', context=c),
2319     }
2320
2321 stock_warehouse()
2322
2323
2324 # Move wizard :
2325 #    get confirm or assign stock move lines of partner and put in current picking.
2326 class stock_picking_move_wizard(osv.osv_memory):
2327     _name = 'stock.picking.move.wizard'
2328
2329     def _get_picking(self, cr, uid, ctx=None):
2330         if ctx is None:
2331             ctx = {}
2332         if ctx.get('action_id', False):
2333             return ctx['action_id']
2334         return False
2335
2336     def _get_picking_address(self, cr, uid, context=None):
2337         picking_obj = self.pool.get('stock.picking')
2338         if context is None:
2339             context = {}
2340         if context.get('action_id', False):
2341             picking = picking_obj.browse(cr, uid, [context['action_id']])[0]
2342             return picking.address_id and picking.address_id.id or False
2343         return False
2344
2345     _columns = {
2346         'name': fields.char('Name', size=64, invisible=True),
2347         'move_ids': fields.many2many('stock.move', 'picking_move_wizard_rel', 'picking_move_wizard_id', 'move_id', 'Entry lines', required=True),
2348         'address_id': fields.many2one('res.partner.address', 'Dest. Address', invisible=True),
2349         'picking_id': fields.many2one('stock.picking', 'Picking list', select=True, invisible=True),
2350     }
2351     _defaults = {
2352         'picking_id': _get_picking,
2353         'address_id': _get_picking_address,
2354     }
2355
2356     def action_move(self, cr, uid, ids, context=None):
2357         move_obj = self.pool.get('stock.move')
2358         picking_obj = self.pool.get('stock.picking')
2359         account_move_obj = self.pool.get('account.move')
2360         for act in self.read(cr, uid, ids):
2361             move_lines = move_obj.browse(cr, uid, act['move_ids'])
2362             for line in move_lines:
2363                 if line.picking_id:
2364                     picking_obj.write(cr, uid, [line.picking_id.id], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2365                     picking_obj.write(cr, uid, [act['picking_id']], {'move_lines': [(1, line.id, {'picking_id': act['picking_id']})]})
2366                     old_picking = picking_obj.read(cr, uid, [line.picking_id.id])[0]
2367                     if not len(old_picking['move_lines']):
2368                         picking_obj.write(cr, uid, [old_picking['id']], {'state': 'done'})
2369                 else:
2370                     raise osv.except_osv(_('UserError'),
2371                         _('You can not create new moves.'))
2372         return {'type': 'ir.actions.act_window_close'}
2373
2374 stock_picking_move_wizard()
2375
2376 class report_products_to_received_planned(osv.osv):
2377     _name = "report.products.to.received.planned"
2378     _description = "Product to Received Vs Planned"
2379     _auto = False
2380     _columns = {
2381         'date':fields.date('Date'),
2382         'qty': fields.integer('Actual Qty'),
2383         'planned_qty': fields.integer('Planned Qty'),
2384
2385     }
2386     def init(self, cr):
2387         tools.drop_view_if_exists(cr, 'report_products_to_received_planned')
2388         cr.execute("""
2389             create or replace view report_products_to_received_planned as (
2390                select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2391                    from stock_picking picking
2392                     inner join stock_move stock
2393                     on picking.id = stock.picking_id and picking.type = 'in'
2394                     where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2395                     group by stock.date
2396
2397                     union
2398
2399                select stock.date_planned, min(stock.id) as id, 0 as actual_qty, sum(stock.product_qty) as planned_qty
2400                     from stock_picking picking
2401                     inner join stock_move stock
2402                     on picking.id = stock.picking_id and picking.type = 'in'
2403                     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)
2404         group by stock.date_planned
2405                 )
2406         """)
2407
2408 report_products_to_received_planned()
2409
2410 class report_delivery_products_planned(osv.osv):
2411     _name = "report.delivery.products.planned"
2412     _description = "Number of Delivery products vs planned"
2413     _auto = False
2414     _columns = {
2415         'date':fields.date('Date'),
2416         'qty': fields.integer('Actual Qty'),
2417         'planned_qty': fields.integer('Planned Qty'),
2418
2419     }
2420
2421     def init(self, cr):
2422         tools.drop_view_if_exists(cr, 'report_delivery_products_planned')
2423         cr.execute("""
2424             create or replace view report_delivery_products_planned as (
2425                 select stock.date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
2426                    from stock_picking picking
2427                     inner join stock_move stock
2428                     on picking.id = stock.picking_id and picking.type = 'out'
2429                     where stock.date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7)
2430                     group by stock.date
2431
2432                     union
2433
2434                select stock.date_planned, min(stock.id), 0 as actual_qty, sum(stock.product_qty) as planned_qty
2435                     from stock_picking picking
2436                     inner join stock_move stock
2437                     on picking.id = stock.picking_id and picking.type = 'out'
2438                     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)
2439         group by stock.date_planned
2440
2441
2442                 )
2443         """)
2444
2445 report_delivery_products_planned()
2446
2447 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: