[FIX] stock: fixed product_available function to take the location and warehouse...
[odoo/odoo.git] / addons / stock / product.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 import openerp.addons.decimal_precision as dp
25
26 class product_product(osv.osv):
27     _inherit = "product.product"
28         
29     def _stock_move_count(self, cr, uid, ids, field_name, arg, context=None):
30         res = dict([(id, {'reception_count': 0, 'delivery_count': 0}) for id in ids])
31         move_pool=self.pool.get('stock.move')
32         moves = move_pool.read_group(cr, uid, [
33             ('product_id', 'in', ids),
34             ('location_id.usage', '!=', 'internal'),
35             ('location_dest_id.usage', '=', 'internal'),
36             ('state','in',('confirmed','assigned','pending'))
37         ], ['product_id'], ['product_id'])
38         for move in moves:
39             product_id = move['product_id'][0]
40             res[product_id]['reception_count'] = move['product_id_count']
41         moves = move_pool.read_group(cr, uid, [
42             ('product_id', 'in', ids),
43             ('location_id.usage', '=', 'internal'),
44             ('location_dest_id.usage', '!=', 'internal'),
45             ('state','in',('confirmed','assigned','pending'))
46         ], ['product_id'], ['product_id'])
47         for move in moves:
48             product_id = move['product_id'][0]
49             res[product_id]['delivery_count'] = move['product_id_count']
50         return res
51
52     def view_header_get(self, cr, user, view_id, view_type, context=None):
53         if context is None:
54             context = {}
55         res = super(product_product, self).view_header_get(cr, user, view_id, view_type, context)
56         if res: return res
57         if (context.get('active_id', False)) and (context.get('active_model') == 'stock.location'):
58             return _('Products: ')+self.pool.get('stock.location').browse(cr, user, context['active_id'], context).name
59         return res
60
61     def _get_domain_locations(self, cr, uid, ids, context=None):
62         '''
63         Parses the context and returns a list of location_ids based on it.
64         It will return all stock locations when no parameters are given
65         Possible parameters are shop, warehouse, location, force_company, compute_child
66         '''
67         context = context or {}
68
69         location_obj = self.pool.get('stock.location')
70         warehouse_obj = self.pool.get('stock.warehouse')
71
72         location_ids = []
73         if context.get('location', False):
74             if type(context['location']) == type(1):
75                 location_ids = [context['location']]
76             elif type(context['location']) in (type(''), type(u'')):
77                 domain = [('complete_name','ilike',context['location'])]
78                 if context.get('force_company', False):
79                     domain += [('company_id', '=', context['force_company'])]
80                 location_ids = location_obj.search(cr, uid, domain, context=context)
81             else:
82                 location_ids = context['location']
83         else:
84             if context.get('warehouse', False):
85                 wids = [context['warehouse']]
86             else:
87                 wids = warehouse_obj.search(cr, uid, [], context=context)
88
89             for w in warehouse_obj.browse(cr, uid, wids, context=context):
90                 location_ids.append(w.lot_stock_id.id)
91
92         operator = context.get('compute_child',True) and 'child_of' or 'in'
93         domain = context.get('force_company', False) and ['&', ('company_id', '=', context['force_company'])] or []
94         domain += [('product_id', 'in', ids)]
95         return (
96             domain + [('location_id', operator, location_ids)],
97             domain + ['&', ('location_dest_id', operator, location_ids), '!', ('location_id', operator, location_ids)],
98             domain + ['&', ('location_id', operator, location_ids), '!', ('location_dest_id', operator, location_ids)]
99         )
100
101     def _get_domain_dates(self, cr, uid, ids, context):
102         from_date = context.get('from_date',False)
103         to_date = context.get('to_date',False)
104         domain = []
105         if from_date:
106             domain.append(('date','>=',from_date))
107         if to_date:
108             domain.append(('date','<=',to_date))
109         return domain
110
111     def _product_available(self, cr, uid, ids, field_names=None, arg=False, context=None):
112         context = context or {}
113         field_names = field_names or []
114
115         domain_products = [('product_id', 'in', ids)]
116         domain_quant, domain_move_in, domain_move_out = self._get_domain_locations(cr, uid, ids, context=context)
117         domain_move_in += self._get_domain_dates(cr, uid, ids, context=context) + [('state','not in',('done','cancel'))] + domain_products
118         domain_move_out += self._get_domain_dates(cr, uid, ids, context=context) + [('state','not in',('done','cancel'))] + domain_products
119         domain_quant += domain_products
120         if context.get('lot_id') or context.get('owner_id') or context.get('package_id'):
121             if context.get('lot_id'):
122                 domain_quant.append(('lot_id','=',context['lot_id']))
123             if context.get('owner_id'):
124                 domain_quant.append(('owner_id','=',context['owner_id']))
125             if context.get('package_id'):
126                 domain_quant.append(('package_id','=',context['package_id']))
127             moves_in  = []
128             moves_out = []
129         else:
130 #             if field_names in ['incoming_qty', 'outgoing_qty', 'virtual_available']:
131             moves_in  = self.pool.get('stock.move').read_group(cr, uid, domain_move_in, ['product_id', 'product_qty'], ['product_id'], context=context)
132             moves_out = self.pool.get('stock.move').read_group(cr, uid, domain_move_out, ['product_id', 'product_qty'], ['product_id'], context=context)
133             
134         quants = self.pool.get('stock.quant').read_group(cr, uid, domain_quant, ['product_id', 'qty'], ['product_id'], context=context)
135         quants = dict(map(lambda x: (x['product_id'][0], x['qty']), quants))
136             
137         moves_in = dict(map(lambda x: (x['product_id'][0], x['product_qty']), moves_in))
138         moves_out = dict(map(lambda x: (x['product_id'][0], x['product_qty']), moves_out))
139
140         res = {}
141         for id in ids:
142             res[id] = {
143                 'qty_available': quants.get(id, 0.0),
144                 'incoming_qty': moves_in.get(id, 0.0),
145                 'outgoing_qty': moves_out.get(id, 0.0),
146                 'virtual_available': quants.get(id, 0.0) + moves_in.get(id, 0.0) - moves_out.get(id, 0.0),
147             }            
148             
149         return res
150
151     _columns = {
152         'reception_count': fields.function(_stock_move_count, string="Reception", type='integer', multi='pickings'),
153         'delivery_count': fields.function(_stock_move_count, string="Delivery", type='integer', multi='pickings'),
154         'qty_available': fields.function(_product_available, multi='qty_available',
155             type='float',  digits_compute=dp.get_precision('Product Unit of Measure'),
156             string='Quantity On Hand',
157             help="Current quantity of products.\n"
158                  "In a context with a single Stock Location, this includes "
159                  "goods stored at this Location, or any of its children.\n"
160                  "In a context with a single Warehouse, this includes "
161                  "goods stored in the Stock Location of this Warehouse, or any "
162                  "of its children.\n"
163                  "stored in the Stock Location of the Warehouse of this Shop, "
164                  "or any of its children.\n"
165                  "Otherwise, this includes goods stored in any Stock Location "
166                  "with 'internal' type."),
167         'virtual_available': fields.function(_product_available, multi='qty_available',
168             type='float',  digits_compute=dp.get_precision('Product Unit of Measure'),
169             string='Forecasted Quantity',
170             help="Forecast quantity (computed as Quantity On Hand "
171                  "- Outgoing + Incoming)\n"
172                  "In a context with a single Stock Location, this includes "
173                  "goods stored in this location, or any of its children.\n"
174                  "In a context with a single Warehouse, this includes "
175                  "goods stored in the Stock Location of this Warehouse, or any "
176                  "of its children.\n"
177                  "stored in the Stock Location of the Warehouse of this Shop, "
178                  "or any of its children.\n"
179                  "Otherwise, this includes goods stored in any Stock Location "
180                  "with 'internal' type."),
181         'incoming_qty': fields.function(_product_available, multi='qty_available',
182             type='float',  digits_compute=dp.get_precision('Product Unit of Measure'),
183             string='Incoming',
184             help="Quantity of products that are planned to arrive.\n"
185                  "In a context with a single Stock Location, this includes "
186                  "goods arriving to this Location, or any of its children.\n"
187                  "In a context with a single Warehouse, this includes "
188                  "goods arriving to the Stock Location of this Warehouse, or "
189                  "any of its children.\n"
190                  "In a context with a single Shop, this includes goods "
191                  "arriving to the Stock Location of the Warehouse of this "
192                  "Shop, or any of its children.\n"
193                  "Otherwise, this includes goods arriving to any Stock "
194                  "Location with 'internal' type."),
195         'outgoing_qty': fields.function(_product_available, multi='qty_available',
196             type='float',  digits_compute=dp.get_precision('Product Unit of Measure'),
197             string='Outgoing',
198             help="Quantity of products that are planned to leave.\n"
199                  "In a context with a single Stock Location, this includes "
200                  "goods leaving this Location, or any of its children.\n"
201                  "In a context with a single Warehouse, this includes "
202                  "goods leaving the Stock Location of this Warehouse, or "
203                  "any of its children.\n"
204                  "In a context with a single Shop, this includes goods "
205                  "leaving the Stock Location of the Warehouse of this "
206                  "Shop, or any of its children.\n"
207                  "Otherwise, this includes goods leaving any Stock "
208                  "Location with 'internal' type."),
209         'track_production': fields.boolean('Track Manufacturing Lots', help="Forces to specify a Serial Number for all moves containing this product and generated by a Manufacturing Order"),
210         'track_incoming': fields.boolean('Track Incoming Lots', help="Forces to specify a Serial Number for all moves containing this product and coming from a Supplier Location"),
211         'track_outgoing': fields.boolean('Track Outgoing Lots', help="Forces to specify a Serial Number for all moves containing this product and going to a Customer Location"),
212         'location_id': fields.dummy(string='Location', relation='stock.location', type='many2one'),
213         'warehouse_id': fields.dummy(string='Warehouse', relation='stock.warehouse', type='many2one'),
214         'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
215         'route_ids': fields.many2many('stock.location.route', 'stock_route_product', 'product_id', 'route_id', 'Routes', domain="[('product_selectable', '=', True)]",
216                                     help="Depending on the modules installed, this will allow you to define the route of the product: whether it will be bought, manufactured, MTO/MTS,..."),
217     }
218
219     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
220         res = super(product_product,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
221         if context is None:
222             context = {}
223         if ('location' in context) and context['location']:
224             location_info = self.pool.get('stock.location').browse(cr, uid, context['location'])
225             fields=res.get('fields',{})
226             if fields:
227                 if location_info.usage == 'supplier':
228                     if fields.get('virtual_available'):
229                         res['fields']['virtual_available']['string'] = _('Future Receptions')
230                     if fields.get('qty_available'):
231                         res['fields']['qty_available']['string'] = _('Received Qty')
232
233                 if location_info.usage == 'internal':
234                     if fields.get('virtual_available'):
235                         res['fields']['virtual_available']['string'] = _('Future Stock')
236
237                 if location_info.usage == 'customer':
238                     if fields.get('virtual_available'):
239                         res['fields']['virtual_available']['string'] = _('Future Deliveries')
240                     if fields.get('qty_available'):
241                         res['fields']['qty_available']['string'] = _('Delivered Qty')
242
243                 if location_info.usage == 'inventory':
244                     if fields.get('virtual_available'):
245                         res['fields']['virtual_available']['string'] = _('Future P&L')
246                     if fields.get('qty_available'):
247                         res['fields']['qty_available']['string'] = _('P&L Qty')
248
249                 if location_info.usage == 'procurement':
250                     if fields.get('virtual_available'):
251                         res['fields']['virtual_available']['string'] = _('Future Qty')
252                     if fields.get('qty_available'):
253                         res['fields']['qty_available']['string'] = _('Unplanned Qty')
254
255                 if location_info.usage == 'production':
256                     if fields.get('virtual_available'):
257                         res['fields']['virtual_available']['string'] = _('Future Productions')
258                     if fields.get('qty_available'):
259                         res['fields']['qty_available']['string'] = _('Produced Qty')
260         return res
261
262     def action_view_routes(self, cr, uid, ids, context=None):
263         route_obj = self.pool.get("stock.location.route")
264         act_obj = self.pool.get('ir.actions.act_window')
265         mod_obj = self.pool.get('ir.model.data')
266         product_route_ids = set()
267         for product in self.browse(cr, uid, ids, context=context):
268             product_route_ids |= set([r.id for r in product.route_ids])
269             product_route_ids |= set([r.id for r in product.categ_id.total_route_ids])
270         route_ids = route_obj.search(cr, uid, ['|', ('id', 'in', list(product_route_ids)), ('warehouse_selectable', '=', True)], context=context)
271         result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_routes_form')
272         id = result and result[1] or False
273         result = act_obj.read(cr, uid, [id], context=context)[0]
274         result['domain'] = "[('id','in',[" + ','.join(map(str, route_ids)) + "])]"
275         return result
276
277 class product_template(osv.osv):
278     _name = 'product.template'
279     _inherit = 'product.template'
280     _columns = {
281         'type': fields.selection([('product', 'Stockable Product'), ('consu', 'Consumable'), ('service', 'Service')], 'Product Type', required=True, help="Consumable: Will not imply stock management for this product. \nStockable product: Will imply stock management for this product."),
282         'property_stock_procurement': fields.property(
283             type='many2one',
284             relation='stock.location',
285             string="Procurement Location",
286             domain=[('usage','like','procurement')],
287             help="This stock location will be used, instead of the default one, as the source location for stock moves generated by procurements."),
288         'property_stock_production': fields.property(
289             type='many2one',
290             relation='stock.location',
291             string="Production Location",
292             domain=[('usage','like','production')],
293             help="This stock location will be used, instead of the default one, as the source location for stock moves generated by manufacturing orders."),
294         'property_stock_inventory': fields.property(
295             type='many2one',
296             relation='stock.location',
297             string="Inventory Location",
298             domain=[('usage','like','inventory')],
299             help="This stock location will be used, instead of the default one, as the source location for stock moves generated when you do an inventory."),
300         'sale_delay': fields.float('Customer Lead Time', help="The average delay in days between the confirmation of the customer order and the delivery of the finished products. It's the time you promise to your customers."),
301         'loc_rack': fields.char('Rack', size=16),
302         'loc_row': fields.char('Row', size=16),
303         'loc_case': fields.char('Case', size=16),
304     }
305
306     _defaults = {
307         'sale_delay': 7,
308     }
309     
310   
311 class product_removal_strategy(osv.osv):
312     _name = 'product.removal'
313     _description = 'Removal Strategy'
314     _order = 'sequence'
315     _columns = {
316         'product_categ_id': fields.many2one('product.category', 'Category', required=True), 
317         'sequence': fields.integer('Sequence'),
318         'method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO')], "Method", required = True),
319         'location_id': fields.many2one('stock.location', 'Locations', required=True),
320     }
321
322
323 class product_putaway_strategy(osv.osv):
324     _name = 'product.putaway'
325     _description = 'Put Away Strategy'
326     _columns = {
327         'product_categ_id':fields.many2one('product.category', 'Product Category', required=True),
328         'location_id': fields.many2one('stock.location','Parent Location', help="Parent Destination Location from which a child bin location needs to be chosen", required=True), #domain=[('type', '=', 'parent')], 
329         'method': fields.selection([('fixed', 'Fixed Location')], "Method", required = True),
330         'location_spec_id': fields.many2one('stock.location','Specific Location', help="When the location is specific, it will be put over there"), #domain=[('type', '=', 'parent')],
331     }
332
333
334 class product_category(osv.osv):
335     _inherit = 'product.category'
336     
337     def calculate_total_routes(self, cr, uid, ids, name, args, context=None):
338         res = {}
339         route_obj = self.pool.get("stock.location.route")
340         for categ in self.browse(cr, uid, ids, context=context):
341             categ2 = categ
342             routes = [x.id for x in categ.route_ids]
343             while categ2.parent_id:
344                 categ2 = categ2.parent_id
345                 routes += [x.id for x in categ2.route_ids]
346             res[categ.id] = routes
347         return res
348         
349     _columns = {
350         'route_ids': fields.many2many('stock.location.route', 'stock_location_route_categ', 'categ_id', 'route_id', 'Routes', domain="[('product_categ_selectable', '=', True)]"),
351         'removal_strategy_ids': fields.one2many('product.removal', 'product_categ_id', 'Removal Strategies'),
352         'putaway_strategy_ids': fields.one2many('product.putaway', 'product_categ_id', 'Put Away Strategies'),
353         'total_route_ids': fields.function(calculate_total_routes, relation='stock.location.route', type='many2many', string='Total routes', readonly=True),
354     }
355
356
357 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: