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