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