[MERGE] Forward-port of latest 7.0 bugfixes, up to rev. 9529 rev-id: mat@openerp...
[odoo/odoo.git] / addons / procurement / procurement.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 operator import attrgetter
23 import time
24
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp import netsvc
28 import openerp.addons.decimal_precision as dp
29
30 # Procurement
31 # ------------------------------------------------------------------
32 #
33 # Produce, Buy or Find products and place a move
34 #     then wizard for picking lists & move
35 #
36
37 class mrp_property_group(osv.osv):
38     """
39     Group of mrp properties.
40     """
41     _name = 'mrp.property.group'
42     _description = 'Property Group'
43     _columns = {
44         'name': fields.char('Property Group', size=64, required=True),
45         'description': fields.text('Description'),
46     }
47
48 class mrp_property(osv.osv):
49     """
50     Properties of mrp.
51     """
52     _name = 'mrp.property'
53     _description = 'Property'
54     _columns = {
55         'name': fields.char('Name', size=64, required=True),
56         'composition': fields.selection([('min','min'),('max','max'),('plus','plus')], 'Properties composition', required=True, help="Not used in computations, for information purpose only."),
57         'group_id': fields.many2one('mrp.property.group', 'Property Group', required=True),
58         'description': fields.text('Description'),
59     }
60     _defaults = {
61         'composition': lambda *a: 'min',
62     }
63
64 class StockMove(osv.osv):
65     _inherit = 'stock.move'
66     _columns= {
67         'procurements': fields.one2many('procurement.order', 'move_id', 'Procurements'),
68     }
69
70     def copy_data(self, cr, uid, id, default=None, context=None):
71         if default is None:
72             default = {}
73         default['procurements'] = []
74         return super(StockMove, self).copy_data(cr, uid, id, default, context=context)
75
76
77 class procurement_order(osv.osv):
78     """
79     Procurement Orders
80     """
81     _name = "procurement.order"
82     _description = "Procurement"
83     _order = 'priority desc,date_planned'
84     _inherit = ['mail.thread']
85     _log_create = False
86     _columns = {
87         'name': fields.text('Description', required=True),
88         'origin': fields.char('Source Document', size=64,
89             help="Reference of the document that created this Procurement.\n"
90             "This is automatically completed by OpenERP."),
91         'priority': fields.selection([('0','Not urgent'),('1','Normal'),('2','Urgent'),('3','Very Urgent')], 'Priority', required=True, select=True),
92         'date_planned': fields.datetime('Scheduled date', required=True, select=True),
93         'date_close': fields.datetime('Date Closed'),
94         'product_id': fields.many2one('product.product', 'Product', required=True, states={'draft':[('readonly',False)]}, readonly=True),
95         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True, states={'draft':[('readonly',False)]}, readonly=True),
96         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True, states={'draft':[('readonly',False)]}, readonly=True),
97         'product_uos_qty': fields.float('UoS Quantity', states={'draft':[('readonly',False)]}, readonly=True),
98         'product_uos': fields.many2one('product.uom', 'Product UoS', states={'draft':[('readonly',False)]}, readonly=True),
99         'move_id': fields.many2one('stock.move', 'Reservation', ondelete='set null'),
100         'close_move': fields.boolean('Close Move at end'),
101         'location_id': fields.many2one('stock.location', 'Location', required=True, states={'draft':[('readonly',False)]}, readonly=True),
102         'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procurement Method', states={'draft':[('readonly',False)], 'confirmed':[('readonly',False)]},
103             readonly=True, required=True, help="If you encode manually a Procurement, you probably want to use" \
104             " a make to order method."),
105         'note': fields.text('Note'),
106         'message': fields.text('Latest error', help="Exception occurred while computing procurement orders."),
107         'state': fields.selection([
108             ('draft','Draft'),
109             ('cancel','Cancelled'),
110             ('confirmed','Confirmed'),
111             ('exception','Exception'),
112             ('running','Running'),
113             ('ready','Ready'),
114             ('done','Done'),
115             ('waiting','Waiting')], 'Status', required=True, track_visibility='onchange',
116             help='When a procurement is created the status is set to \'Draft\'.\n If the procurement is confirmed, the status is set to \'Confirmed\'.\
117             \nAfter confirming the status is set to \'Running\'.\n If any exception arises in the order then the status is set to \'Exception\'.\n Once the exception is removed the status becomes \'Ready\'.\n It is in \'Waiting\'. status when the procurement is waiting for another one to finish.'),
118         'note': fields.text('Note'),
119         'company_id': fields.many2one('res.company','Company',required=True),
120     }
121     _defaults = {
122         'state': 'draft',
123         'priority': '1',
124         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
125         'close_move': 0,
126         'procure_method': 'make_to_order',
127         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c)
128     }
129
130     def message_track(self, cr, uid, ids, tracked_fields, initial_values, context=None):
131         """ Overwrite message_track to avoid tracking more than once the confirm-exception loop
132         Add '_first_pass_done_' to the note field only the first time stuck in exception state
133         Will avoid getting furthur confirmed and exception change of state messages
134
135         TODO: this hack is necessary for a stable version but should be avoided for the next release.
136         Instead find a more elegant way to prevent redundant messages or entirely stop tracking states on procurement orders
137         """
138         for proc in self.browse(cr, uid, ids, context=context):
139             if not proc.note or '_first_pass_done_' not in proc.note or proc.state not in ('confirmed', 'exception'):
140                 super(procurement_order, self).message_track(cr, uid, [proc.id], tracked_fields, initial_values, context=context)
141                 if proc.state == 'exception':
142                     cr.execute("""UPDATE procurement_order set note = CONCAT(note, %s) WHERE id = %s""", ('_first_pass_done_',proc.id))
143
144         return True
145
146     def unlink(self, cr, uid, ids, context=None):
147         procurements = self.read(cr, uid, ids, ['state'], context=context)
148         unlink_ids = []
149         for s in procurements:
150             if s['state'] in ['draft','cancel']:
151                 unlink_ids.append(s['id'])
152             else:
153                 raise osv.except_osv(_('Invalid Action!'),
154                         _('Cannot delete Procurement Order(s) which are in %s state.') % \
155                         s['state'])
156         return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
157
158     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
159         """ Finds UoM and UoS of changed product.
160         @param product_id: Changed id of product.
161         @return: Dictionary of values.
162         """
163         if product_id:
164             w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
165             v = {
166                 'product_uom': w.uom_id.id,
167                 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
168             }
169             return {'value': v}
170         return {}
171
172     def is_product(self, cr, uid, ids, context=None):
173         """ Checks product type to decide which transition of the workflow to follow.
174         @return: True if all product ids received in argument are of type 'product' or 'consummable'. False if any is of type 'service'
175         """
176         return all(proc.product_id.type in ('product', 'consu') for proc in self.browse(cr, uid, ids, context=context))
177
178     def check_move_cancel(self, cr, uid, ids, context=None):
179         """ Checks if move is cancelled or not.
180         @return: True or False.
181         """
182         return all(procurement.move_id.state == 'cancel' for procurement in self.browse(cr, uid, ids, context=context))
183
184     #This Function is create to avoid  a server side Error Like 'ERROR:tests.mrp:name 'check_move' is not defined'
185     def check_move(self, cr, uid, ids, context=None):
186         pass
187
188     def check_move_done(self, cr, uid, ids, context=None):
189         """ Checks if move is done or not.
190         @return: True or False.
191         """
192         return all(proc.product_id.type == 'service' or (proc.move_id and proc.move_id.state == 'done') \
193                     for proc in self.browse(cr, uid, ids, context=context))
194
195     #
196     # This method may be overrided by objects that override procurement.order
197     # for computing their own purpose
198     #
199     def _quantity_compute_get(self, cr, uid, proc, context=None):
200         """ Finds sold quantity of product.
201         @param proc: Current procurement.
202         @return: Quantity or False.
203         """
204         if proc.product_id.type == 'product' and proc.move_id:
205             if proc.move_id.product_uos:
206                 return proc.move_id.product_uos_qty
207         return False
208
209     def _uom_compute_get(self, cr, uid, proc, context=None):
210         """ Finds UoS if product is Stockable Product.
211         @param proc: Current procurement.
212         @return: UoS or False.
213         """
214         if proc.product_id.type == 'product' and proc.move_id:
215             if proc.move_id.product_uos:
216                 return proc.move_id.product_uos.id
217         return False
218
219     #
220     # Return the quantity of product shipped/produced/served, which may be
221     # different from the planned quantity
222     #
223     def quantity_get(self, cr, uid, id, context=None):
224         """ Finds quantity of product used in procurement.
225         @return: Quantity of product.
226         """
227         proc = self.browse(cr, uid, id, context=context)
228         result = self._quantity_compute_get(cr, uid, proc, context=context)
229         if not result:
230             result = proc.product_qty
231         return result
232
233     def uom_get(self, cr, uid, id, context=None):
234         """ Finds UoM of product used in procurement.
235         @return: UoM of product.
236         """
237         proc = self.browse(cr, uid, id, context=context)
238         result = self._uom_compute_get(cr, uid, proc, context=context)
239         if not result:
240             result = proc.product_uom.id
241         return result
242
243     def check_waiting(self, cr, uid, ids, context=None):
244         """ Checks state of move.
245         @return: True or False
246         """
247         for procurement in self.browse(cr, uid, ids, context=context):
248             if procurement.move_id and procurement.move_id.state == 'auto':
249                 return True
250         return False
251
252     def check_produce_service(self, cr, uid, procurement, context=None):
253         """ Depicts the capacity of the procurement workflow to deal with production of services.
254             By default, it's False. Overwritten by project_mrp module.
255         """
256         return False
257
258     def check_produce_product(self, cr, uid, procurement, context=None):
259         """ Depicts the capacity of the procurement workflow to deal with production of products.
260             By default, it's False. Overwritten by mrp module.
261         """
262         return False
263
264     def check_make_to_stock(self, cr, uid, ids, context=None):
265         """ Checks product type.
266         @return: True or False
267         """
268         ok = True
269         for procurement in self.browse(cr, uid, ids, context=context):
270             if procurement.product_id.type == 'service':
271                 ok = ok and self._check_make_to_stock_service(cr, uid, procurement, context)
272             else:
273                 ok = ok and self._check_make_to_stock_product(cr, uid, procurement, context)
274         return ok
275
276     def check_produce(self, cr, uid, ids, context=None):
277         """ Checks product type.
278         @return: True or False
279         """
280         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
281         for procurement in self.browse(cr, uid, ids, context=context):
282             product = procurement.product_id
283             #TOFIX: if product type is 'service' but supply_method is 'buy'.
284             if product.supply_method <> 'produce':
285                 return False
286             if product.type=='service':
287                 res = self.check_produce_service(cr, uid, procurement, context)
288             else:
289                 res = self.check_produce_product(cr, uid, procurement, context)
290             if not res:
291                 return False
292         return True
293
294     def check_buy(self, cr, uid, ids):
295         """ Depicts the capacity of the procurement workflow to manage the supply_method == 'buy'.
296             By default, it's False. Overwritten by purchase module.
297         """
298         return False
299
300     def check_conditions_confirm2wait(self, cr, uid, ids):
301         """ condition on the transition to go from 'confirm' activity to 'confirm_wait' activity """
302         return not self.test_cancel(cr, uid, ids)
303
304     def test_cancel(self, cr, uid, ids):
305         """ Tests whether state of move is cancelled or not.
306         @return: True or False
307         """
308         for record in self.browse(cr, uid, ids):
309             if record.move_id and record.move_id.state == 'cancel':
310                 return True
311         return False
312
313     #Initialize get_phantom_bom_id method as it is raising an error from yml of mrp_jit
314     #when one install first mrp and after that, mrp_jit. get_phantom_bom_id defined in mrp module
315     #which is not dependent for mrp_jit.
316     def get_phantom_bom_id(self, cr, uid, ids, context=None):
317         return False
318
319     def action_confirm(self, cr, uid, ids, context=None):
320         """ Confirms procurement and writes exception message if any.
321         @return: True
322         """
323         move_obj = self.pool.get('stock.move')
324         for procurement in self.browse(cr, uid, ids, context=context):
325             if procurement.product_qty <= 0.00:
326                 raise osv.except_osv(_('Data Insufficient!'),
327                     _('Please check the quantity in procurement order(s) for the product "%s", it should not be 0 or less!' % procurement.product_id.name))
328             if procurement.product_id.type in ('product', 'consu'):
329                 if not procurement.move_id:
330                     source = procurement.location_id.id
331                     if procurement.procure_method == 'make_to_order':
332                         source = procurement.product_id.property_stock_procurement.id
333                     id = move_obj.create(cr, uid, {
334                         'name': procurement.name,
335                         'location_id': source,
336                         'location_dest_id': procurement.location_id.id,
337                         'product_id': procurement.product_id.id,
338                         'product_qty': procurement.product_qty,
339                         'product_uom': procurement.product_uom.id,
340                         'date_expected': procurement.date_planned,
341                         'state': 'draft',
342                         'company_id': procurement.company_id.id,
343                         'auto_validate': True,
344                     })
345                     move_obj.action_confirm(cr, uid, [id], context=context)
346                     self.write(cr, uid, [procurement.id], {'move_id': id, 'close_move': 1})
347         self.write(cr, uid, ids, {'state': 'confirmed', 'message': ''})
348         return True
349
350     def action_move_assigned(self, cr, uid, ids, context=None):
351         """ Changes procurement state to Running and writes message.
352         @return: True
353         """
354         message = _('Products reserved from stock.')
355         self.write(cr, uid, ids, {'state': 'running',
356                 'message': message}, context=context)
357         self.message_post(cr, uid, ids, body=message, context=context)
358         return True
359
360     def _check_make_to_stock_service(self, cr, uid, procurement, context=None):
361         """
362            This method may be overrided by objects that override procurement.order
363            for computing their own purpose
364         @return: True"""
365         return True
366
367     def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
368         """ Checks procurement move state.
369         @param procurement: Current procurement.
370         @return: True or move id.
371         """
372         ok = True
373         if procurement.move_id:
374             message = False
375             id = procurement.move_id.id
376             if not (procurement.move_id.state in ('done','assigned','cancel')):
377                 ok = ok and self.pool.get('stock.move').action_assign(cr, uid, [id])
378                 order_point_id = self.pool.get('stock.warehouse.orderpoint').search(cr, uid, [('product_id', '=', procurement.product_id.id)], context=context)
379                 if not order_point_id and not ok:
380                     message = _("Not enough stock and no minimum orderpoint rule defined.")
381                 elif not ok:
382                     message = _("Not enough stock.")
383
384                 if message:
385                     message = _("Procurement '%s' is in exception: ") % (procurement.name) + message
386                     #temporary context passed in write to prevent an infinite loop
387                     ctx_wkf = dict(context or {})
388                     ctx_wkf['workflow.trg_write.%s' % self._name] = False
389                     self.write(cr, uid, [procurement.id], {'message': message},context=ctx_wkf)
390         return ok
391
392     def step_workflow(self, cr, uid, ids, context=None):
393         """ Don't trigger workflow for the element specified in trigger """
394         wkf_op_key = 'workflow.trg_write.%s' % self._name
395         if context and not context.get(wkf_op_key, True):
396             # make sure we don't have a trigger loop while processing triggers
397             return 
398         return super(procurement_order, self).step_workflow(cr, uid, ids, context=context)
399
400     def action_produce_assign_service(self, cr, uid, ids, context=None):
401         """ Changes procurement state to Running.
402         @return: True
403         """
404         for procurement in self.browse(cr, uid, ids, context=context):
405             self.write(cr, uid, [procurement.id], {'state': 'running'})
406         return True
407
408     def action_produce_assign_product(self, cr, uid, ids, context=None):
409         """ This is action which call from workflow to assign production order to procurements
410         @return: True
411         """
412         return 0
413
414
415     def action_po_assign(self, cr, uid, ids, context=None):
416         """ This is action which call from workflow to assign purchase order to procurements
417         @return: True
418         """
419         return 0
420
421     # XXX action_cancel() should accept a context argument
422     def action_cancel(self, cr, uid, ids):
423         """Cancel Procurements and either cancel or assign the related Stock Moves, depending on the procurement configuration.
424         
425         @return: True
426         """
427         to_assign = []
428         to_cancel = []
429         move_obj = self.pool.get('stock.move')
430         for proc in self.browse(cr, uid, ids):
431             if proc.close_move and proc.move_id:
432                 if proc.move_id.state not in ('done', 'cancel'):
433                     to_cancel.append(proc.move_id.id)
434             else:
435                 if proc.move_id and proc.move_id.state == 'waiting':
436                     to_assign.append(proc.move_id.id)
437         if len(to_cancel):
438             move_obj.action_cancel(cr, uid, to_cancel)
439         if len(to_assign):
440             move_obj.write(cr, uid, to_assign, {'state': 'assigned'})
441         self.write(cr, uid, ids, {'state': 'cancel'})
442         wf_service = netsvc.LocalService("workflow")
443         for id in ids:
444             wf_service.trg_trigger(uid, 'procurement.order', id, cr)
445         return True
446
447     def action_check_finished(self, cr, uid, ids):
448         return self.check_move_done(cr, uid, ids)
449
450     def action_check(self, cr, uid, ids):
451         """ Checks procurement move state whether assigned or done.
452         @return: True
453         """
454         ok = False
455         for procurement in self.browse(cr, uid, ids):
456             if procurement.move_id and procurement.move_id.state == 'assigned' or procurement.move_id.state == 'done':
457                 self.action_done(cr, uid, [procurement.id])
458                 ok = True
459         return ok
460
461     def action_ready(self, cr, uid, ids):
462         """ Changes procurement state to Ready.
463         @return: True
464         """
465         res = self.write(cr, uid, ids, {'state': 'ready'})
466         return res
467
468     def action_done(self, cr, uid, ids):
469         """ Changes procurement state to Done and writes Closed date.
470         @return: True
471         """
472         move_obj = self.pool.get('stock.move')
473         for procurement in self.browse(cr, uid, ids):
474             if procurement.move_id:
475                 if procurement.close_move and (procurement.move_id.state <> 'done'):
476                     move_obj.action_done(cr, uid, [procurement.move_id.id])
477         res = self.write(cr, uid, ids, {'state': 'done', 'date_close': time.strftime('%Y-%m-%d')})
478         wf_service = netsvc.LocalService("workflow")
479         for id in ids:
480             wf_service.trg_trigger(uid, 'procurement.order', id, cr)
481         return res
482
483 class StockPicking(osv.osv):
484     _inherit = 'stock.picking'
485     def test_finished(self, cr, uid, ids):
486         res = super(StockPicking, self).test_finished(cr, uid, ids)
487         for picking in self.browse(cr, uid, ids):
488             for move in picking.move_lines:
489                 if move.state == 'done' and move.procurements:
490                     self.pool.get('procurement.order').signal_button_check(cr, uid, map(attrgetter('id'), move.procurements))
491         return res
492
493 class stock_warehouse_orderpoint(osv.osv):
494     """
495     Defines Minimum stock rules.
496     """
497     _name = "stock.warehouse.orderpoint"
498     _description = "Minimum Inventory Rule"
499
500     def _get_draft_procurements(self, cr, uid, ids, field_name, arg, context=None):
501         if context is None:
502             context = {}
503         result = {}
504         procurement_obj = self.pool.get('procurement.order')
505         for orderpoint in self.browse(cr, uid, ids, context=context):
506             procurement_ids = procurement_obj.search(cr, uid , [('state', '=', 'draft'), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)])
507             result[orderpoint.id] = procurement_ids
508         return result
509
510     def _check_product_uom(self, cr, uid, ids, context=None):
511         '''
512         Check if the UoM has the same category as the product standard UoM
513         '''
514         if not context:
515             context = {}
516             
517         for rule in self.browse(cr, uid, ids, context=context):
518             if rule.product_id.uom_id.category_id.id != rule.product_uom.category_id.id:
519                 return False
520             
521         return True
522
523     _columns = {
524         'name': fields.char('Name', size=32, required=True),
525         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
526         'logic': fields.selection([('max','Order to Max'),('price','Best price (not yet active!)')], 'Reordering Mode', required=True),
527         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
528         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
529         'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type','!=','service')]),
530         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
531         'product_min_qty': fields.float('Minimum Quantity', required=True,
532             help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
533             "a procurement to bring the forecasted quantity to the Max Quantity."),
534         'product_max_qty': fields.float('Maximum Quantity', required=True,
535             help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
536             "a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity."),
537         'qty_multiple': fields.integer('Qty Multiple', required=True,
538             help="The procurement quantity will be rounded up to this multiple."),
539         'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
540         'company_id': fields.many2one('res.company','Company',required=True),
541         'procurement_draft_ids': fields.function(_get_draft_procurements, type='many2many', relation="procurement.order", \
542                                 string="Related Procurement Orders",help="Draft procurement of the product and location of that orderpoint"),
543     }
544     _defaults = {
545         'active': lambda *a: 1,
546         'logic': lambda *a: 'max',
547         'qty_multiple': lambda *a: 1,
548         'name': lambda x,y,z,c: x.pool.get('ir.sequence').get(y,z,'stock.orderpoint') or '',
549         'product_uom': lambda sel, cr, uid, context: context.get('product_uom', False),
550         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=c)
551     }
552     _sql_constraints = [
553         ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
554     ]
555     _constraints = [
556         (_check_product_uom, 'You have to select a product unit of measure in the same category than the default unit of measure of the product', ['product_id', 'product_uom']),
557     ]
558
559     def default_get(self, cr, uid, fields, context=None):
560         res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
561         # default 'warehouse_id' and 'location_id'
562         if 'warehouse_id' not in res:
563             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
564             res['warehouse_id'] = warehouse.id
565         if 'location_id' not in res:
566             warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
567             res['location_id'] = warehouse.lot_stock_id.id
568         return res
569
570     def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
571         """ Finds location id for changed warehouse.
572         @param warehouse_id: Changed id of warehouse.
573         @return: Dictionary of values.
574         """
575         if warehouse_id:
576             w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
577             v = {'location_id': w.lot_stock_id.id}
578             return {'value': v}
579         return {}
580
581     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
582         """ Finds UoM for changed product.
583         @param product_id: Changed id of product.
584         @return: Dictionary of values.
585         """
586         if product_id:
587             prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
588             d = {'product_uom': [('category_id', '=', prod.uom_id.category_id.id)]}
589             v = {'product_uom': prod.uom_id.id}
590             return {'value': v, 'domain': d}
591         return {'domain': {'product_uom': []}}
592
593     def copy(self, cr, uid, id, default=None, context=None):
594         if not default:
595             default = {}
596         default.update({
597             'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
598         })
599         return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
600
601 class product_template(osv.osv):
602     _inherit="product.template"
603
604     _columns = {
605         '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."),
606         'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procurement Method', required=True, help="Make to Stock: When needed, the product is taken from the stock or we wait for replenishment. \nMake to Order: When needed, the product is purchased or produced."),
607         'supply_method': fields.selection([('produce','Manufacture'),('buy','Buy')], 'Supply Method', required=True, help="Manufacture: When procuring the product, a manufacturing order or a task will be generated, depending on the product type. \nBuy: When procuring the product, a purchase order will be generated."),
608     }
609     _defaults = {
610         'procure_method': 'make_to_stock',
611         'supply_method': 'buy',
612     }
613
614 class product_product(osv.osv):
615     _inherit="product.product"
616     _columns = {
617         'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
618     }
619
620
621
622 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: