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