[FIX] subtype_xml_id -> subtype in message_post.
[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 osv import osv, fields
23 from tools.translate import _
24 import netsvc
25 import time
26 import 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(self, cr, uid, id, default=None, context=None):
71         default = default or {}
72         default['procurements'] = []
73         return super(StockMove, self).copy(cr, uid, id, default, context=context)
74
75 StockMove()
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.char('Reason', size=64, required=True, help='Procurement name.'),
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', required=True),
101         'location_id': fields.many2one('stock.location', 'Location', required=True, states={'draft':[('readonly',False)]}, readonly=True),
102         'procure_method': fields.selection([('make_to_stock','from stock'),('make_to_order','on 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
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,
117             help='When a procurement is created the state is set to \'Draft\'.\n If the procurement is confirmed, the state is set to \'Confirmed\'.\
118             \nAfter confirming the state is set to \'Running\'.\n If any exception arises in the order then the state is set to \'Exception\'.\n Once the exception is removed the state becomes \'Ready\'.\n It is in \'Waiting\'. state 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 unlink(self, cr, uid, ids, context=None):
132         procurements = self.read(cr, uid, ids, ['state'], context=context)
133         unlink_ids = []
134         for s in procurements:
135             if s['state'] in ['draft','cancel']:
136                 unlink_ids.append(s['id'])
137             else:
138                 raise osv.except_osv(_('Invalid Action!'),
139                         _('Cannot delete Procurement Order(s) which are in %s state.') % \
140                         s['state'])
141         return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
142
143     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
144         """ Finds UoM and UoS of changed product.
145         @param product_id: Changed id of product.
146         @return: Dictionary of values.
147         """
148         if product_id:
149             w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
150             v = {
151                 'product_uom': w.uom_id.id,
152                 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
153             }
154             return {'value': v}
155         return {}
156
157     def check_product(self, cr, uid, ids, context=None):
158         """ Checks product type.
159         @return: True or False
160         """
161         return all(proc.product_id.type in ('product', 'consu') for proc in self.browse(cr, uid, ids, context=context))
162
163     def check_move_cancel(self, cr, uid, ids, context=None):
164         """ Checks if move is cancelled or not.
165         @return: True or False.
166         """
167         return all(procurement.move_id.state == 'cancel' for procurement in self.browse(cr, uid, ids, context=context))
168
169     #This Function is create to avoid  a server side Error Like 'ERROR:tests.mrp:name 'check_move' is not defined'
170     def check_move(self, cr, uid, ids, context=None):
171         pass
172
173     def check_move_done(self, cr, uid, ids, context=None):
174         """ Checks if move is done or not.
175         @return: True or False.
176         """
177         return all(proc.product_id.type == 'service' or (proc.move_id and proc.move_id.state == 'done') \
178                     for proc in self.browse(cr, uid, ids, context=context))
179
180     #
181     # This method may be overrided by objects that override procurement.order
182     # for computing their own purpose
183     #
184     def _quantity_compute_get(self, cr, uid, proc, context=None):
185         """ Finds sold quantity of product.
186         @param proc: Current procurement.
187         @return: Quantity or False.
188         """
189         if proc.product_id.type == 'product' and proc.move_id:
190             if proc.move_id.product_uos:
191                 return proc.move_id.product_uos_qty
192         return False
193
194     def _uom_compute_get(self, cr, uid, proc, context=None):
195         """ Finds UoS if product is Stockable Product.
196         @param proc: Current procurement.
197         @return: UoS or False.
198         """
199         if proc.product_id.type == 'product' and proc.move_id:
200             if proc.move_id.product_uos:
201                 return proc.move_id.product_uos.id
202         return False
203
204     #
205     # Return the quantity of product shipped/produced/served, which may be
206     # different from the planned quantity
207     #
208     def quantity_get(self, cr, uid, id, context=None):
209         """ Finds quantity of product used in procurement.
210         @return: Quantity of product.
211         """
212         proc = self.browse(cr, uid, id, context=context)
213         result = self._quantity_compute_get(cr, uid, proc, context=context)
214         if not result:
215             result = proc.product_qty
216         return result
217
218     def uom_get(self, cr, uid, id, context=None):
219         """ Finds UoM of product used in procurement.
220         @return: UoM of product.
221         """
222         proc = self.browse(cr, uid, id, context=context)
223         result = self._uom_compute_get(cr, uid, proc, context=context)
224         if not result:
225             result = proc.product_uom.id
226         return result
227
228     def check_waiting(self, cr, uid, ids, context=None):
229         """ Checks state of move.
230         @return: True or False
231         """
232         for procurement in self.browse(cr, uid, ids, context=context):
233             if procurement.move_id and procurement.move_id.state == 'auto':
234                 return True
235         return False
236
237     def check_produce_service(self, cr, uid, procurement, context=None):
238         return False
239
240     def check_produce_product(self, cr, uid, procurement, context=None):
241         """ Finds BoM of a product if not found writes exception message.
242         @param procurement: Current procurement.
243         @return: True or False.
244         """
245         return True
246
247     def check_make_to_stock(self, cr, uid, ids, context=None):
248         """ Checks product type.
249         @return: True or False
250         """
251         ok = True
252         for procurement in self.browse(cr, uid, ids, context=context):
253             if procurement.product_id.type == 'service':
254                 ok = ok and self._check_make_to_stock_service(cr, uid, procurement, context)
255             else:
256                 ok = ok and self._check_make_to_stock_product(cr, uid, procurement, context)
257         return ok
258
259     def check_produce(self, cr, uid, ids, context=None):
260         """ Checks product type.
261         @return: True or False
262         """
263         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
264         for procurement in self.browse(cr, uid, ids, context=context):
265             product = procurement.product_id
266             #TOFIX: if product type is 'service' but supply_method is 'buy'.
267             if product.supply_method <> 'produce':
268                 supplier = product.seller_id
269                 if supplier and user.company_id and user.company_id.partner_id:
270                     if supplier.id == user.company_id.partner_id.id:
271                         continue
272                 return False
273             if product.type=='service':
274                 res = self.check_produce_service(cr, uid, procurement, context)
275             else:
276                 res = self.check_produce_product(cr, uid, procurement, context)
277             if not res:
278                 return False
279         return True
280
281     def check_buy(self, cr, uid, ids):
282         """ Checks product type.
283         @return: True or Product Id.
284         """
285         user = self.pool.get('res.users').browse(cr, uid, uid)
286         partner_obj = self.pool.get('res.partner')
287         for procurement in self.browse(cr, uid, ids):
288             if procurement.product_id.product_tmpl_id.supply_method <> 'buy':
289                 return False
290             if not procurement.product_id.seller_ids:
291                 message = _('No supplier defined for this product !')
292                 self.message_post(cr, uid, [procurement.id], body=message)
293                 cr.execute('update procurement_order set message=%s where id=%s', (message, procurement.id))
294                 return False
295             partner = procurement.product_id.seller_id #Taken Main Supplier of Product of Procurement.
296
297             if not partner:
298                 message = _('No default supplier defined for this product')
299                 self.message_post(cr, uid, [procurement.id], body=message)
300                 cr.execute('update procurement_order set message=%s where id=%s', (message, procurement.id))
301                 return False
302             if user.company_id and user.company_id.partner_id:
303                 if partner.id == user.company_id.partner_id.id:
304                     return False
305
306             address_id = partner_obj.address_get(cr, uid, [partner.id], ['delivery'])['delivery']
307             if not address_id:
308                 message = _('No address defined for the supplier')
309                 self.message_post(cr, uid, [procurement.id], body=message)
310                 cr.execute('update procurement_order set message=%s where id=%s', (message, procurement.id))
311                 return False
312         return True
313
314     def test_cancel(self, cr, uid, ids):
315         """ Tests whether state of move is cancelled or not.
316         @return: True or False
317         """
318         for record in self.browse(cr, uid, ids):
319             if record.move_id and record.move_id.state == 'cancel':
320                 return True
321         return False
322
323     #Initialize get_phantom_bom_id method as it is raising an error from yml of mrp_jit
324     #when one install first mrp and after that, mrp_jit. get_phantom_bom_id defined in mrp module
325     #which is not dependent for mrp_jit.
326     def get_phantom_bom_id(self, cr, uid, ids, context=None):
327         return False
328
329     def action_confirm(self, cr, uid, ids, context=None):
330         """ Confirms procurement and writes exception message if any.
331         @return: True
332         """
333         move_obj = self.pool.get('stock.move')
334         for procurement in self.browse(cr, uid, ids, context=context):
335             if procurement.product_qty <= 0.00:
336                 raise osv.except_osv(_('Insufficient Data!'),
337                     _('Quantity in procurement order(s) must be greater than 0.'))
338             if procurement.product_id.type in ('product', 'consu'):
339                 if not procurement.move_id:
340                     source = procurement.location_id.id
341                     if procurement.procure_method == 'make_to_order':
342                         source = procurement.product_id.product_tmpl_id.property_stock_procurement.id
343                     id = move_obj.create(cr, uid, {
344                         'name': procurement.name,
345                         'location_id': source,
346                         'location_dest_id': procurement.location_id.id,
347                         'product_id': procurement.product_id.id,
348                         'product_qty': procurement.product_qty,
349                         'product_uom': procurement.product_uom.id,
350                         'date_expected': procurement.date_planned,
351                         'state': 'draft',
352                         'company_id': procurement.company_id.id,
353                         'auto_validate': True,
354                     })
355                     move_obj.action_confirm(cr, uid, [id], context=context)
356                     self.write(cr, uid, [procurement.id], {'move_id': id, 'close_move': 1})
357         self.write(cr, uid, ids, {'state': 'confirmed', 'message': ''})
358         self.confirm_send_note(cr, uid, ids, context)
359         return True
360
361     def action_move_assigned(self, cr, uid, ids, context=None):
362         """ Changes procurement state to Running and writes message.
363         @return: True
364         """
365         message = _('From stock: products assigned.')
366         self.write(cr, uid, ids, {'state': 'running',
367                 'message': message}, context=context)
368         self.message_post(cr, uid, ids, body=message, context=context)
369         self.running_send_note(cr, uid, ids, context=context)
370         return True
371
372     def _check_make_to_stock_service(self, cr, uid, procurement, context=None):
373         """
374            This method may be overrided by objects that override procurement.order
375            for computing their own purpose
376         @return: True"""
377         return True
378
379     def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
380         """ Checks procurement move state.
381         @param procurement: Current procurement.
382         @return: True or move id.
383         """
384         ok = True
385         if procurement.move_id:
386             message = False
387             id = procurement.move_id.id
388             if not (procurement.move_id.state in ('done','assigned','cancel')):
389                 ok = ok and self.pool.get('stock.move').action_assign(cr, uid, [id])
390                 order_point_id = self.pool.get('stock.warehouse.orderpoint').search(cr, uid, [('product_id', '=', procurement.product_id.id)], context=context)
391                 if not order_point_id and not ok:
392                     message = _("Not enough stock and no minimum orderpoint rule defined.")
393                 elif not order_point_id:
394                     message = _("No minimum orderpoint rule defined.")
395                 elif not ok:
396                     message = _("Not enough stock.")
397
398                 if message:
399                     message = _("Procurement '%s' is in exception: ") % (procurement.name) + message
400                     cr.execute('update procurement_order set message=%s where id=%s', (message, procurement.id))
401                     self.message_post(cr, uid, [procurement.id], body=message, context=context)
402         return ok
403
404     def action_produce_assign_service(self, cr, uid, ids, context=None):
405         """ Changes procurement state to Running.
406         @return: True
407         """
408         for procurement in self.browse(cr, uid, ids, context=context):
409             self.write(cr, uid, [procurement.id], {'state': 'running'})
410         self.running_send_note(cr, uid, ids, context=None)
411         return True
412
413     def action_produce_assign_product(self, cr, uid, ids, context=None):
414         """ This is action which call from workflow to assign production order to procurements
415         @return: True
416         """
417         return 0
418
419
420     def action_po_assign(self, cr, uid, ids, context=None):
421         """ This is action which call from workflow to assign purchase order to procurements
422         @return: True
423         """
424         return 0
425
426     def action_cancel(self, cr, uid, ids):
427         """ Cancels procurement and writes move state to Assigned.
428         @return: True
429         """
430         todo = []
431         todo2 = []
432         move_obj = self.pool.get('stock.move')
433         for proc in self.browse(cr, uid, ids):
434             if proc.close_move and proc.move_id:
435                 if proc.move_id.state not in ('done', 'cancel'):
436                     todo2.append(proc.move_id.id)
437             else:
438                 if proc.move_id and proc.move_id.state == 'waiting':
439                     todo.append(proc.move_id.id)
440         if len(todo2):
441             move_obj.action_cancel(cr, uid, todo2)
442         if len(todo):
443             move_obj.write(cr, uid, todo, {'state': 'assigned'})
444         self.write(cr, uid, ids, {'state': 'cancel'})
445         self.cancel_send_note(cr, uid, ids, context=None)
446         wf_service = netsvc.LocalService("workflow")
447         for id in ids:
448             wf_service.trg_trigger(uid, 'procurement.order', id, cr)
449         return True
450
451     def action_check_finished(self, cr, uid, ids):
452         return self.check_move_done(cr, uid, ids)
453
454     def action_check(self, cr, uid, ids):
455         """ Checks procurement move state whether assigned or done.
456         @return: True
457         """
458         ok = False
459         for procurement in self.browse(cr, uid, ids):
460             if procurement.move_id and procurement.move_id.state == 'assigned' or procurement.move_id.state == 'done':
461                 self.action_done(cr, uid, [procurement.id])
462                 ok = True
463         return ok
464
465     def action_ready(self, cr, uid, ids):
466         """ Changes procurement state to Ready.
467         @return: True
468         """
469         res = self.write(cr, uid, ids, {'state': 'ready'})
470         self.ready_send_note(cr, uid, ids, context=None)
471         return res
472
473     def action_done(self, cr, uid, ids):
474         """ Changes procurement state to Done and writes Closed date.
475         @return: True
476         """
477         move_obj = self.pool.get('stock.move')
478         for procurement in self.browse(cr, uid, ids):
479             if procurement.move_id:
480                 if procurement.close_move and (procurement.move_id.state <> 'done'):
481                     move_obj.action_done(cr, uid, [procurement.move_id.id])
482         res = self.write(cr, uid, ids, {'state': 'done', 'date_close': time.strftime('%Y-%m-%d')})
483         self.done_send_note(cr, uid, ids, context=None)
484         wf_service = netsvc.LocalService("workflow")
485         for id in ids:
486             wf_service.trg_trigger(uid, 'procurement.order', id, cr)
487         return res
488
489     # ----------------------------------------
490     # OpenChatter methods and notifications
491     # ----------------------------------------
492
493     def create(self, cr, uid, vals, context=None):
494         obj_id = super(procurement_order, self).create(cr, uid, vals, context)
495         self.create_send_note(cr, uid, [obj_id], context=context)
496         return obj_id
497
498     def create_send_note(self, cr, uid, ids, context=None):
499         self.message_post(cr, uid, ids, body=_("Procurement has been <b>created</b>."), subtype="procurement_subtype_new", context=context)
500
501     def confirm_send_note(self, cr, uid, ids, context=None):
502         self.message_post(cr, uid, ids, body=_("Procurement has been <b>confirmed</b>."), subtype="procurement_subtype_confirmed", context=context)
503
504     def running_send_note(self, cr, uid, ids, context=None):
505         self.message_post(cr, uid, ids, body=_("Procurement has been set to <b>running</b>."), subtype="procurement_subtype_running", context=context)
506
507     def ready_send_note(self, cr, uid, ids, context=None):
508         self.message_post(cr, uid, ids, body=_("Procurement has been set to <b>ready</b>."), subtype="procurement_subtype_ready", context=context)
509
510     def cancel_send_note(self, cr, uid, ids, context=None):
511         self.message_post(cr, uid, ids, body=_("Procurement has been <b>cancelled</b>."), subtype="procurement_subtype_cancelled", context=context)
512
513     def done_send_note(self, cr, uid, ids, context=None):
514         self.message_post(cr, uid, ids, body=_("Procurement has been <b>done</b>."), subtype="procurement_subtype_closed", context=context)
515
516 procurement_order()
517
518 class StockPicking(osv.osv):
519     _inherit = 'stock.picking'
520
521     def test_finished(self, cursor, user, ids):
522         wf_service = netsvc.LocalService("workflow")
523         res = super(StockPicking, self).test_finished(cursor, user, ids)
524         for picking in self.browse(cursor, user, ids):
525             for move in picking.move_lines:
526                 if move.state == 'done' and move.procurements:
527                     for procurement in move.procurements:
528                         wf_service.trg_validate(user, 'procurement.order',
529                             procurement.id, 'button_check', cursor)
530         return res
531
532 StockPicking()
533
534 class stock_warehouse_orderpoint(osv.osv):
535     """
536     Defines Minimum stock rules.
537     """
538     _name = "stock.warehouse.orderpoint"
539     _description = "Minimum Inventory Rule"
540
541     def _get_draft_procurements(self, cr, uid, ids, field_name, arg, context=None):
542         if context is None:
543             context = {}
544         result = {}
545         procurement_obj = self.pool.get('procurement.order')
546         for orderpoint in self.browse(cr, uid, ids, context=context):
547             procurement_ids = procurement_obj.search(cr, uid , [('state', '=', 'draft'), ('product_id', '=', orderpoint.product_id.id), ('location_id', '=', orderpoint.location_id.id)])
548             result[orderpoint.id] = procurement_ids
549         return result
550
551     _columns = {
552         'name': fields.char('Name', size=32, required=True),
553         'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the orderpoint without removing it."),
554         'logic': fields.selection([('max','Order to Max'),('price','Best price (not yet active!)')], 'Reordering Mode', required=True),
555         'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, ondelete="cascade"),
556         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete="cascade"),
557         'product_id': fields.many2one('product.product', 'Product', required=True, ondelete='cascade', domain=[('type','!=','service')]),
558         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
559         'product_min_qty': fields.float('Minimum Quantity', required=True,
560             help="When the virtual stock goes below the Min Quantity specified for this field, OpenERP generates "\
561             "a procurement to bring the virtual stock to the Max Quantity."),
562         'product_max_qty': fields.float('Maximum Quantity', required=True,
563             help="When the virtual stock goes below the Min Quantity, OpenERP generates "\
564             "a procurement to bring the virtual stock to the Quantity specified as Max Quantity."),
565         'qty_multiple': fields.integer('Qty Multiple', required=True,
566             help="The procurement quantity will be rounded up to this multiple."),
567         'procurement_id': fields.many2one('procurement.order', 'Latest procurement', ondelete="set null"),
568         'company_id': fields.many2one('res.company','Company',required=True),
569         'procurement_draft_ids': fields.function(_get_draft_procurements, type='many2many', relation="procurement.order", \
570                                 string="Related Procurement Orders",help="Draft procurement of the product and location of that orderpoint"),
571     }
572     _defaults = {
573         'active': lambda *a: 1,
574         'logic': lambda *a: 'max',
575         'qty_multiple': lambda *a: 1,
576         'name': lambda x,y,z,c: x.pool.get('ir.sequence').get(y,z,'stock.orderpoint') or '',
577         'product_uom': lambda sel, cr, uid, context: context.get('product_uom', False),
578         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.orderpoint', context=c)
579     }
580     _sql_constraints = [
581         ('qty_multiple_check', 'CHECK( qty_multiple > 0 )', 'Qty Multiple must be greater than zero.'),
582     ]
583
584     def default_get(self, cr, uid, fields, context=None):
585         res = super(stock_warehouse_orderpoint, self).default_get(cr, uid, fields, context)
586         # default 'warehouse_id' and 'location_id'
587         if 'warehouse_id' not in res:
588             warehouse = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'warehouse0', context)
589             res['warehouse_id'] = warehouse.id
590         if 'location_id' not in res:
591             warehouse = self.pool.get('stock.warehouse').browse(cr, uid, res['warehouse_id'], context)
592             res['location_id'] = warehouse.lot_stock_id.id
593         return res
594
595     def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
596         """ Finds location id for changed warehouse.
597         @param warehouse_id: Changed id of warehouse.
598         @return: Dictionary of values.
599         """
600         if warehouse_id:
601             w = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
602             v = {'location_id': w.lot_stock_id.id}
603             return {'value': v}
604         return {}
605
606     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
607         """ Finds UoM for changed product.
608         @param product_id: Changed id of product.
609         @return: Dictionary of values.
610         """
611         if product_id:
612             prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
613             v = {'product_uom': prod.uom_id.id}
614             return {'value': v}
615         return {}
616
617     def copy(self, cr, uid, id, default=None, context=None):
618         if not default:
619             default = {}
620         default.update({
621             'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.orderpoint') or '',
622         })
623         return super(stock_warehouse_orderpoint, self).copy(cr, uid, id, default, context=context)
624
625 stock_warehouse_orderpoint()
626
627 class product_product(osv.osv):
628     _inherit="product.product"
629     _columns = {
630         'orderpoint_ids': fields.one2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules'),
631     }
632
633 product_product()
634
635 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: