1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 from openerp.tools.safe_eval import safe_eval as eval
25 import openerp.addons.decimal_precision as dp
27 class product_product(osv.osv):
28 _inherit = "product.product"
30 def _stock_move_count(self, cr, uid, ids, field_name, arg, context=None):
31 res = dict([(id, {'reception_count': 0, 'delivery_count': 0}) for id in ids])
32 move_pool=self.pool.get('stock.move')
33 moves = move_pool.read_group(cr, uid, [
34 ('product_id', 'in', ids),
35 ('location_id.usage', '!=', 'internal'),
36 ('location_dest_id.usage', '=', 'internal'),
37 ('state','in',('confirmed','assigned','pending'))
38 ], ['product_id'], ['product_id'])
40 product_id = move['product_id'][0]
41 res[product_id]['reception_count'] = move['product_id_count']
42 moves = move_pool.read_group(cr, uid, [
43 ('product_id', 'in', ids),
44 ('location_id.usage', '=', 'internal'),
45 ('location_dest_id.usage', '!=', 'internal'),
46 ('state','in',('confirmed','assigned','pending'))
47 ], ['product_id'], ['product_id'])
49 product_id = move['product_id'][0]
50 res[product_id]['delivery_count'] = move['product_id_count']
53 def view_header_get(self, cr, user, view_id, view_type, context=None):
56 res = super(product_product, self).view_header_get(cr, user, view_id, view_type, context)
58 if (context.get('active_id', False)) and (context.get('active_model') == 'stock.location'):
59 return _('Products: ')+self.pool.get('stock.location').browse(cr, user, context['active_id'], context).name
62 def _get_domain_locations(self, cr, uid, ids, context=None):
64 Parses the context and returns a list of location_ids based on it.
65 It will return all stock locations when no parameters are given
66 Possible parameters are shop, warehouse, location, force_company, compute_child
68 context = context or {}
70 location_obj = self.pool.get('stock.location')
71 warehouse_obj = self.pool.get('stock.warehouse')
74 if context.get('location', False):
75 if type(context['location']) == type(1):
76 location_ids = [context['location']]
77 elif type(context['location']) in (type(''), type(u'')):
78 domain = [('complete_name','ilike',context['location'])]
79 if context.get('force_company', False):
80 domain += [('company_id', '=', context['force_company'])]
81 location_ids = location_obj.search(cr, uid, domain, context=context)
83 location_ids = context['location']
85 if context.get('warehouse', False):
86 wids = [context['warehouse']]
88 wids = warehouse_obj.search(cr, uid, [], context=context)
90 for w in warehouse_obj.browse(cr, uid, wids, context=context):
91 location_ids.append(w.view_location_id.id)
93 operator = context.get('compute_child',True) and 'child_of' or 'in'
94 domain = context.get('force_company', False) and ['&', ('company_id', '=', context['force_company'])] or []
95 domain += [('product_id', 'in', ids)]
97 domain + [('location_id', operator, location_ids)],
98 domain + ['&', ('location_dest_id', operator, location_ids), '!', ('location_id', operator, location_ids)],
99 domain + ['&', ('location_id', operator, location_ids), '!', ('location_dest_id', operator, location_ids)]
102 def _get_domain_dates(self, cr, uid, ids, context):
103 from_date = context.get('from_date', False)
104 to_date = context.get('to_date', False)
107 domain.append(('date', '>=', from_date))
109 domain.append(('date', '<=', to_date))
112 def _product_available(self, cr, uid, ids, field_names=None, arg=False, context=None):
113 context = context or {}
114 field_names = field_names or []
116 domain_products = [('product_id', 'in', ids)]
117 domain_quant, domain_move_in, domain_move_out = self._get_domain_locations(cr, uid, ids, context=context)
118 domain_move_in += self._get_domain_dates(cr, uid, ids, context=context) + [('state', 'not in', ('done', 'cancel'))] + domain_products
119 domain_move_out += self._get_domain_dates(cr, uid, ids, context=context) + [('state', 'not in', ('done', 'cancel'))] + domain_products
120 domain_quant += domain_products
121 if context.get('lot_id') or context.get('owner_id') or context.get('package_id'):
122 if context.get('lot_id'):
123 domain_quant.append(('lot_id', '=', context['lot_id']))
124 if context.get('owner_id'):
125 domain_quant.append(('owner_id', '=', context['owner_id']))
126 if context.get('package_id'):
127 domain_quant.append(('package_id', '=', context['package_id']))
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)
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))
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))
142 'qty_available': quants.get(id, 0.0),
143 'incoming_qty': moves_in.get(id, 0.0),
144 'outgoing_qty': moves_out.get(id, 0.0),
145 'virtual_available': quants.get(id, 0.0) + moves_in.get(id, 0.0) - moves_out.get(id, 0.0),
150 def _search_product_quantity(self, cr, uid, obj, name, domain, context):
152 for field, operator, value in domain:
153 #to prevent sql injections
154 assert field in ('qty_available', 'virtual_available', 'incoming_qty', 'outgoing_qty'), 'Invalid domain left operand'
155 assert operator in ('<', '>', '=', '<=', '>='), 'Invalid domain operator'
156 assert isinstance(value, (float, int)), 'Invalid domain right operand'
161 product_ids = self.search(cr, uid, [], context=context)
164 #TODO: use a query instead of this browse record which is probably making the too much requests, but don't forget
165 #the context that can be set with a location, an owner...
166 for element in self.browse(cr, uid, product_ids, context=context):
167 if eval(str(element[field]) + operator + str(value)):
168 ids.append(element.id)
169 res.append(('id', 'in', ids))
173 'reception_count': fields.function(_stock_move_count, string="Reception", type='integer', multi='pickings'),
174 'delivery_count': fields.function(_stock_move_count, string="Delivery", type='integer', multi='pickings'),
175 'qty_available': fields.function(_product_available, multi='qty_available',
176 type='float', digits_compute=dp.get_precision('Product Unit of Measure'),
177 string='Quantity On Hand',
178 fnct_search=_search_product_quantity,
179 help="Current quantity of products.\n"
180 "In a context with a single Stock Location, this includes "
181 "goods stored at this Location, or any of its children.\n"
182 "In a context with a single Warehouse, this includes "
183 "goods stored in the Stock Location of this Warehouse, or any "
185 "stored in the Stock Location of the Warehouse of this Shop, "
186 "or any of its children.\n"
187 "Otherwise, this includes goods stored in any Stock Location "
188 "with 'internal' type."),
189 'virtual_available': fields.function(_product_available, multi='qty_available',
190 type='float', digits_compute=dp.get_precision('Product Unit of Measure'),
191 string='Forecast Quantity',
192 fnct_search=_search_product_quantity,
193 help="Forecast quantity (computed as Quantity On Hand "
194 "- Outgoing + Incoming)\n"
195 "In a context with a single Stock Location, this includes "
196 "goods stored in this location, or any of its children.\n"
197 "In a context with a single Warehouse, this includes "
198 "goods stored in the Stock Location of this Warehouse, or any "
200 "Otherwise, this includes goods stored in any Stock Location "
201 "with 'internal' type."),
202 'incoming_qty': fields.function(_product_available, multi='qty_available',
203 type='float', digits_compute=dp.get_precision('Product Unit of Measure'),
205 fnct_search=_search_product_quantity,
206 help="Quantity of products that are planned to arrive.\n"
207 "In a context with a single Stock Location, this includes "
208 "goods arriving to this Location, or any of its children.\n"
209 "In a context with a single Warehouse, this includes "
210 "goods arriving to the Stock Location of this Warehouse, or "
211 "any of its children.\n"
212 "Otherwise, this includes goods arriving to any Stock "
213 "Location with 'internal' type."),
214 'outgoing_qty': fields.function(_product_available, multi='qty_available',
215 type='float', digits_compute=dp.get_precision('Product Unit of Measure'),
217 fnct_search=_search_product_quantity,
218 help="Quantity of products that are planned to leave.\n"
219 "In a context with a single Stock Location, this includes "
220 "goods leaving this Location, or any of its children.\n"
221 "In a context with a single Warehouse, this includes "
222 "goods leaving the Stock Location of this Warehouse, or "
223 "any of its children.\n"
224 "Otherwise, this includes goods leaving any Stock "
225 "Location with 'internal' type."),
226 '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"),
227 '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"),
228 'track_all': fields.boolean('Full Lots Traceability', help="Forces to specify a Serial Number on each and every operation related to this product"),
229 'location_id': fields.dummy(string='Location', relation='stock.location', type='many2one'),
230 'warehouse_id': fields.dummy(string='Warehouse', relation='stock.warehouse', type='many2one'),
231 'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
232 'route_ids': fields.many2many('stock.location.route', 'stock_route_product', 'product_id', 'route_id', 'Routes', domain="[('product_selectable', '=', True)]",
233 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,..."),
236 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
237 res = super(product_product,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
240 if ('location' in context) and context['location']:
241 location_info = self.pool.get('stock.location').browse(cr, uid, context['location'])
242 fields=res.get('fields',{})
244 if location_info.usage == 'supplier':
245 if fields.get('virtual_available'):
246 res['fields']['virtual_available']['string'] = _('Future Receptions')
247 if fields.get('qty_available'):
248 res['fields']['qty_available']['string'] = _('Received Qty')
250 if location_info.usage == 'internal':
251 if fields.get('virtual_available'):
252 res['fields']['virtual_available']['string'] = _('Future Stock')
254 if location_info.usage == 'customer':
255 if fields.get('virtual_available'):
256 res['fields']['virtual_available']['string'] = _('Future Deliveries')
257 if fields.get('qty_available'):
258 res['fields']['qty_available']['string'] = _('Delivered Qty')
260 if location_info.usage == 'inventory':
261 if fields.get('virtual_available'):
262 res['fields']['virtual_available']['string'] = _('Future P&L')
263 if fields.get('qty_available'):
264 res['fields']['qty_available']['string'] = _('P&L Qty')
266 if location_info.usage == 'procurement':
267 if fields.get('virtual_available'):
268 res['fields']['virtual_available']['string'] = _('Future Qty')
269 if fields.get('qty_available'):
270 res['fields']['qty_available']['string'] = _('Unplanned Qty')
272 if location_info.usage == 'production':
273 if fields.get('virtual_available'):
274 res['fields']['virtual_available']['string'] = _('Future Productions')
275 if fields.get('qty_available'):
276 res['fields']['qty_available']['string'] = _('Produced Qty')
279 def action_view_routes(self, cr, uid, ids, context=None):
280 route_obj = self.pool.get("stock.location.route")
281 act_obj = self.pool.get('ir.actions.act_window')
282 mod_obj = self.pool.get('ir.model.data')
283 product_route_ids = set()
284 for product in self.browse(cr, uid, ids, context=context):
285 product_route_ids |= set([r.id for r in product.route_ids])
286 product_route_ids |= set([r.id for r in product.categ_id.total_route_ids])
287 route_ids = route_obj.search(cr, uid, ['|', ('id', 'in', list(product_route_ids)), ('warehouse_selectable', '=', True)], context=context)
288 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_routes_form')
289 id = result and result[1] or False
290 result = act_obj.read(cr, uid, [id], context=context)[0]
291 result['domain'] = "[('id','in',[" + ','.join(map(str, route_ids)) + "])]"
295 def copy(self, cr, uid, id, default=None, context=None):
296 context = context or {}
297 default = dict(default or {})
299 product = self.browse(cr, uid, id, context=context)
300 op_obj = self.pool.get('stock.warehouse.orderpoint')
302 for orderpoint in product.orderpoint_ids:
303 op_val = op_obj.copy(cr, uid, orderpoint.id, context=context)
304 op_ids.append(op_val)
305 default['orderpoint_ids'] = [(6, 0, op_ids)]
306 res = super(product_product, self).copy(cr, uid, id, default=default, context=context)
310 class product_template(osv.osv):
311 _name = 'product.template'
312 _inherit = 'product.template'
314 '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."),
315 'property_stock_procurement': fields.property(
317 relation='stock.location',
318 string="Procurement Location",
319 domain=[('usage','like','procurement')],
320 help="This stock location will be used, instead of the default one, as the source location for stock moves generated by procurements."),
321 'property_stock_production': fields.property(
323 relation='stock.location',
324 string="Production Location",
325 domain=[('usage','like','production')],
326 help="This stock location will be used, instead of the default one, as the source location for stock moves generated by manufacturing orders."),
327 'property_stock_inventory': fields.property(
329 relation='stock.location',
330 string="Inventory Location",
331 domain=[('usage','like','inventory')],
332 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."),
333 '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."),
334 'loc_rack': fields.char('Rack', size=16),
335 'loc_row': fields.char('Row', size=16),
336 'loc_case': fields.char('Case', size=16),
344 class product_removal_strategy(osv.osv):
345 _name = 'product.removal'
346 _description = 'Removal Strategy'
349 'product_categ_id': fields.many2one('product.category', 'Category', required=True),
350 'sequence': fields.integer('Sequence'),
351 'method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO')], "Method", required = True),
352 'location_id': fields.many2one('stock.location', 'Locations', required=True),
356 class product_putaway_strategy(osv.osv):
357 _name = 'product.putaway'
358 _description = 'Put Away Strategy'
360 'product_categ_id':fields.many2one('product.category', 'Product Category', required=True),
361 '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')],
362 'method': fields.selection([('fixed', 'Fixed Location')], "Method", required = True),
363 'location_spec_id': fields.many2one('stock.location','Specific Location', help="When the location is specific, it will be put over there"), #domain=[('type', '=', 'parent')],
367 class product_category(osv.osv):
368 _inherit = 'product.category'
370 def calculate_total_routes(self, cr, uid, ids, name, args, context=None):
372 route_obj = self.pool.get("stock.location.route")
373 for categ in self.browse(cr, uid, ids, context=context):
375 routes = [x.id for x in categ.route_ids]
376 while categ2.parent_id:
377 categ2 = categ2.parent_id
378 routes += [x.id for x in categ2.route_ids]
379 res[categ.id] = routes
383 'route_ids': fields.many2many('stock.location.route', 'stock_location_route_categ', 'categ_id', 'route_id', 'Routes', domain="[('product_categ_selectable', '=', True)]"),
384 'removal_strategy_ids': fields.one2many('product.removal', 'product_categ_id', 'Removal Strategies'),
385 'putaway_strategy_ids': fields.one2many('product.putaway', 'product_categ_id', 'Put Away Strategies'),
386 'total_route_ids': fields.function(calculate_total_routes, relation='stock.location.route', type='many2many', string='Total routes', readonly=True),
390 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: